#!/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__'):
    if os.path.basename(os.path.dirname(__file__)) == 'ui':
        def _pathext(path):
            if os.access(path, os.R_OK):
                sys.path.insert(0, path)
        _pathext('externals/pygtk-shell')
        sys.path.insert(0, '.')
import hotwire
import hotwire.sysdep
import hotwire.config
import hotwire.pluginsystem
import hotwire.logutil
import hotwire.util
from hotwire_ui.shell import HotWindowFactory
from hotwire.persist import Persister
from hotwire.version import __version__, svn_version_str

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

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

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

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

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

def main():
    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()
        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

    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

    # read config before chdir
    hotwire.config.Config.getInstance()

    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()

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

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

    # Random global GTK+-related initialization
    gtk.settings_get_default().set_property('gtk-key-theme-name',  'Emacs')
    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"
''')

    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()
