Example #1
0
    def context_reload(self):
        self.context = {}
        self.timezone = 'utc'
        self.context = self.rpc_exec_auth('/object', 'execute', 'res.users', 'context_get') or {}
        if 'lang' in self.context:
            import translate
            translate.setlang(self.context['lang'])
            options.options['client.lang'] = self.context['lang']
            lang_ids = self.rpc_exec_auth('/object', 'execute', 'res.lang', 'search', [('code', '=', self.context['lang'])])
            if lang_ids:
                lang_data = self.rpc_exec_auth('/object', 'execute', 'res.lang', 'read', lang_ids, ['date_format', 'time_format', 'grouping', 'decimal_point', 'thousands_sep','direction'])
                if lang_data and 'direction' in lang_data[0]:
                    common.DIRECTION = lang_data[0]['direction']
                    import gtk
                    if common.DIRECTION == 'rtl':
                        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
                    else:
                        gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
                tools.user_locale_format.set_locale_cache(lang_data and lang_data[0] or {})

        if self.context.get('tz'):
            # FIXME: Timezone handling
            #   rpc_session.timezone contains the server's idea of its timezone (from time.tzname[0]),
            #   which is quite quite unreliable in some cases. We'll fix this in trunk.
            self.timezone = self.rpc_exec_auth('/common', 'timezone_get')
            try:
                import pytz
                pytz.timezone(self.timezone)
            except pytz.UnknownTimeZoneError:
                # Server timezone is not recognized!
                # Time values will be displayed as if located in the server timezone. (nothing we can do)
                pass
Example #2
0
    def showWindow(self):
        # self.readConfig()

        gtk.rc_add_default_file(resource_path("gtkrc"))
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)

        # Set the Glade file
        self.builder = gtk.Builder()

        translated_glade = resource_path("main.glade")
        self.builder.add_from_file(translated_glade)

        # Get the Main Window, and connect the "destroy" event
        self.window = self.builder.get_object("MainWindow")

        if self.window:
            self.window.connect("destroy", self.destroy)

        self.window.set_border_width(1)

        # self.builder.get_object("notebook1").set_current_page(1)

        # self.add_methods_tree()

        self.builder.connect_signals(self)

        self.my_init()

        self.window.show_all()
Example #3
0
 def context_reload(self):
     self.context = {}
     self.timezone = 'utc'
     self.context = self.rpc_exec_auth('/object', 'execute', 'res.users', 'context_get') or {}
     if 'lang' in self.context:
         import translate
         translate.setlang(self.context['lang'])
         options.options['client.lang']=self.context['lang']
         ids = self.rpc_exec_auth('/object', 'execute', 'res.lang', 'search', [('code', '=', self.context['lang'])])
         if ids:
             l = self.rpc_exec_auth('/object', 'execute', 'res.lang', 'read', ids, ['direction'])
             if l and 'direction' in l[0]:
                 common.DIRECTION = l[0]['direction']
                 import gtk
                 if common.DIRECTION == 'rtl':
                     gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
                 else:
                     gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
     if self.context.get('tz'):
         # FIXME: Timezone handling
         #   rpc_session.timezone contains the server's idea of its timezone (from time.tzname[0]),
         #   which is quite quite unreliable in some cases. We'll fix this in trunk.
         self.timezone = self.rpc_exec_auth('/common', 'timezone_get')
         try:
             pytz.timezone(self.timezone)
         except pytz.UnknownTimeZoneError:
             # Server timezone is not recognized!
             # Time values will be displayed as if located in the server timezone. (nothing we can do)
             pass
Example #4
0
 def applyFormatSetting(self, sender):
     langindex = self.langlist.get_active()
     if langindex != config.localelist.index(config.locale):
         config.locale = config.localelist[langindex]
         self.emit("locale-changed", config.locale)
         
         if config.directionlist[langindex] == "rtl":
             gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
         else:
             gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
         
     config.datetype = self.dateformat.get_active()
     config.datedelim = self.delimiter.get_active()
     config.dateorder = self.dateorder.get_active()
     for i in range(0,3):
         field = config.dateorders[config.dateorder][i]
         config.datefields[field] = i
     if self.uselatin.get_active() == True:
         config.digittype = 0
     else:
         config.digittype = 1
         
     msgbox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, 
                                _("Format settings changed successfully.") )
     msgbox.set_title(_("Successfully changed"))
     msgbox.run()
     msgbox.destroy()
