#!/usr/bin/env python
#
# This file is part of MyPaint.
# Copyright (C) 2007 by Martin Renold <martinxyz@gmx.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY. See the COPYING file for more details.

#import psyco
#psyco.full()

import gtk, sys, os, os.path
gdk = gtk.gdk

# autodetect prefix
# this allow relocatable version

#standard values
data='/share/mypaint'
lib='/lib/python%d.%d/site-packages/mypaint/' % (sys.version_info[0], sys.version_info[1])
pwd=os.getcwd()
curdir=os.path.dirname(sys.argv[0])

# script is installed as $prefix/bin. I just need $prefix to continue.
dir_install=os.path.normpath(os.path.join(pwd,curdir))

if os.path.basename(dir_install) == 'bin':
    prefix=os.path.dirname(dir_install)
    share=prefix+data
    sys.path.insert(0, prefix + lib)
    sys.path.insert(0, share + '/python')
else:
    # we are not installed, use .libs/mydrawwidget.so
    sys.path.insert(0,'.libs')
    prefix=None
    share='.'
    # checking for import error below

try: # just for a nice error message, plus portability test
    from mydrawwidget import MyBrush
    b = MyBrush()
    b.srandom(0xf4a1)
    b.random_double()
    b.random_double()
    val = b.random_double()
    if abs(val - 0.37175135167) > 1e-10:
        print val
        print 'Warning: the pseudo random generator did not generate the expected sequence.'
        print 'You should be able to use mypaint normally, but files (stroke replays) saved'
        print 'on a different system will have a different randomness, thus look different.'
        print 'Please report this together with your glib version and CPU architecture.'
        print
    assert val >= 0.0
    assert val <= 1.0
    del MyBrush
except ImportError, detail:
    print 'ImportError:', detail
    print "\nWe are not correctly installed or compiled!"
    print 'script = "%s"' % sys.argv[0]
    print 'dir_install = "%s"' % dir_install
    print "\nYou need to './configure && make' the C modules first.\n"
    if 'cannot import name' in str(detail).lower():
        print "Maybe try 'python mypaint' instead of './mypaint'.\n"
    sys.exit(1)

import application

def init_input():
    "make those pressure sensitive devices working"
    pressure_devices = []
    for device in gdk.devices_list():
        #if device.source in [gdk.SOURCE_PEN, gdk.SOURCE_ERASER]:
        # The above seems to be True sometimes for a normal
        # USB Mouse (bug #11215). Using different check now:
        for use, val_min, val_max in device.axes:
            if use == gdk.AXIS_PRESSURE:
                pressure_devices.append(device)
                break

    if pressure_devices:
        print 'Setting "screen mode" for pressure sensitive devices:'
        for device in pressure_devices:
            print device.name
            device.set_mode(gdk.MODE_SCREEN)
    else:
        print 'No pressure sensitive devices found.'


def main():

    def usage_exit():
        print sys.argv[0], '[OPTION]... [FILENAME]'
        print 'Options:'
        print '  -c /path/to/config   use this directory instead of ~/.mypaint/'
        sys.exit(1)

    homepath =  os.path.expanduser('~')
    if homepath == '~':
        confpath = os.path.join(prefix, 'UserData')
    else:
        confpath = os.path.join(homepath, '.mypaint/')

    print 'confpath =', confpath
    filename = None

    args = sys.argv[1:]
    while args:
        if args[0] == '-c':
            confpath = args[1]
            args = args[2:]
        elif args[0].startswith('-'):
            usage_exit()
        else:
            if filename:
                print 'Cannot open more than one file!'
                sys.exit(2)
            filename = args[0]
            if not os.path.isfile(filename):
                print 'File', filename, 'does not exist!'
                sys.exit(2)
            args = args[1:]

    init_input()
    app = application.Application(share, confpath, filename)

    # Recent gtk versions don't allow changing those menu shortcuts by
    # default. <rant>Sigh. This very useful feature used to be the
    # default behaviour even in the GIMP some time ago. I guess
    # assigning a keyboard shortcut without a complicated dialog
    # clicking marathon must have totally upset the people coming from
    # windows.</rant>
    gtksettings = gtk.settings_get_default()
    gtksettings.set_property('gtk-can-change-accels', True)

    gtk.main()

if __name__ == '__main__':
    main()

