Example #1
0
 def clipboard_nesting_check(self, action, packet_type, ss):
     clipboardlog("clipboard_nesting_check(%s, %s, %s)", action,
                  packet_type, ss)
     cc = self._clipboard_client
     if cc is None:
         clipboardlog("not %s clipboard packet '%s': no clipboard client",
                      action, packet_type)
         return False
     if not cc.clipboard_enabled:
         clipboardlog(
             "not %s clipboard packet '%s': client %s has clipboard disabled",
             action, packet_type, cc)
         return False
     if gtk.main_level() >= 10:
         clipboardlog.warn("Warning: loop nesting too deep: %s",
                           gtk.main_level())
         clipboardlog.warn(
             " you may have a clipboard forwarding loop, disabling the clipboard"
         )
         #turn off clipboard at our end:
         self.set_clipboard_enabled_status(ss, False)
         #if we can, tell the client to do the same:
         if ss.clipboard_set_enabled:
             ss.send_clipboard_enabled("probable clipboard loop detected")
         return False
     return True
Example #2
0
 def _run_gtk_main(self):
     print("_run_gtk_main")
     print(gtk.main_level())
     if gtk.main_level() < 3:
         gobject.timeout_add(0, self._run_gtk_main)
     else:
         gobject.timeout_add(0, wimpiggy.util.gtk_main_quit_really)
     gtk.main()
     return False
Example #3
0
 def _run_gtk_main(self):
     print("_run_gtk_main")
     print(gtk.main_level())
     if gtk.main_level() < 3:
         gobject.timeout_add(0, self._run_gtk_main)
     else:
         gobject.timeout_add(0, wimpiggy.util.gtk_main_quit_really)
     gtk.main()
     return False
Example #4
0
 def process_clipboard_packet(self, packet):
     clipboardlog("process_clipboard_packet(%s) level=%s", packet, gtk.main_level())
     #check for clipboard loops:
     if gtk.main_level()>=40:
         clipboardlog.warn("loop nesting too deep: %s", gtk.main_level())
         clipboardlog.warn("you may have a clipboard forwarding loop, disabling the clipboard")
         self.clipboard_enabled = False
         self.emit("clipboard-toggled")
         return
     self.idle_add(self.clipboard_helper.process_clipboard_packet, packet)
Example #5
0
 def process_clipboard_packet(self, packet):
     clipboardlog("process_clipboard_packet(%s) level=%s", packet, gtk.main_level())
     #check for clipboard loops:
     if gtk.main_level()>=40:
         clipboardlog.warn("loop nesting too deep: %s", gtk.main_level())
         clipboardlog.warn("you may have a clipboard forwarding loop, disabling the clipboard")
         self.clipboard_enabled = False
         self.emit("clipboard-toggled")
         return
     self.idle_add(self.clipboard_helper.process_clipboard_packet, packet)
Example #6
0
    def terminate_program(self, save_current_file=False):
        """Run clean-up tasks and exit the program."""

        self.hide()

        if gtk.main_level() > 0:
            gtk.main_quit()

        if prefs['auto load last file'] and self.filehandler.file_loaded:
            prefs['path to last file'] = self.imagehandler.get_real_path()
            prefs['page of last file'] = self.imagehandler.get_current_page()

        else:
            prefs['path to last file'] = ''
            prefs['page of last file'] = 1

        if prefs['hide all'] and self.hide_all_forced and self.fullscreen:
            prefs['hide all'] = False

        self.write_config_files()

        self.filehandler.cleanup()
        self.imagehandler.cleanup()
        self.thumbnailsidebar.clear()
        backend.LibraryBackend().close()

        # This hack is to avoid Python issue #1856.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                thread.join()
Example #7
0
    def terminate_program(self):
        """Run clean-up tasks and exit the program."""

        self.hide()

        if gtk.main_level() > 0:
            gtk.main_quit()

        if prefs['auto load last file'] and self.filehandler.file_loaded:
            prefs['path to last file'] = self.imagehandler.get_real_path()
            prefs['page of last file'] = self.imagehandler.get_current_page()

        else:
            prefs['path to last file'] = ''
            prefs['page of last file'] = 1

        if prefs['hide all'] and self.hide_all_forced and self.fullscreen:
            prefs['hide all'] = False

        self.write_config_files()

        self.filehandler.close_file()
        if main_dialog._dialog is not None:
            main_dialog._dialog.close()
        backend.LibraryBackend().close()

        # This hack is to avoid Python issue #1856.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                log.debug('Waiting for thread %s to finish before exit', thread)
                thread.join()