Example #5
0
def run():
    """Run the program."""

    open_path = None
    open_page = 1
    argv = portability.get_commandline_args()
    opts, args = parse_arguments(argv)

    # First things first: set the log level.
    log.setLevel(opts.loglevel)

    if not os.path.exists(constants.DATA_DIR):
        os.makedirs(constants.DATA_DIR, 0700)

    if not os.path.exists(constants.CONFIG_DIR):
        os.makedirs(constants.CONFIG_DIR, 0700)

    from mcomix import icons
    icons.load_icons()

    if len(args) == 1:
        open_path = args[0]
    elif len(args) > 1:
        open_path = args

    elif preferences.prefs['auto load last file'] \
        and preferences.prefs['path to last file'] \
        and os.path.isfile(preferences.prefs['path to last file']):
        open_path = preferences.prefs['path to last file']
        open_page = preferences.prefs['page of last file']

    # Some languages require a RTL layout
    if preferences.prefs['language'] in ('he', 'fa'):
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)

    gtk.gdk.set_program_class(constants.APPNAME)

    from mcomix import main
    window = main.MainWindow(fullscreen = opts.fullscreen, is_slideshow = opts.slideshow,
            show_library = opts.library, manga_mode = opts.manga,
            double_page = opts.doublepage, zoom_mode = opts.zoommode,
            open_path = open_path, open_page = open_page)
    main.set_main_window(window)

    if 'win32' != sys.platform:
        # Add a SIGCHLD handler to reap zombie processes.
        def on_sigchld(signum, frame):
            try:
                os.waitpid(-1, os.WNOHANG)
            except OSError:
                pass
        signal.signal(signal.SIGCHLD, on_sigchld)

    signal.signal(signal.SIGTERM, lambda: gobject.idle_add(window.terminate_program))
    try:
        gtk.main()
    except KeyboardInterrupt: # Will not always work because of threading.
        window.terminate_program()
Example #6
0
def run():
    """Run the program."""

    open_path = None
    open_page = 1
    argv = portability.get_commandline_args()
    opts, args = parse_arguments(argv)

    if not os.path.exists(constants.DATA_DIR):
        os.makedirs(constants.DATA_DIR, 0700)

    if not os.path.exists(constants.CONFIG_DIR):
        os.makedirs(constants.CONFIG_DIR, 0700)

    icons.load_icons()

    if len(args) == 1:
        open_path = args[0]
    elif len(args) > 1:
        open_path = args

    elif preferences.prefs['auto load last file'] \
        and os.path.isfile(preferences.prefs['path to last file']):
        open_path = preferences.prefs['path to last file']
        open_page = preferences.prefs['page of last file']

    log.setLevel(opts.loglevel)

    # Some languages require a RTL layout
    if preferences.prefs['language'] in ('he', 'fa'):
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)

    gtk.gdk.set_program_class(constants.APPNAME)

    window = main.MainWindow(fullscreen=opts.fullscreen,
                             is_slideshow=opts.slideshow,
                             show_library=opts.library,
                             manga_mode=opts.manga,
                             double_page=opts.doublepage,
                             zoom_mode=opts.zoommode,
                             open_path=open_path,
                             open_page=open_page)
    main.set_main_window(window)

    signal.signal(signal.SIGTERM,
                  lambda: gobject.idle_add(window.terminate_program))
    try:
        gtk.main()
    except KeyboardInterrupt:  # Will not always work because of threading.
        window.terminate_program()
