#!/usr/bin/python
# -*- tab-width: 4; indent-tabs-mode: nil -*-

import sys, os, getopt, logging, re, string, Queue, locale

import gtk, gobject, pango

# workaround for segfault if we try to load them later
try:
    import gnome, gnome.ui, gnomevfs
except:
    pass

if __name__ == '__main__' and hasattr(sys.modules['__main__'], '__file__'):
    basedir = os.path.dirname(os.path.abspath(__file__))
    up_basedir = os.path.dirname(basedir)
    if os.path.basename(basedir) == 'ui':
        def _pathext(path):
            if os.access(path, os.R_OK):
                sys.path.insert(0, path)
        _pathext('externals/pygtk-shell')

		print "Running uninstalled, extending PYTHONPATH with: %s" % (up_basedir,)
        sys.path.insert(0, up_basedir)
        # Extend PATH so hotwire-editor works correctly
        os.environ['PYTHONPATH'] = os.pathsep.join(sys.path)
        os.environ['PATH'] = (basedir + os.pathsep + os.environ.get('PATH', ''))
        os.environ['HOTWIRE_UNINSTALLED'] = up_basedir

try:
    import psyco
    psyco.full() 
except:
    pass

if sys.version_info[0] == 2 and sys.version_info[1] < 6:
    import hotwire.pycompat.webbrowser as webbrowser
else:
    import webbrowser

_logger = logging.getLogger("hotwire.Main")

def on_about_dialog_url(dialog, link):
    webbrowser.open(link)

def usage(ver, svnstr):
    sys.stdout.write('Hotwire %s %s\n' % (ver, svnstr))
    sys.stdout.write("%s [--debug] [--debug-modules=mod1,mod2...] [--help]\n" % (sys.argv[0],))

def main():
	import hotwire
	from hotwire.version import __version__, svn_version_str
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hdsn", ["help", "debug", "debug-modules=", "thread-debug",
                                                          "no-persist",
                                                          "minion-debug",
                                                          "minion-thread-debug"])
    except getopt.GetoptError:
        usage(__version__, svn_version_str())
        sys.exit(2)

    debug = False
    debug_modules = []
    thread_debug = False
    minion_debug = False
    minion_thread_debug = False
    no_persist = False
    for o, v in opts:
        if o in ('-d', '--debug'):
            debug = True
        elif o in ('--debug-modules'):
            debug_modules = v.split(',')
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ('-n', '--no-persist'):
            no_persist = True
        elif o in ('--thread-debug',):
            thread_debug = True
        elif o in ('--minion-debug',):
            minion_debug = True
        elif o in ('--minion-thread-debug',):
            minion_thread_debug = True

    default_log_level = logging.WARNING
    if debug:
        default_log_level = logging.DEBUG
 
	import hotwire.logutil
    hotwire.logutil.init(default_log_level, debug_modules, 'hotwire.')

    _logger.debug("logging initialized, debug: %s", __debug__)

    locale.setlocale(locale.LC_ALL, '')

    if thread_debug:
        hotwire.util.start_thread_dump_task(7000, sys.stderr)
    if minion_thread_debug:
        hotwire.minion.thread_debug = True
    if minion_debug:
        hotwire.minion.minion_debug = True

	# Do all these imports after we've initialized the basics, like logging

	import hotwire.sysdep
	import hotwire.config
	import hotwire.pluginsystem
	import hotwire.util
	from hotwire_ui.shell import HotWindowFactory
	from hotwire.persist import Persister

	try:
    	from hotwire.sysdep.ipc import Ipc
    	ipc_avail = True
	except NotImplementedError, e:
    	ipc_avail = False

    ipc = None
    if not ipc_avail:
        _logger.warn("No IPC subsystem available for this platform")
    elif not no_persist:
        ipc = Ipc.getInstance()
        try:
            hotw_exists = ipc.singleton()
            if hotw_exists:
                _logger.info("Existing Hotwire instance detected")
                ipc.new_window()
                gtk.gdk.notify_startup_complete()
                sys.exit(0)
        except NotImplementedError, e:
            _logger.warn("No IPC subsystem available for this platform")
            pass

    # We move to the root directory to make debugging things which don't
    # use hotwire.get_cwd() easier
    os.chdir('/')

    _logger.debug('initializing threads')
    gobject.threads_init()

    import gettext
    gettext.install('hotwire')

	hotwire.sysdep.do_late_init()

    if no_persist:
        Persister.getInstance().disable()
        
    hotwire.pluginsystem.load_plugins()

    # Random global GTK+-related initialization
    gtk.about_dialog_set_url_hook(on_about_dialog_url)
    gtk.rc_parse_string('''
style "hotwire-tab-close" {
  xthickness = 0
  ythickness = 0
}
widget "*hotwire-tab-close" style "hotwire-tab-close"
''')

    if os.getenv('HOTWIRE_UNINSTALLED'):
        theme = gtk.icon_theme_get_default()
        imgpath = os.path.join(os.getenv('HOTWIRE_UNINSTALLED'), 'images')
        _logger.debug("appending to icon theme: %s", imgpath)
        theme.append_search_path(imgpath)

    w = HotWindowFactory.getInstance().create_initial_window(subtitle=(no_persist and _(' (Unshared)') or ''))
    w.show()
    if ipc_avail and (not no_persist):
        ipc.register_window(w)

    gtk.gdk.notify_startup_complete()

    _logger.debug('entering mainloop')
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()

    Persister.getInstance().flush()

if __name__ == "__main__":
    main()