Example #8
0
    def close_application(self, widget, event=None, data=None):
        """Termination"""

        if self.rendering_thread:
            self.rendering_thread.quit = True
            self.rendering_thread.join()

        if os.path.isdir(self.tmp_dir):
            try:
                shutil.rmtree(self.tmp_dir)
            except:
                # ============= Start python-poppler for Windows bug workaround ============
                # python-poppler does not "release" the file and only the files of previous sessions can be deleted
                # Get the list of all pdf-shuffler temporary dirs
                temp_dir_root = os.path.split(self.tmp_dir)[0]
                shuffler_dirs = glob.glob(temp_dir_root +
                                          "/tmp??????pdfshuffler")
                # delete if possible
                for directory in shuffler_dirs:
                    try:
                        shutil.rmtree(directory)
                    except:
                        pass
                # ============= End python-poppler for Windows bug workaround ==============

        if gtk.main_level():
            gtk.main_quit()
        else:
            sys.exit(0)
        return False
Example #9
0
 def quit_cb (self, *args):
     self.w.hide()
     if (self.gsd.grid
         and self.gsd.grid.is_changed()
         and (not self.won)):
         self.save_game(self)
     if gtk.main_level() > 1:
         # If we are in an embedded mainloop, that means that one
         # of our "swallowed" dialogs is active, in which case we
         # have to quit that mainloop before we can quit
         # properly.
         if self.swallower.running:
             d = self.swallower.running
             d.response(gtk.RESPONSE_DELETE_EVENT)
         gtk.main_quit() # Quit the embedded mainloop
         gobject.idle_add(self.quit_cb, 100) # Call ourselves again
                                            # to quit the main
                                            # mainloop
         return
     # make sure we really go away before doing our saving --
     # otherwise we appear sluggish.
     while gtk.events_pending():
         gtk.main_iteration()
     self.stop_worker_thread()
     # allow KeyboardInterrupts, which calls quit_cb outside the main loop
     try:
         gtk.main_quit()
     except RuntimeError:
         pass
Example #10
0
    def terminate_program(self, save_current_file=False):
        """Run clean-up tasks and exit the program."""

        self.hide()

        if gtk.main_level() > 0:
            gtk.main_quit()

        if prefs['auto load last file'] and self.filehandler.file_loaded:
            prefs['path to last file'] = self.imagehandler.get_real_path()
            prefs['page of last file'] = self.imagehandler.get_current_page()

        else:
            prefs['path to last file'] = ''
            prefs['page of last file'] = 1

        if prefs['hide all'] and self.hide_all_forced and self.fullscreen:
            prefs['hide all'] = False

        self.write_config_files()

        self.filehandler.cleanup()
        self.imagehandler.cleanup()
        self.thumbnailsidebar.clear()
        backend.LibraryBackend().close()

        # This hack is to avoid Python issue #1856.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                thread.join()
Example #11
0
 def _DOM_ready(self):
     document = self.__webkit.GetDomDocument()
     window = self.__webkit.GetDomWindow()
     document.addEventListener('DOMNodeInserted', self._DOM_node_inserted,
                                     False)
     document.addEventListener('DOMNodeRemoved', self._DOM_node_removed,
                                     False)
     document.addEventListener('DOMAttrModified', self._DOM_node_attr_modified,
                                     False)
     document.addEventListener('DOMCharacterDataModified', self._DOM_node_data_modified,
                                     False)
     #print >> sys.stderr,  "URL:", document.URL
     #print >> sys.stderr,  "Title:", document.title
     #print >> sys.stderr,  "Cookies:", document.cookie
     #print body, dir(body)
     #print "INNER:", document.innerHTML
     #print "OUTER:", body.outerHTML
     #print dir(document)
     #print str(document)
     # Save results so that we can return it on visit() calls.
     self.result = document.title, document.cookie, document.body.outerHTML
     self.walker.walk_node(document)
     # _DOM_ready may be called before we call gtk.main() -- see
     # visit() -- in which case calling mainquit is invalid. We check
     # for that here.
     if gtk.main_level() > 0:
         gtk.mainquit()
Example #12
0
 def __timeout_callback(self):
     debug("Timeout Callback")
     if gtk.main_level() > 0:
         gtk.mainquit()
     # Set a flag so that the main thread knows to raise a
     # TimeoutException.
     self.timed_out = True