Example #7
0
def run():
    """Run the program."""

    open_path = None
    open_page = 1
    argv = portability.get_commandline_args()
    opts, args = parse_arguments(argv)

    if not os.path.exists(constants.DATA_DIR):
        os.makedirs(constants.DATA_DIR, 0700)

    if not os.path.exists(constants.CONFIG_DIR):
        os.makedirs(constants.CONFIG_DIR, 0700)

    icons.load_icons()

    if len(args) == 1:
        open_path = args[0]
    elif len(args) > 1:
        open_path = args

    elif preferences.prefs['auto load last file'] \
        and os.path.isfile(preferences.prefs['path to last file']):
        open_path = preferences.prefs['path to last file']
        open_page = preferences.prefs['page of last file']

    log.setLevel(opts.loglevel)

    # Some languages require a RTL layout
    if preferences.prefs['language'] in ('he', 'fa'):
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)

    gtk.gdk.set_program_class(constants.APPNAME)

    window = main.MainWindow(fullscreen = opts.fullscreen, is_slideshow = opts.slideshow,
            show_library = opts.library, manga_mode = opts.manga,
            double_page = opts.doublepage, zoom_mode = opts.zoommode,
            open_path = open_path, open_page = open_page)
    main.set_main_window(window)

    signal.signal(signal.SIGTERM, lambda: gobject.idle_add(window.terminate_program))
    try:
        gtk.main()
    except KeyboardInterrupt: # Will not always work because of threading.
        window.terminate_program()
Example #8
0
    def on_language_selection_changed(self, *args, **kwargs):
        lang = self.get_language()
        if not lang:
            return
        # strip encoding; we use UTF-8 internally no matter what
        lang = lang.split(".")[0]
        self.controller.translate(lang)
        import gtk

        ltr = i18n.get_string("default-ltr", lang, "ubiquity/imported")
        if ltr == "default:RTL":
            gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
        else:
            gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
        if not self.only:
            release_name = misc.get_release_name()
            install_medium = misc.get_install_medium()
            install_medium = i18n.get_string(install_medium, lang)
            for widget in (
                self.try_text_label,
                self.try_ubuntu,
                self.install_ubuntu,
                self.ready_text_label,
                self.alpha_warning_label,
            ):
                text = i18n.get_string(gtk.Buildable.get_name(widget), lang)
                text = text.replace("${RELEASE}", release_name)
                text = text.replace("${MEDIUM}", install_medium)
                widget.set_label(text)

            if self.release_notes_label:
                if self.release_notes_url and self.update_installer:
                    pass
                elif self.release_notes_url:
                    text = i18n.get_string("release_notes_only", lang)
                    self.release_notes_label.set_markup(text)
                elif self.update_installer:
                    text = i18n.get_string("update_installer_only", lang)
                    self.release_notes_label.set_markup(text)
                else:
                    self.release_notes_label.hide()
            for w in self.page.get_children():
                w.show()
Example #9
0
 def applyFormatSetting(self):
     langindex = self.langlist.get_active()
     if langindex != config.localelist.index(config.locale):
         config.locale = config.localelist[langindex]
         self.emit("locale-changed", config.locale)
         
         if config.directionlist[langindex] == "rtl":
             gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
         else:
             gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
         
     config.datetype = self.dateformat.get_active()
     config.datedelim = self.delimiter.get_active()
     config.dateorder = self.dateorder.get_active()
     for i in range(0,3):
         field = config.dateorders[config.dateorder][i]
         config.datefields[field] = i
     if self.uselatin.get_active() == True:
         config.digittype = 0
     else:
         config.digittype = 1
Example #10
0
    def applyFormatSetting(self):
        langindex = self.langlist.get_active()
        if langindex != config.localelist.index(config.locale):
            config.locale = config.localelist[langindex]
            self.emit("locale-changed", config.locale)

            if config.directionlist[langindex] == "rtl":
                gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
            else:
                gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)

        config.datetype = self.dateformat.get_active()
        config.datedelim = self.delimiter.get_active()
        config.dateorder = self.dateorder.get_active()
        for i in range(0, 3):
            field = config.dateorders[config.dateorder][i]
            config.datefields[field] = i
        if self.uselatin.get_active() == True:
            config.digittype = 0
        else:
            config.digittype = 1