Example #13
0
    def __call__(self, exctyp, value, tback):
        # type: (Type[BaseException], BaseException, Any) -> None
        """Custom sys.excepthook callback which displays a GTK+ dialog"""
        # pylint: disable=no-member

        dialog = self.make_info_dialog()
        while True:
            resp = dialog.run()

            if resp == 3:
                if self.cached_tb is None:
                    self.cached_tb = analyse(exctyp, value, tback).getvalue()
                self.send_report(self.cached_tb)
            elif resp == 2:
                if self.cached_tb is None:
                    self.cached_tb = analyse(exctyp, value, tback).getvalue()
                details = self.make_details_dialog(dialog, self.cached_tb)
                details.run()
                details.destroy()
            elif resp == 1 and gtk.main_level() > 0:
                gtk.main_quit()

            # Only the "Details" dialog loops back when closed
            if resp != 2:
                break

        dialog.destroy()
Example #14
0
def _dump_recursion_info():
    # This is how deeply nested in recursive main-loops we are:
    print("gtk depth: %s" % (gtk.main_level()))
    import ctypes
    class ThreadState(ctypes.Structure):
        _fields_ = [("next", ctypes.c_voidp),
                    ("interp", ctypes.c_voidp),
                    ("frame", ctypes.c_voidp),
                    ("recursion_depth", ctypes.c_int)]
    ts = ctypes.cast(ctypes.pythonapi.PyThreadState_Get(),
                     ctypes.POINTER(ThreadState))
    # This is Python's count of the recursion depth -- i.e., the thing that
    # will eventually trigger the 'Maximum recursion depth exceeded' message.
    print("python internal depth: %s" % ts[0].recursion_depth)
    import inspect
    count = 0
    frame = inspect.currentframe()
    while frame:
        frame = frame.f_back
        count += 1
    # This is the number of frames in the current stack. It probably only
    # counts up to the last call to gtk.main().
    print("stack frames: %s" % count)
    # The number of NestedMainLoops in progress:
    print("NestedMainLoops: %s" % len(NestedMainLoop._stack))
def _gui_excepthook_generic(
      exc_type,
      exc_value,
      exc_traceback,
      orig_sys_excepthook,
      title,
      app_name,
      parent,
      report_uri_list):
  callback_result = _gui_excepthook_additional_callback(
    exc_type, exc_value, exc_traceback)
  
  if callback_result:
    return
  
  orig_sys_excepthook(exc_type, exc_value, exc_traceback)
  
  if issubclass(exc_type, Exception):
    exception_message = "".join(
      traceback.format_exception(exc_type, exc_value, exc_traceback))
    
    display_error_message(
      title=title,
      app_name=app_name,
      parent=parent,
      details=exception_message,
      report_uri_list=report_uri_list)
    
    # Make sure to quit the application since unhandled exceptions can
    # mess up the application state.
    if gtk.main_level() > 0:
      gtk.main_quit()
Example #16
0
    def __call__(self, exctyp, value, tback):
        # type: (Type[BaseException], BaseException, Any) -> None
        """Custom sys.excepthook callback which displays a GTK+ dialog"""
        # pylint: disable=no-member

        dialog = self.make_info_dialog()
        while True:
            resp = dialog.run()

            if resp == 3:
                if self.cached_tb is None:
                    self.cached_tb = analyse(exctyp, value, tback).getvalue()
                self.send_report(self.cached_tb)
            elif resp == 2:
                if self.cached_tb is None:
                    self.cached_tb = analyse(exctyp, value, tback).getvalue()
                details = self.make_details_dialog(dialog, self.cached_tb)
                details.run()
                details.destroy()
            elif resp == 1 and gtk.main_level() > 0:
                gtk.main_quit()

            # Only the "Details" dialog loops back when closed
            if resp != 2:
                break

        dialog.destroy()