Example #11
0
    def on_language_selection_changed(self, *args, **kwargs):
        lang = self.get_language()
        if not lang:
            return
        # strip encoding; we use UTF-8 internally no matter what
        lang = lang.split('.')[0]
        self.controller.translate(lang)
        import gtk
        ltr = i18n.get_string('default-ltr', lang, 'ubiquity/imported')
        if ltr == 'default:RTL':
            gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
        else:
            gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
        if not self.only:
            release_name = misc.get_release_name()
            install_medium = misc.get_install_medium()
            install_medium = i18n.get_string(install_medium, lang)
            for widget in (self.try_text_label,
                           self.try_ubuntu,
                           self.install_ubuntu,
                           self.ready_text_label,
                           self.alpha_warning_label):
                text = i18n.get_string(gtk.Buildable.get_name(widget), lang)
                text = text.replace('${RELEASE}', release_name)
                text = text.replace('${MEDIUM}', install_medium)
                widget.set_label(text)

            if self.release_notes_label:
                if self.release_notes_url and self.update_installer:
                    pass
                elif self.release_notes_url:
                    text = i18n.get_string('release_notes_only', lang)
                    self.release_notes_label.set_markup(text)
                elif self.update_installer:
                    text = i18n.get_string('update_installer_only', lang)
                    self.release_notes_label.set_markup(text)
                else:
                    self.release_notes_label.hide()
            for w in self.page.get_children():
                w.show()
Example #12
0
 def setLtR(self):
     ltrrtl = gettext.dgettext("gtk20", "default:LTR")
     if ltrrtl == "default:RTL":
         gtk.widget_set_default_direction (gtk.TEXT_DIR_RTL)
     elif ltrrtl == "default:LTR":
         gtk.widget_set_default_direction (gtk.TEXT_DIR_LTR)
     else:
         log.error("someone didn't translate the ltr bits right: %s" %(ltrrtl,))
         gtk.widget_set_default_direction (gtk.TEXT_DIR_LTR)            
Example #13
0
 def setLtR(self):
     ltrrtl = gettext.dgettext("gtk20", "default:LTR")
     if ltrrtl == "default:RTL":
         gtk.widget_set_default_direction (gtk.TEXT_DIR_RTL)
     elif ltrrtl == "default:LTR":
         gtk.widget_set_default_direction (gtk.TEXT_DIR_LTR)
     else:
         log.error("someone didn't translate the ltr bits right: %s" %(ltrrtl,))
         gtk.widget_set_default_direction (gtk.TEXT_DIR_LTR)
Example #14
0
def main():
    usage = "%prog [options] [python-executable]"
    version = 'DreamPie %s' % __version__
    parser = OptionParser(usage=usage, version=version)
    if sys.platform == 'win32':
        parser.add_option("--hide-console-window", action="store_true",
                          dest="hide_console",
                          help="Hide the console window")

    opts, args = parser.parse_args()
    
    if len(args) > 1:
        parser.error("Can accept at most one argument")
    if len(args) == 1:
        pyexec = args[0]
    elif 'dreampie' in sys.executable.lower():
        # We are under py2exe.
        msg = gtk.MessageDialog(
            None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
            _("DreamPie must be given the file name of a Python interpreter. "
              "Please create a shortcut to something like '%s "
              "--hide-console-window c:\\python26\\python.exe'.")
            % os.path.abspath(sys.argv[0]))
        _response = msg.run()
        msg.destroy()
        sys.exit(1)
    else:
        pyexec = sys.executable
        
    
    if sys.platform == 'win32' and opts.hide_console:
        from .hide_console_window import hide_console_window
        hide_console_window()

    gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
    _dp = DreamPie(pyexec)
    gtk.main()
Example #15
0
def tuneHijriMonthes(widget=None):
    if rtl:
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
    dialog = EditDbDialog()
    dialog.resize(400, 400)
    dialog.run()
Example #16
0
def set_language_direction(direction):
    if direction == 'rtl':
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
    else:
        gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