Example #17
0
def _dialog_response_cb(dialog, resp, trace, exctyp, value):
    global exception_dialog_active

    if resp == RESPONSE_QUIT and gtk.main_level() > 0:
        if not quit_confirmation_func:
            sys.exit(1)  # Exit code is important for IDEs
        else:
            if quit_confirmation_func():
                sys.exit(1)  # Exit code is important for IDEs
            else:
                dialog.destroy()
                exception_dialog_active = False
    elif resp == RESPONSE_SEARCH:
        search_url = ("https://github.com/mypaint/mypaint/search"
                      "?utf8=%E2%9C%93"
                      "&q={}+{}"
                      "&type=Issues").format(quote_plus(exctyp.__name__, "/"),
                                             quote_plus(str(value), "/"))
        gtk.show_uri(None, search_url, gtk.gdk.CURRENT_TIME)
        if "-" in lib.meta.MYPAINT_VERSION:
            dialog.set_response_sensitive(RESPONSE_REPORT, True)
    elif resp == RESPONSE_REPORT:
        #TRANSLATORS: Crash report template for github, preceding a traceback.
        #TRANSLATORS: Please ask users kindly to supply at least an English
        #TRANSLATORS: title if they are able.
        body = _(u"""\
            #### Description

            Give this report a short descriptive title.
            Use something like
            "{feature-that-broke}: {what-went-wrong}"
            for the title, if you can.
            Then please replace this text
            with a longer description of the bug.
            Screenshots or videos are great, too!

            #### Steps to reproduce

            Please tell us what you were doing
            when the error message popped up.
            If you can provide step-by-step instructions
            on how to reproduce the bug,
            that's even better.

            #### Traceback
        """)
        body = "\n\n".join([
            "".join(textwrap.wrap(p, sys.maxint))
            for p in textwrap.dedent(body).split("\n\n")
        ] + [trace])
        report_url = ("https://github.com/mypaint/mypaint/issues/new"
                      "?title={title}"
                      "&body={body}").format(
                          title="",
                          body=quote_plus(body.encode("utf-8"), "/"),
                      )
        gtk.show_uri(None, report_url, gtk.gdk.CURRENT_TIME)
    else:
        dialog.destroy()
        exception_dialog_active = False
Example #18
0
def funcBack(statwin):
    #gtk.threads_enter()
    #gtk.threads_leave()
    import time
    print "Went ..."
    sys.stdout.write("cp2-0\n")
    sys.stdout.flush()
    #statwin.grab_remove()
    sys.stdout.write("cp2-1: " + ` gtk.main_level() ` + "\n")
    sys.stdout.write("cp2-2: " + ` threading.activeCount() ` + "\n")
    #gtk.threads_leave()
    #gtk.threads_enter()
    sys.stdout.write("cp2-3\n")
    sys.stdout.flush()
    #gtk.block_
    #gtk.threads_enter()
    win = gtk.MessageDialog(None, gtk.DIALOG_MODAL, \
     gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Hello" )
    #gtk.threads_leave()
    sys.stdout.write("cp2-3.1\n")
    sys.stdout.flush()
    #gtk.threads_leave()
    sys.stdout.write("cp2-4\n")
    sys.stdout.flush()
    win.show_all()
    win.run()
    win.destroy()
    win.hide_all()
    del win
    print "Back!"
Example #19
0
 def quit_cb (self, *args):
     self.w.hide()
     if (self.gsd.grid
         and self.gsd.grid.is_changed()
         and (not self.won)):
         self.save_game(self)
     if gtk.main_level() > 1:
         # If we are in an embedded mainloop, that means that one
         # of our "swallowed" dialogs is active, in which case we
         # have to quit that mainloop before we can quit
         # properly.
         if self.swallower.running:
             d = self.swallower.running
             d.response(gtk.RESPONSE_DELETE_EVENT)
         gtk.main_quit() # Quit the embedded mainloop
         gobject.idle_add(self.quit_cb, 100) # Call ourselves again
                                            # to quit the main
                                            # mainloop
         return
     # make sure we really go away before doing our saving --
     # otherwise we appear sluggish.
     while gtk.events_pending():
         gtk.main_iteration()
     self.stop_worker_thread()
     # allow KeyboardInterrupts, which calls quit_cb outside the main loop
     try:
         gtk.main_quit()
     except RuntimeError:
         pass
Example #20
0
def _make_window():
    window = gtk.Window()
    logging.info(dir(gtk))
    v=gtk.VBox()
    button1=gtk.Button()
    button1.set_label("hi")
    text1=gtk.Entry()
    logging.info(dir(text1))
    window.set_title("pyconsole.py")
    swin = gtk.ScrolledWindow()
    swin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
    #window.add(swin)#FileChooserDialog
    console = Console(banner="Hello there!",
                      use_rlcompleter=False,
                      start_script="from gtk import *\n")
    v.add(button1)
    v.add(text1)
    text1.set_text("hello")
    swin.add(console)
    v.add(swin)
    window.add(v)

    #logging.info(dir(button1))
    button1.connect("clicked",button1_click,window)
    window.set_default_size(500, 400)
    window.show_all()

    if not gtk.main_level():
        window.connect("destroy", gtk.main_quit)
        gtk.main()

    return console
Example #21
0
def funcBack(statwin):
    # gtk.threads_enter()
    # gtk.threads_leave()
    import time

    print "Went ..."
    sys.stdout.write("cp2-0\n")
    sys.stdout.flush()
    # statwin.grab_remove()
    sys.stdout.write("cp2-1: " + ` gtk.main_level() ` + "\n")
    sys.stdout.write("cp2-2: " + ` threading.activeCount() ` + "\n")
    # gtk.threads_leave()
    # gtk.threads_enter()
    sys.stdout.write("cp2-3\n")
    sys.stdout.flush()
    # gtk.block_
    # gtk.threads_enter()
    win = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Hello")
    # gtk.threads_leave()
    sys.stdout.write("cp2-3.1\n")
    sys.stdout.flush()
    # gtk.threads_leave()
    sys.stdout.write("cp2-4\n")
    sys.stdout.flush()
    win.show_all()
    win.run()
    win.destroy()
    win.hide_all()
    del win
    print "Back!"
Example #22
0
 def on_delete_event(self, *args):
     self.quit = True
     self.hide()
     if self.child_pid:
         os.kill(self.child_pid, signal.SIGKILL)
     if gtk.main_level():
         gtk.main_quit()
Example #23
0
    def destroy(self, *args):
        if _debug:
            print "FigureManagerGTK.%s" % fn_name()
        self.window.destroy()

        if Gcf.get_num_fig_managers() == 0 and not matplotlib.is_interactive() and gtk.main_level() >= 1:
            gtk.main_quit()
Example #24
0
 def on_delete_event(self, *args):
     self.quit = True
     self.hide()
     if self.child_pid:
         os.kill(self.child_pid, signal.SIGKILL)
     if gtk.main_level():
         gtk.main_quit()
Example #25
0
File: main.py Project: roadt/mcomix
    def terminate_program(self):
        """Run clean-up tasks and exit the program."""

        self.hide()

        if gtk.main_level() > 0:
            gtk.main_quit()

        if prefs['auto load last file'] and self.filehandler.file_loaded:
            prefs['path to last file'] = self.imagehandler.get_real_path()
            prefs['page of last file'] = self.imagehandler.get_current_page()

        else:
            prefs['path to last file'] = ''
            prefs['page of last file'] = 1

        if prefs['hide all'] and self.hide_all_forced and self.fullscreen:
            prefs['hide all'] = False

        self.write_config_files()

        self.filehandler.close_file()
        if main_dialog._dialog is not None:
            main_dialog._dialog.close()
        backend.LibraryBackend().close()

        # This hack is to avoid Python issue #1856.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                log.debug('Waiting for thread %s to finish before exit',
                          thread)
                thread.join()
Example #26
0
def _dump_recursion_info():
    # This is how deeply nested in recursive main-loops we are:
    print("gtk depth: %s" % (gtk.main_level()))
    import ctypes

    class ThreadState(ctypes.Structure):
        _fields_ = [("next", ctypes.c_voidp), ("interp", ctypes.c_voidp),
                    ("frame", ctypes.c_voidp),
                    ("recursion_depth", ctypes.c_int)]

    ts = ctypes.cast(ctypes.pythonapi.PyThreadState_Get(),
                     ctypes.POINTER(ThreadState))
    # This is Python's count of the recursion depth -- i.e., the thing that
    # will eventually trigger the 'Maximum recursion depth exceeded' message.
    print("python internal depth: %s" % ts[0].recursion_depth)
    import inspect
    count = 0
    frame = inspect.currentframe()
    while frame:
        frame = frame.f_back
        count += 1
    # This is the number of frames in the current stack. It probably only
    # counts up to the last call to gtk.main().
    print("stack frames: %s" % count)
    # The number of NestedMainLoops in progress:
    print("NestedMainLoops: %s" % len(NestedMainLoop._stack))
Example #27
0
    def destroy(self, *args):
        if _debug: print 'FigureManagerGTK.%s' % fn_name()
        self.window.destroy()

        if Gcf.get_num_fig_managers()==0 and \
               not matplotlib.is_interactive() and \
               gtk.main_level() >= 1:
            gtk.main_quit()
Example #28
0
    def _on_destroy_window(self, window):
        self.remove_window(window)
        if not self._windows:
            import gtk

            logger.debug('Last toplevel destroyed, quit')
            if gtk.main_level() > 0:
                gtk.main_quit()