Example #17
0
    def __init__(self, gui_queue, logic_queue, file_name='gui.xml'):
        """
        Initialize the gui thread.

        Args:
            gui_queue (Queue.Queue): The queue of the thread.
            logic_queue (Queue.Queue): The queue of the logic thread.
            file_name (str, optional): The XML file that describes the gui.
        """
        self.logger = logging.getLogger('gui')

        self.gui_queue = gui_queue
        self.logic_queue = logic_queue

        # the builder is used to access the different widgets of the gui
        self.builder = gtk.Builder()
        self.builder.add_from_file(file_name)

        # block dict containing information about the block.
        # the keys are the clients' ip, and the values are list
        # of block records
        self.block_dict = {}

        gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)

        # adjust the main window
        window = self.builder.get_object('main_window')
        window.set_border_width(10)
        window.resize(700, 600)

        # add padding to the notebook tabs
        notebook = self.builder.get_object('main_notebook')
        for frame in notebook:
            label = notebook.get_tab_label(frame)
            label_text = label.get_text()
            label.set_property('width-chars', len(label_text) - 1)

        # add spacial column data rendering to the tree views
        self.add_tree_view_data_renderers()

        # The handler of the signals
        handlers = {
            'gtk_main_quit':
                self.exit,
            'on_file_system_download_clicked':
                self.file_system_download_clicked,
            'on_file_system_upload_clicked':
                self.file_system_upload_clicked,
            'on_upload_window_delete_event':
                self.upload_window_delete_event,
            'on_upload_ok_button_clicked':
                self.upload_ok_button_clicked,
            'on_upload_cancel_button_clicked':
                self.upload_cancel_button_clicked,
            'on_file_system_reconstruct_clicked':
                self.file_system_reconstruct_clicked,
            'on_file_system_delete_clicked':
                self.file_system_delete_clicked,
            'on_waiting_files_cancel_clicked':
                self.waiting_files_cancel_clicked,
            'on_file_status_files_tree_view_cursor_changed':
                self.file_status_callback,
            'on_clients_clients_tree_view_cursor_changed':
                self.clients_callback,
            'on_clients_refresh_clicked':
                self.clients_refresh_clicked,
            'on_clients_delete_clicked':
                self.clients_delete_clicked
        }

        self.builder.connect_signals(handlers)

        window.show_all()
Example #18
0
        else:
            gtk.main_quit()## FIXME
        return True
    def buttonPress(self, obj, event):
        if event.button==1:
            (px, py, mask) = ud.rootWindow.get_pointer()
            self.begin_move_drag(event.button, px, py, event.time)
            return True
        return False


gobject.type_register(TimeLine)
TimeLine.registerSignals()
TimeLineWindow.registerSignals()

if __name__=='__main__':
    gtk.window_set_default_icon_from_file(ui.logo)
    if rtl:
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
    win = TimeLineWindow()
    win.resize(ud.screenW, 150)
    win.move(0, 0)
    #win.tline.timeWidth = 100 * 365 * 24 * 3600 # 2*10**17
    #win.tline.timeStart = time.time() - win.tline.timeWidth # -10**17
    win.show()
    gtk.main()




Example #19
0
def set_language_direction(direction):
    if direction == 'rtl':
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
    else:
        gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