Example #29
0
 def _Run(self):
     """Enter GTK mainloop."""
     self._GetNativeApp()
     
     if gtk.main_level() == 0:
         # We need to start the mainloop.  This means we will also
         # have to kill the mainloop when the last figure is closed.
         gtk.vv_do_quit = True
         gtk.main()
Example #30
0
def gtk_main_quit_really():
    # We import gtk inside here, rather than at the top of the file, because
    # importing gtk has the side-effect of trying to connect to the X server
    # (and this process may block, may cause us to later be killed if the X
    # server goes away, etc.), and we don't want to impose that on every user
    # of wimpiggy.util.
    import gtk
    for i in xrange(gtk.main_level()):
        gtk.main_quit()
Example #31
0
def show(mainloop=True):
    """
    Show all the figures and enter the gtk main loop
    This should be the last line of your script
    """
    for manager in Gcf.get_all_fig_managers():
        manager.window.show()
    if mainloop and gtk.main_level() == 0 and len(Gcf.get_all_fig_managers()) > 0:
        gtk.main()
Example #32
0
    def _Run(self):
        """Enter GTK mainloop."""
        self._GetNativeApp()

        if gtk.main_level() == 0:
            # We need to start the mainloop.  This means we will also
            # have to kill the mainloop when the last figure is closed.
            gtk.vv_do_quit = True
            gtk.main()
Example #33
0
def _our_mainquit():
    # XXX: gtk.main_quit() (which is used for crash()) raises an exception if
    # gtk.main_level() == 0; however, all the tests freeze if we use this
    # function to stop the reactor.  what gives?  (I believe this may have been
    # a stupid mistake where I forgot to import gtk here... I will remove this
    # comment if the tests pass)
    import gtk
    if gtk.main_level():
        gtk.main_quit()
Example #34
0
 def crash(self):
     selectreactor.SelectReactor.crash(self)
     import gtk
     # mainquit is deprecated in newer versions
     if gtk.main_level():
         if hasattr(gtk, 'main_quit'):
             gtk.main_quit()
         else:
             gtk.mainquit()
Example #35
0
 def crash(self):
     selectreactor.SelectReactor.crash(self)
     import gtk
     # mainquit is deprecated in newer versions
     if gtk.main_level():
         if hasattr(gtk, 'main_quit'):
             gtk.main_quit()
         else:
             gtk.mainquit()
Example #36
0
def _our_mainquit():
    # XXX: gtk.main_quit() (which is used for crash()) raises an exception if
    # gtk.main_level() == 0; however, all the tests freeze if we use this
    # function to stop the reactor.  what gives?  (I believe this may have been
    # a stupid mistake where I forgot to import gtk here... I will remove this
    # comment if the tests pass)
    import gtk
    if gtk.main_level():
        gtk.main_quit()
 def show(self):
     self.init_video()
     gobject.timeout_add(200, self.run)
     #gobject.idle_add(self.run)
     gtk.Window.show(self)
     if not gtk.main_level():
         gtk.quit_add(0, self.drone.stop, True)
         gobject.threads_init()
         gtk.main()
Example #38
0
def show(exctype, value, tb):
    if exctype is not KeyboardInterrupt:
        dw = DebugWindow()
        dw.show_exception(exctype, value, tb)
        dw.show_all()
        if not gtk.main_level():
            def q(window):
                gtk.main_quit()
            dw.connect('destroy', q)
            gtk.main()
 def stop(self, widget, event=None):
     print "Shutting down GUI\r"
     self.posmap.save_map()
     
     # ofile = open("./testdata/task.data", "w")
     # pickle.dump(self.tasks, ofile)
     # ofile.close()
     if gtk.main_level() > 0:
         gtk.main_quit()
         self.drone.stop(True)
Example #40
0
def show(mainloop=True):
    """
    Show all the figures and enter the gtk main loop
    This should be the last line of your script
    """
    for manager in Gcf.get_all_fig_managers():
        manager.window.show()

    if mainloop and gtk.main_level() == 0:
        gtk.main()
Example #41
0
 def process_clipboard_packet(self, packet):
     clipboardlog("process_clipboard_packet(%s) level=%s", packet,
                  gtk.main_level())
     #check for clipboard loops:
     from xpra.clipboard.clipboard_base import nesting_check
     if not nesting_check():
         self.clipboard_enabled = False
         self.emit("clipboard-toggled")
         return
     self.idle_add(self.clipboard_helper.process_clipboard_packet, packet)
Example #42
0
def gtk2main():
    import pygtk
    pygtk.require('2.0')
    import gtk
    if gtk.main_level()==0:
        gtk.gdk.threads_init()
        try:
            gtk.threads_enter()
            gtk.main()
        finally:
            gtk.threads_leave()
 def gui_excepthook(exc_type, exc_value, exc_traceback):
   orig_sys_excepthook(exc_type, exc_value, exc_traceback)
   
   if issubclass(exc_type, Exception):
     exception_message = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
     display_exception_message(exception_message, plugin_title=plugin_title,
                               report_uri_list=report_uri_list, parent=_gui_excepthook_parent)
     # Make sure to quit the application since unhandled exceptions can
     # mess up the application state.
     if gtk.main_level() > 0:
       gtk.main_quit()
Example #44
0
def show(mainloop=True):
    """
    Show all the figures and enter the gtk main loop
    This should be the last line of your script
    """
    for manager in Gcf.get_all_fig_managers():
        manager.window.show()
        
    if mainloop and gtk.main_level() == 0:
        if gtk.pygtk_version >= (2,4,0): gtk.main()
        else:                            gtk.mainloop()
Example #45
0
 def destroy(self, *args):
     if _debug:
         print "FigureManagerGTK.%s" % fn_name()
     self.vbox.destroy()
     self.window.destroy()
     self.canvas.destroy()
     if self.toolbar:
         self.toolbar.destroy()
     self.__dict__.clear()
     if Gcf.get_num_fig_managers() == 0 and not matplotlib.is_interactive() and gtk.main_level() >= 1:
         gtk.main_quit()
Example #46
0
 def gui_excepthook(exc_type, exc_value, exc_traceback):
   orig_sys_excepthook(exc_type, exc_value, exc_traceback)
   
   if issubclass(exc_type, Exception):
     exception_message = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
     display_exception_message(
       exception_message, plugin_title=plugin_title, report_uri_list=report_uri_list,
       parent=_gui_excepthook_parent)
     # Make sure to quit the application since unhandled exceptions can
     # mess up the application state.
     if gtk.main_level() > 0:
       gtk.main_quit()
Example #47
0
def on_destroy(event):
    from hamster.configuration import GconfStore, runtime
    config = GconfStore()
    
    # handle config option to stop tracking on shutdown
    if config.get_stop_on_shutdown():
        last_activity = runtime.storage.get_last_activity()
        if last_activity and last_activity['end_time'] is None:
            runtime.storage.touch_fact(last_activity)
        
    if gtk.main_level():
        gtk.main_quit()
Example #48
0
    def destroy(self, *args):
        if _debug: print 'FigureManagerGTK.%s' % fn_name()
        self.vbox.destroy()
        self.window.destroy()
        self.canvas.destroy()
        if self.toolbar:
            self.toolbar.destroy()
        self.__dict__.clear()

        if Gcf.get_num_fig_managers()==0 and \
               not matplotlib.is_interactive() and \
               gtk.main_level() >= 1:
            gtk.main_quit()
Example #49
0
    def destroy(self, *args):
        if _debug: print 'FigureManagerGTK.%s' % fn_name()
        self.vbox.destroy()
        self.window.destroy()
        self.canvas.destroy()
        if self.toolbar:
            self.toolbar.destroy()
        self.__dict__.clear()   #Is this needed? Other backends don't have it.

        if Gcf.get_num_fig_managers()==0 and \
               not matplotlib.is_interactive() and \
               gtk.main_level() >= 1:
            gtk.main_quit()
Example #50
0
    def close_application(self, widget, event=None, data=None):
        """Termination"""

        if self.rendering_thread:
            self.rendering_thread.quit = True
            self.rendering_thread.join()

        if os.path.isdir(self.tmp_dir):
            shutil.rmtree(self.tmp_dir)
        if gtk.main_level():
            gtk.main_quit()
        else:
            sys.exit(0)
        return False