Example #20
0
    def __init__(self, gui_queue, logic_queue, file_name='gui.xml'):
        """
        Initialize the gui thread.

        Args:
            gui_queue (Queue.Queue): The queue of the thread.
            logic_queue (Queue.Queue): The queue of the logic thread.
            file_name (str, optional): The XML file that describes the gui.
        """
        self.logger = logging.getLogger('gui')

        self.gui_queue = gui_queue
        self.logic_queue = logic_queue

        # the builder is used to access the different widgets of the gui
        self.builder = gtk.Builder()
        self.builder.add_from_file(file_name)

        # block dict containing information about the block.
        # the keys are the clients' ip, and the values are list
        # of block records
        self.block_dict = {}

        gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)

        # adjust the main window
        window = self.builder.get_object('main_window')
        window.set_border_width(10)
        window.resize(700, 600)

        # add padding to the notebook tabs
        notebook = self.builder.get_object('main_notebook')
        for frame in notebook:
            label = notebook.get_tab_label(frame)
            label_text = label.get_text()
            label.set_property('width-chars', len(label_text) - 1)

        # add spacial column data rendering to the tree views
        self.add_tree_view_data_renderers()

        # The handler of the signals
        handlers = {
            'gtk_main_quit': self.exit,
            'on_file_system_download_clicked':
            self.file_system_download_clicked,
            'on_file_system_upload_clicked': self.file_system_upload_clicked,
            'on_upload_window_delete_event': self.upload_window_delete_event,
            'on_upload_ok_button_clicked': self.upload_ok_button_clicked,
            'on_upload_cancel_button_clicked':
            self.upload_cancel_button_clicked,
            'on_file_system_reconstruct_clicked':
            self.file_system_reconstruct_clicked,
            'on_file_system_delete_clicked': self.file_system_delete_clicked,
            'on_waiting_files_cancel_clicked':
            self.waiting_files_cancel_clicked,
            'on_file_status_files_tree_view_cursor_changed':
            self.file_status_callback,
            'on_clients_clients_tree_view_cursor_changed':
            self.clients_callback,
            'on_clients_refresh_clicked': self.clients_refresh_clicked,
            'on_clients_delete_clicked': self.clients_delete_clicked
        }

        self.builder.connect_signals(handlers)

        window.show_all()
Example #21
0
import pygtk
pygtk.require('2.0')
import gtk
import gobject

gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Hello Buttons!")
window.connect("delete_event", lambda *args: False)
window.connect("destroy", lambda *args: gtk.main_quit())
window.set_border_width(10)
box1 = gtk.HBox(False, 20)
window.add(box1)
box1.show()
button1 = gtk.Button("Hello World")


def hello(widget, data=None):
    print("Hello World", widget, data)


button1.connect("clicked", hello, None)
button1.show()
box1.pack_start(button1, True, True, 0)

button2 = gtk.Button("Button 2")
button2.show()
box1.pack_start(button2, True, True, 0)