Example #51
0
    def __init__(self):
        gtk.Window.__init__(self)

        self.set_title('low-level')
        if sys.platform != 'win32':
            self.set_resize_mode(gtk.RESIZE_IMMEDIATE)
        self.set_reallocate_redraws(True)
        self.connect('delete_event', gtk.main_quit)

        # VBox to hold everything.
        vbox = gtk.VBox()
        self.add(vbox)

        # Query the OpenGL extension version.
        print "OpenGL extension version - %d.%d\n" % gtk.gdkgl.query_version()

        # Configure OpenGL framebuffer.
        # Try to get a double-buffered framebuffer configuration,
        # if not successful then try to get a single-buffered one.
        display_mode = (gtk.gdkgl.MODE_RGB    |
                        gtk.gdkgl.MODE_DEPTH  |
                        gtk.gdkgl.MODE_DOUBLE)
        try:
            glconfig = gtk.gdkgl.Config(mode=display_mode)
        except gtk.gdkgl.NoMatches:
            display_mode &= ~gtk.gdkgl.MODE_DOUBLE
            glconfig = gtk.gdkgl.Config(mode=display_mode)

        print "is RGBA:",                 glconfig.is_rgba()
        print "is double-buffered:",      glconfig.is_double_buffered()
        print "is stereo:",               glconfig.is_stereo()
        print "has alpha:",               glconfig.has_alpha()
        print "has depth buffer:",        glconfig.has_depth_buffer()
        print "has stencil buffer:",      glconfig.has_stencil_buffer()
        print "has accumulation buffer:", glconfig.has_accum_buffer()
        print

        # LowLevelDrawingArea
        drawing_area = LowLevelDrawingArea(glconfig)
        drawing_area.set_size_request(200, 200)
        vbox.pack_start(drawing_area)

        # Unrealize drawing_area on quit.
        gtk.quit_add(gtk.main_level()+1, self._on_quit, drawing_area)

        # A quit button.
        button = gtk.Button('Quit')
        # Destroy window on quit explicitly.
        button.connect('clicked', gtk.main_quit)
        vbox.pack_start(button, expand=False)
Example #52
0
    def run(self):
        self._setup_folder_view()
        self.show_all()

        self._name_entry.grab_focus()

        # Select the current folder.
        if self._active_iter:
            self._folder_tree.get_selection().select_iter(self._active_iter)
            self._folder_tree.set_cursor(self._tree_model.get_path(self._active_iter))

        self._loop_level = gtk.main_level() + 1
        gtk.main()
        return self._response
Example #53
0
    def close_application(self, widget, event=None, data=None):
        """Termination"""

        if self.rendering_thread:
            self.rendering_thread.quit = True
            self.rendering_thread.join()

        if os.path.isdir(self.tmp_dir):
            shutil.rmtree(self.tmp_dir)
        if gtk.main_level():
            gtk.main_quit()
        else:
            sys.exit(0)
        return False
Example #54
0
def stop_gtk():
    # shutdown twisted correctly
    if reactor_required():
        from twisted.internet import reactor
        if reactor.running:
            reactor.callFromThread(reactor.stop)
        # Twisted can be imported without the reactor being used
        # => check if GTK main loop is running
        elif gtk.main_level() > 0:
            glib.idle_add(gtk.main_quit)
    else:
        glib.idle_add(gtk.main_quit)

    # Run the GTK loop until no more events are being generated and thus the GUI is fully destroyed
    wait_for_gui()
Example #55
0
    def destroy(self, *args):
        if hasattr(self, 'toolbar') and self.toolbar is not None:
            self.toolbar.destroy()
        if hasattr(self, 'vbox'):
            self.vbox.destroy()
        if hasattr(self, 'window'):
            self.window.destroy()
        if hasattr(self, 'canvas'):
            self.canvas.destroy()
        self.__dict__.clear()  #Is this needed? Other backends don't have it.

        if Gcf.get_num_fig_managers()==0 and \
               not matplotlib.is_interactive() and \
               gtk.main_level() >= 1:
            gtk.main_quit()
Example #56
0
    def download_and_execute_application(self, app_name, args):
        self.app_name = app_name
        self.args = args

        progress = ProgressDialog(self)
        progress.set_window_title("klik - " + self.app_name)
        print gtk.main_level()
        # grab recipe on another thread
        @threaded
        def download_recipe_threaded(progress):

            # Get recipe
            try:
                self.recipe = self.klik.get_recipe(self.app_name)

                gtk.gdk.threads_enter()
                progress.destroy()
                gtk.gdk.threads_leave()

            except Exception, inst:
                self.error = inst
                gtk.gdk.threads_enter()
                progress.destroy()
                gtk.gdk.threads_leave()
Example #57
-1
 def __init__(self):
     if not gobject.signal_lookup("output", ShellCommandJob):
         gobject.signal_new("output", ShellCommandJob, \
                 gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, \
                 [str])
     if not gtk.main_level():
         gtk.gdk.threads_init()  # _DEBE_ llamarse _ANTES_ del gtk.main por temas del GIL.