print "xxx"
Example #22
0
File: run.py Project: roadt/mcomix
def run():
    """Run the program."""

    try:
        import pkg_resources

    except ImportError:
        # gettext isn't initialized yet, since pkg_resources is required to find translation files.
        # Thus, localizing these messages is pointless.
        log._print("The package 'pkg_resources' could not be found.")
        log._print("You need to install the 'setuptools' package, which also includes pkg_resources.")
        log._print("Note: On most distributions, 'distribute' supersedes 'setuptools'.")
        wait_and_exit()

    # Load configuration and setup localisation.
    preferences.read_preferences_file()
    from mcomix import i18n
    i18n.install_gettext()

    # Retrieve and parse command line arguments.
    argv = portability.get_commandline_args()
    opts, args = parse_arguments(argv)

    # First things first: set the log level.
    log.setLevel(opts.loglevel)

    # On Windows, update the fontconfig cache manually, before MComix starts
    # using Gtk, since the process may take several minutes, during which the
    # main window will just be frozen if the work is left to Gtk itself...
    if opts.update_fontconfig_cache:
        # First, update fontconfig cache.
        log.debug('starting fontconfig cache update')
        try:
            from mcomix.win32 import fc_cache
            from mcomix import process
            fc_cache.update()
            log.debug('fontconfig cache updated')
        except Exception as e:
            log.error('during fontconfig cache update', exc_info=e)
        # And then replace current MComix process with a fresh one
        # (that will not try to update the cache again).
        exe = sys.argv[0]
        if sys.platform == 'win32' and exe.endswith('.py'):
            # Find the interpreter.
            exe = process.find_executable(('pythonw.exe', 'python.exe'))
            args = [exe, sys.argv[0]]
        else:
            args = [exe]
        if sys.platform == 'win32':
            args.append('--no-update-fontconfig-cache')
        args.extend(argv)
        if '--update-fontconfig-cache' in args:
            args.remove('--update-fontconfig-cache')
        log.debug('restarting MComix from fresh: os.execv(%s, %s)', repr(exe), args)
        try:
            if sys.platform == 'win32':
                # Of course we can't use os.execv on Windows because it will
                # mangle arguments containing spaces or non-ascii characters...
                process.Win32Popen(args)
                sys.exit(0)
            else:
                os.execv(exe, args)
        except Exception as e:
            log.error('os.execv(%s, %s) failed', exe, str(args), exc_info=e)
        wait_and_exit()

    # Check for PyGTK and PIL dependencies.
    try:
        import pygtk
        pygtk.require('2.0')

        import gtk
        assert gtk.gtk_version >= (2, 12, 0)
        assert gtk.pygtk_version >= (2, 12, 0)

        import gobject
        gobject.threads_init()

    except AssertionError:
        log.error( _("You do not have the required versions of GTK+ and PyGTK installed.") )
        log.error( _('Installed GTK+ version is: %s') % \
                  '.'.join([str(n) for n in gtk.gtk_version]) )
        log.error( _('Required GTK+ version is: 2.12.0 or higher') )
        log.error( _('Installed PyGTK version is: %s') % \
                  '.'.join([str(n) for n in gtk.pygtk_version]) )
        log.error( _('Required PyGTK version is: 2.12.0 or higher') )
        wait_and_exit()

    except ImportError:
        log.error( _('Required PyGTK version is: 2.12.0 or higher') )
        log.error( _('No version of PyGTK was found on your system.') )
        log.error( _('This error might be caused by missing GTK+ libraries.') )
        wait_and_exit()

    try:
        import PIL.Image
        assert PIL.Image.VERSION >= '1.1.5'

    except AssertionError:
        log.error( _("You don't have the required version of the Python Imaging"), end=' ')
        log.error( _('Library (PIL) installed.') )
        log.error( _('Installed PIL version is: %s') % Image.VERSION )
        log.error( _('Required PIL version is: 1.1.5 or higher') )
        wait_and_exit()

    except ImportError:
        log.error( _('Python Imaging Library (PIL) 1.1.5 or higher is required.') )
        log.error( _('No version of the Python Imaging Library was found on your system.') )
        wait_and_exit()

    if not os.path.exists(constants.DATA_DIR):
        os.makedirs(constants.DATA_DIR, 0700)

    if not os.path.exists(constants.CONFIG_DIR):
        os.makedirs(constants.CONFIG_DIR, 0700)

    from mcomix import icons
    icons.load_icons()

    open_path = None
    open_page = 1
    if len(args) == 1:
        open_path = args[0]
    elif len(args) > 1:
        open_path = args

    elif preferences.prefs['auto load last file'] \
        and preferences.prefs['path to last file'] \
        and os.path.isfile(preferences.prefs['path to last file']):
        open_path = preferences.prefs['path to last file']
        open_page = preferences.prefs['page of last file']

    # Some languages require a RTL layout
    if preferences.prefs['language'] in ('he', 'fa'):
        gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)

    gtk.gdk.set_program_class(constants.APPNAME)

    from mcomix import main
    window = main.MainWindow(fullscreen = opts.fullscreen, is_slideshow = opts.slideshow,
            show_library = opts.library, manga_mode = opts.manga,
            double_page = opts.doublepage, zoom_mode = opts.zoommode,
            open_path = open_path, open_page = open_page)
    main.set_main_window(window)

    if 'win32' != sys.platform:
        # Add a SIGCHLD handler to reap zombie processes.
        def on_sigchld(signum, frame):
            try:
                os.waitpid(-1, os.WNOHANG)
            except OSError:
                pass
        signal.signal(signal.SIGCHLD, on_sigchld)

    signal.signal(signal.SIGTERM, lambda: gobject.idle_add(window.terminate_program))
    try:
        gtk.main()
    except KeyboardInterrupt: # Will not always work because of threading.
        window.terminate_program()