示例#1
0
 def onLoadConfig(self, widget, data=None):
     loadDialog = self.widgets["fileLoader"]
     response = loadDialog.run()
     if response == 0 :
         self.loadConfig(loadDialog.get_filename())
         gtk.recent_manager_get_default().add_item(loadDialog.get_uri())
     loadDialog.hide()
示例#2
0
	def playFile(self, file, stop=True):
		## Plays the file 'file' (Could also be a URI).
		# Stop the player if requested. (Required for playbin2 and
		# changing streams midway through another).
		if stop: player.stop()
		if (file == None):
			# If no file is to be played, set the URI to None, and the file to ""
			file = ""
		# Set the now playing label to the file to be played.
		self.nowPlyLbl.set_label(os.path.basename(urllib.url2pathname(file)))
		if (os.path.exists(file) or '://' in file):
			# If it's not already a uri, make it one.
			# Also escape any # characters in the filename
			file = useful.filenameToUri(file).replace('#', '%23')
			# Set the URI to the file's one.
			player.setURI(file)
			# Try to set the subtitle track if requested.
			if cfg.getBool('video/autosub'): subtitles.trySubs(file)
			# Add the file to recently opened files.
			gtk.recent_manager_get_default().add_item(file)
			# Start the player, if it isn't already running.
			if (not player.isPlaying()): player.play()
		
		elif (file != ""):
			# If none of the above, a bad filename was passed.
			print _("Something's stuffed up, no such file: %s") % (file)
			self.playFile(None)
示例#3
0
 def set_filename(self, filename, uri, auto_extension=True):
     """Change the puzzle's filename and optionally correct the
     file extension"""
     self.filename = filename
     self.uri = uri
     if auto_extension and not filename[-len(FILE_EXT) -
                                        1:] == '.' + FILE_EXT:
         self.filename += "." + FILE_EXT
         if self.uri:
             self.uri += "." + FILE_EXT
     #Add the file to the recently used file list
     if self.uri and RECENT_CHOOSER:
         gtk.recent_manager_get_default().add_item(self.uri)
     #Update the display
     self.update_window_title()
示例#4
0
 def get_manager():
     global recent_manager
     if recent_manager != None:
         return recent_manager
     recent_manager = gtk.recent_manager_get_default()
     recent_manager = gtk.RecentManager()
     return recent_manager
示例#5
0
文件: recent.py 项目: Gosha/mcomix
    def __init__(self, ui, window):
        self._window = window
        self._manager = gtk.recent_manager_get_default()
        gtk.RecentChooserMenu.__init__(self, self._manager)

        self.set_sort_type(gtk.RECENT_SORT_MRU)
        self.set_show_tips(True)
        # Missing icons crash GTK on Win32
        if sys.platform == 'win32':
            self.set_show_icons(False)
            self.set_show_numbers(True)

        rfilter = gtk.RecentFilter()
        rfilter.add_pixbuf_formats()

        mimetypes, patterns = itertools.izip(constants.ZIP_FORMATS,
                constants.RAR_FORMATS, constants.TAR_FORMATS,
                constants.SZIP_FORMATS)

        for mimetype in itertools.chain.from_iterable(mimetypes):
            rfilter.add_mime_type(mimetype)

        # Win32 prefers file patterns instead of MIME types
        for pattern in itertools.chain.from_iterable(patterns):
            rfilter.add_pattern(pattern)

        self.add_filter(rfilter)
        self.connect('item_activated', self._load)
示例#6
0
    def save_file(self, filename, export=False, **options):
        thumbnail_pixbuf = self.save_doc_to_file(filename, self.doc, export=export, **options)
        if not export:
            self.filename = os.path.abspath(filename)
            gtk.recent_manager_get_default().add_full(helpers.filename2uri(self.filename),
                    {
                        'app_name': 'mypaint',
                        'app_exec': sys.argv_unicode[0].encode('utf-8'),
                        # todo: get mime_type
                        'mime_type': 'application/octet-stream'
                    }
            )

        if not thumbnail_pixbuf:
            thumbnail_pixbuf = self.doc.model.render_thumbnail()
        helpers.freedesktop_thumbnail(filename, thumbnail_pixbuf)
示例#7
0
    def welcome(self, action=None):
        """
        display a welcome window
        """
        page = gtk.Label()
        # welcome text
        text = """<span size="x-large" weight="bold">Welcome to odML-Editor</span>\n\nNow go ahead and <a href="#new">create a new document</a>."""
        for action in self.welcome_disabled_actions:
            self.enable_action(action, False)
        
        # display recently used files
        recent_filter = gtk.RecentFilter()
        odMLChooserDialog._setup_file_filter(recent_filter)
        files = filter(lambda i: recent_filter.filter(
            {'display_name': i.get_display_name(),
             'uri': i.get_uri(),
             'mime_type': i.get_mime_type()}),
            gtk.recent_manager_get_default().get_items())

        if files:
            text += """\n\nOr open a <b>recently used file</b>:\n"""
            text += "\n".join([u"""\u2022 <a href="%s">%s</a>""" % (i.get_uri(), i.get_display_name()) for i in files])
            
        page.set_markup(text)
        page.connect("activate-link", self.welcome_action)
        page.show()
        self.notebook.set_show_tabs(False)
        self.notebook.append_page(page)
示例#8
0
  def __init__(self):
    hildon.Dialog.__init__ (self)
    self.set_title('Choose a file to open')
    self.selected = None
    
    vbox = gtk.VBox()
    p1 = hildon.PannableArea()
    p1.add_with_viewport(vbox)
    
    rm = gtk.recent_manager_get_default()
    ritems = rm.get_items()
    ritems.sort(lambda x,y: y.get_modified()-x.get_modified())

    if (len(ritems)>0):
#      vbox.add(gtk.Label('Recent Files'))        

      for index,item in enumerate(ritems):
        b=hildon.Button(0,1)
        label = item.get_uri_display()
        i = gtk.image_new_from_stock(gtk.STOCK_FILE,gtk.ICON_SIZE_BUTTON)
#        i = gtk.image_new_from_icon_name(item.get_mime_type(),gtk.ICON_SIZE_BUTTON)
#        i = gtk.image_new_from_pixbuf(item.get_icon(gtk.ICON_SIZE_LARGE_TOOLBAR))
        b.set_image(i)
        b.set_title(os.path.basename(label))
        b.set_value(label)
        b.set_alignment(0.0,0.0,0.0,0.5)
        vbox.add(b)
        b.connect("clicked", self._clicked, label)
    
#    vbox
    p1.set_size_request(-1,350)
    self.vbox.add(p1)
    self.vbox.show_all()
示例#9
0
    def __init__(self, ui, window):
        self._window = window
        self._manager = gtk.recent_manager_get_default()
        super(RecentFilesMenu, self).__init__(self._manager)

        self.set_sort_type(gtk.RECENT_SORT_MRU)
        self.set_show_tips(True)
        # Missing icons crash GTK on Win32
        if sys.platform == 'win32':
            self.set_show_icons(False)
            self.set_show_numbers(True)

        rfilter = gtk.RecentFilter()
        supported_formats = {}
        supported_formats.update(image_tools.get_supported_formats())
        supported_formats.update(archive_tools.get_supported_formats())
        for name in sorted(supported_formats):
            mime_types, extensions = supported_formats[name]
            patterns = ['*.%s' % ext for ext in extensions]
            for mime in mime_types:
                rfilter.add_mime_type(mime)
            for pat in patterns:
                rfilter.add_pattern(pat)
        self.add_filter(rfilter)

        self.connect('item_activated', self._load)
示例#10
0
 def __init__(self):
     """Initialize an :class:`Application` object."""
     aeidon.Observable.__init__(self)
     self._delegations = {}
     self.clipboard = aeidon.Clipboard()
     self.counter = itertools.count(1)
     self.extension_manager = gaupol.ExtensionManager(self)
     self.framerate_combo = None
     self.notebook = None
     self.output_window = None
     self.pages = []
     self.pattern = ""
     self.recent_manager = gtk.recent_manager_get_default()
     self.replacement = ""
     self.statusbar = None
     self.uim = None
     self.video_button = None
     self.video_toolbar = None
     self.window = None
     self.x_clipboard = gtk.Clipboard()
     self._init_delegations()
     self._init_gui()
     self.extension_manager.find_extensions()
     self.extension_manager.setup_extensions()
     self.update_gui()
     self.window.show()
示例#11
0
    def __init__(self, ui, window):
        self._window = window
        self._manager = gtk.recent_manager_get_default()
        gtk.RecentChooserMenu.__init__(self, self._manager)

        self.set_sort_type(gtk.RECENT_SORT_MRU)
        self.set_show_tips(True)
        # Missing icons crash GTK on Win32
        if sys.platform == 'win32':
            self.set_show_icons(False)
            self.set_show_numbers(True)

        rfilter = gtk.RecentFilter()
        rfilter.add_pixbuf_formats()

        mimetypes, patterns = itertools.izip(constants.ZIP_FORMATS,
                                             constants.RAR_FORMATS,
                                             constants.TAR_FORMATS,
                                             constants.SZIP_FORMATS)

        for mimetype in itertools.chain.from_iterable(mimetypes):
            rfilter.add_mime_type(mimetype)

        # Win32 prefers file patterns instead of MIME types
        for pattern in itertools.chain.from_iterable(patterns):
            rfilter.add_pattern(pattern)

        self.add_filter(rfilter)
        self.connect('item_activated', self._load)
示例#12
0
  def save_as(self):
    fsm = hildon.FileSystemModel()
#    fc = hildon.FileChooserDialog(self, gtk.FILE_CHOOSER_ACTION_SAVE,fsm)
    fc = gobject.new(hildon.FileChooserDialog, action=gtk.FILE_CHOOSER_ACTION_SAVE)
    if self.filepath != None :
      fc.set_current_folder(os.path.dirname(self.filepath))
    else:
      fc.set_current_folder(self._parent._last_opened_folder)
    fc.set_show_hidden(True)
    fc.set_do_overwrite_confirmation(False)

    fp = self.filepath
    if fp == None:
      fp = 'Untitled'
    self.set_title(os.path.basename(fp))
    self._parent._last_opened_folder = os.path.dirname(fp)
    fc.set_property('autonaming',False)
    fc.set_property('show-files',True)
#    fc.set_current_folder(os.path.dirname(fp))
    fc.set_current_name(os.path.basename(fp))
#    fc.set_extension('py')
    if fc.run()==gtk.RESPONSE_OK:
      filepath = fc.get_filename()
      fc.destroy()
      if type(filepath) == str: # fix #19 - fix #23
        self.save_file(filepath)
        manager = gtk.recent_manager_get_default()
        manager.add_item('file://'+filepath)
      else:
        note = osso.SystemNote(self._parent.context)
        result = note.system_note_dialog('An error occurs saving file :\n'+str(filepath))

    else:
      fc.destroy()
示例#13
0
    def create_documents_submenu(self, menu):
        recent_manager = gtk.recent_manager_get_default()

        chooser_menu = gtk.RecentChooserMenu(recent_manager)
        recent_item = self.append_menu_item(menu, _("Recent Documents"),
                                            "document-open-recent", None)
        recent_item.set_submenu(chooser_menu)

        def set_sensitivity_recent_menu(widget=None):
            recent_item.set_sensitive(recent_manager.props.size > 0)

        recent_manager.connect("changed", set_sensitivity_recent_menu)
        set_sensitivity_recent_menu()

        def open_recent_document(widget):
            self.open_uri(widget.get_current_uri())

        chooser_menu.connect("item-activated", open_recent_document)

        chooser_menu.append(gtk.SeparatorMenuItem())

        item = self.append_menu_item(
            chooser_menu, _("Clear Recent Documents"), "gtk-clear",
            _("Clear all items from the recent documents list"))
        clear_dialog = self.ClearRecentDocumentsDialog(
            self.applet, recent_manager.purge_items)

        def purge_items_cb(widget):
            clear_dialog.show_all()
            clear_dialog.deiconify()

        item.connect("activate", purge_items_cb)
示例#14
0
    def __init__(self):
        self.current = 0
        self.buffers = []
        self.config = config
        gui = GUI()
        state['gui'] = gui
        self.preferences = Preferences()
        try:
            self.recent_manager = gtk.recent_manager_get_default()
        except AttributeError:
            self.recent_manager = None
        self.status = gui.status
        self.revision_status = gui.revision_status
        self.window = gui.window
        self.window.add_accel_group(make_accel_group(self))
        self.textbox = gui.textbox
        self.UNNAMED_FILENAME = FILE_UNNAMED

        self.autosave_timeout_id = ''
        self.autosave_elapsed = ''

        self.textbox.connect('key-press-event', self.key_press_event)

        # Autosave timer object
        autosave.start_autosave(self)

        self.window.show_all()
        self.window.fullscreen()

        # Handle multiple monitors
        screen = gtk.gdk.screen_get_default()
        root_window = screen.get_root_window()
        mouse_x, mouse_y, mouse_mods = root_window.get_pointer()
        current_monitor_number = screen.get_monitor_at_point(mouse_x, mouse_y)
        monitor_geometry = screen.get_monitor_geometry(current_monitor_number)
        self.window.move(monitor_geometry.x, monitor_geometry.y)

        # Defines the glade file functions for use on closing a buffer or exit
        gladefile = os.path.join(state['absolute_path'], "interface.glade")
        builder = gtk.Builder()
        builder.add_from_file(gladefile)
        self.dialog = builder.get_object("SaveBuffer")
        self.dialog.set_transient_for(self.window)
        self.quitdialog = builder.get_object("QuitSave")
        self.quitdialog.set_transient_for(self.window)
        dic = {
            "on_button-close_clicked": self.unsave_dialog,
            "on_button-cancel_clicked": self.cancel_dialog,
            "on_button-save_clicked": self.save_dialog,
            "on_button-close2_clicked": self.quit_quit,
            "on_button-cancel2_clicked": self.cancel_quit,
            "on_button-save2_clicked": self.save_quit,
        }
        builder.connect_signals(dic)

        self.keybindings = define_keybindings(self)
        # this sucks, shouldn't have to call this here, textbox should
        # have its background and padding color from GUI().__init__() already
        gui.apply_theme()
示例#15
0
    def __init__(self):
        self.current = 0
        self.buffers = []
        self.config = config
        gui = GUI()
        state['gui'] = gui
        self.preferences = Preferences()
        try:
            self.recent_manager = gtk.recent_manager_get_default()
        except AttributeError:
            self.recent_manager = None
        self.status = gui.status
        self.revision_status = gui.revision_status
        self.window = gui.window
        self.window.add_accel_group(make_accel_group(self))
        self.textbox = gui.textbox
        self.UNNAMED_FILENAME = FILE_UNNAMED

        self.autosave_timeout_id = ''
        self.autosave_elapsed = ''

        self.textbox.connect('key-press-event', self.key_press_event)

        # Autosave timer object
        autosave.start_autosave(self)

        self.window.show_all()
        self.window.fullscreen()

        # Handle multiple monitors
        screen = gtk.gdk.screen_get_default()
        root_window = screen.get_root_window()
        mouse_x, mouse_y, mouse_mods = root_window.get_pointer()
        current_monitor_number = screen.get_monitor_at_point(mouse_x, mouse_y)
        monitor_geometry = screen.get_monitor_geometry(current_monitor_number)
        self.window.move(monitor_geometry.x, monitor_geometry.y)

        # Defines the glade file functions for use on closing a buffer or exit
        gladefile = os.path.join(state['absolute_path'], "interface.glade")
        builder = gtk.Builder()
        builder.add_from_file(gladefile)
        self.dialog = builder.get_object("SaveBuffer")
        self.dialog.set_transient_for(self.window)
        self.quitdialog = builder.get_object("QuitSave")
        self.quitdialog.set_transient_for(self.window)
        dic = {
                "on_button-close_clicked": self.unsave_dialog,
                "on_button-cancel_clicked": self.cancel_dialog,
                "on_button-save_clicked": self.save_dialog,
                "on_button-close2_clicked": self.quit_quit,
                "on_button-cancel2_clicked": self.cancel_quit,
                "on_button-save2_clicked": self.save_quit,
                }
        builder.connect_signals(dic)

        self.keybindings = define_keybindings(self)
        # this sucks, shouldn't have to call this here, textbox should
        # have its background and padding color from GUI().__init__() already
        gui.apply_theme()
示例#16
0
 def __get_infos(self):
     from gtk import recent_manager_get_default
     infos = iter(recent_manager_get_default().get_items())
     scribes_infos = (info for info in infos
                      if self.__is_scribes_resource(info))
     exist_infos = (info for info in scribes_infos
                    if self.__resource_exists(info))
     return sorted(exist_infos, cmp=self.__compare, reverse=True)
示例#17
0
 def add_recent(self, uri):
     manager = gtk.recent_manager_get_default()
     app_exec = "playitslowly \"%s\"" % uri
     mime_type = mimetypes.guess_type(uri)[0]
     if mime_type:
         manager.add_full(uri, {
             "app_name": "playitslowly",
             "app_exec": "playitslowly",
             "mime_type": mime_type
         })
示例#18
0
 def add_recent(self, uri):
     manager = gtk.recent_manager_get_default()
     app_exec = "playitslowly \"%s\"" % uri
     mime_type, certain = gio.content_type_guess(uri, want_uncertain=True)
     if mime_type:
         manager.add_full(uri, {
             "app_name": "playitslowly",
             "app_exec": "playitslowly",
             "mime_type": mime_type
         })
         print app_exec, mime_type
示例#19
0
  def _create_ui(self):
    p1 = hildon.PannableArea()
    vbox = gtk.VBox()
    p1.add(vbox)

    vbox.add(gtk.Label('PyGTKEditor %s' % (self._parent.VERSION,)))
    i = gtk.Image()
    i.set_from_icon_name('pygtkeditor',gtk.ICON_SIZE_LARGE_TOOLBAR)
    vbox.add(i)

    hbox = gtk.HBox()
    new_button = hildon.Button(0,0)
    new_button.set_label('New')
    new_button.connect("clicked", self.menu_button_clicked, 'New')

    open_button = hildon.Button(0,0)
    open_button.set_label('Open')
    open_button.connect("clicked", self.open_dialog)

    hbox.add(new_button)
    hbox.add(open_button)
    vbox.add(hbox)

    self.recent_manager = gtk.recent_manager_get_default()
#    self.recent_manager.set_limit(3)
    self.recent_manager.connect('changed',self.recent_manager_changed)
    ritems=self.recent_manager.get_items()
    ritems.sort(lambda x,y: y.get_modified()-x.get_modified())

    if (len(ritems)>2):
      vbox.add(gtk.Label('Recent Files'))
      self.recent_button_1=hildon.Button(0,1)
      label = ritems[0].get_uri_display()
      self.recent_button_1.set_title(os.path.basename(label))
      self.recent_button_1.set_value(label)
      self.recent_button_1.set_alignment(0.0,0.0,0.0,0.5)
      vbox.add(self.recent_button_1)
      self.recent_button_1.connect("clicked", self.recent_button_clicked, label)
      self.recent_button_2=hildon.Button(0,1)
      label = ritems[1].get_uri_display()
      self.recent_button_2.set_title(os.path.basename(label))
      self.recent_button_2.set_value(label)
      self.recent_button_2.set_alignment(0.0,0.0,0.0,0.5)
      vbox.add(self.recent_button_2)
      self.recent_button_2.connect("clicked", self.recent_button_clicked, label)
      self.recent_button_3=hildon.Button(0,1)
      label = ritems[2].get_uri_display()
      self.recent_button_3.set_title(os.path.basename(label))
      self.recent_button_3.set_value(label)
      self.recent_button_3.set_alignment(0.0,0.0,0.0,0.5)
      vbox.add(self.recent_button_3)
      self.recent_button_3.connect("clicked", self.recent_button_clicked, label)

    return p1
示例#20
0
    def set_recent_items(self):
        # this list is consumed in open_last_cb

        # Note: i.exists() does not work on Windows if the pathname
        # contains utf-8 characters. Since GIMP also saves its URIs
        # with utf-8 characters into this list, I assume this is a
        # gtk bug.  So we use our own test instead of i.exists().
        self.recent_items = [
                i for i in gtk.recent_manager_get_default().get_items()
                if "mypaint" in i.get_applications() and os.path.exists(helpers.uri2filename(i.get_uri()))
        ]
        self.recent_items.reverse()
示例#21
0
 def add_recent(self, uri):
     manager = gtk.recent_manager_get_default()
     app_exec = "playitslowly \"%s\"" % uri
     mime_type, certain = gio.content_type_guess(uri, want_uncertain=True)
     if mime_type:
         manager.add_full(
             uri, {
                 "app_name": "playitslowly",
                 "app_exec": "playitslowly",
                 "mime_type": mime_type
             })
         print app_exec, mime_type
示例#22
0
文件: recent.py 项目: mkeane/mintmenu
    def __init__(self, mintMenuWin, toggleButton):

        self.Win = mintMenuWin
        self.toggleButton = toggleButton

        #The Glade file for the plugin
        self.gladefile = os.path.join(os.path.dirname(__file__),
                                      "recent.glade")

        #Read GLADE file
        self.wTree = gtk.glade.XML(self.gladefile, "window1")

        #Set 'window' property for the plugin (Must be the root widget)
        self.window = self.wTree.get_widget("window1")

        #Set 'heading' property for plugin
        self.heading = _("Recent documents")

        #This should be the first item added to the window in glade
        self.content_holder = self.wTree.get_widget("eventbox1")

        #Specify plugin width
        self.width = 250

        #Plugin icon
        self.icon = 'gnome-folder.png'

        self.gconf_dir = '/apps/mintMenu/plugins/recent'
        self.client = gconf.client_get_default()
        self.client.add_dir('/apps/mintMenu/plugins/recent',
                            gconf.CLIENT_PRELOAD_NONE)
        self.client.notify_add('/apps/mintMenu/plugins/recent/height',
                               self.RegenPlugin)
        self.client.notify_add('/apps/mintMenu/plugins/recent/width',
                               self.RegenPlugin)
        self.client.notify_add(
            '/apps/mintMenu/plugins/recent/num_recent_docs_to_show',
            self.RegenPlugin)
        self.client.notify_add(
            '/apps/mintMenu/plugins/recent/recent_font_size', self.RegenPlugin)

        self.FileList = []
        self.RecManagerInstance = gtk.recent_manager_get_default()
        self.RecManagerInstance.connect("changed", self.DoRecent)

        self.RegenPlugin()
        self.wTree.get_widget("RecentTabs").set_current_page(1)

        #Connect event handlers
        dic = {"on_ClrBtn_clicked": self.clrmenu}
        self.wTree.signal_autoconnect(dic)
示例#23
0
文件: viewCmd.py 项目: renyxa/re-lab
	def cli_on_open (self,wg,event,fname=None):
		home = expanduser("~")
		if fname is None:
			fname = self.app.file_open('Open',None,os.path.join(home,".oletoy"))
			if fname:
				manager = gtk.recent_manager_get_default()
				manager.add_item(fname)
		if fname:
			offset = 0
			f = open(fname,"rb")
			buf = f.read()
			if buf:
				self.cli_on_new(wg,event,buf,fname)
			f.close()
示例#24
0
	def __init__(self):
		gobject.GObject.__init__ (self)
		if not os.path.isdir(Globals.AutoStartDirectory):
			os.system('mkdir %s' % Globals.AutoStartDirectory)
		self.notifier = utils.Notifier()
		self.menuparser = MenuParser.MenuParser()
		self.menuparser.connect('menu-changed',self.MenuChanged)
		self.AppsFile = None
		self.SetFile = None
		self.menucache = {}
		self.nonMenuitems = '<Bookmarks>','<AuxiliaryFunctions>','<RecentItems>','<RecentApps>','<WebBookmarks>','<Favorites>','<Shutdown>'

		if Globals.OnlyShowFavs: 
			self.BaseMenu = '<Favorites>'
			self.menuparser.CacheApplications = None
			self.menuparser.CacheSettings = None
		elif Globals.OnlyShowRecentApps: 
			self.BaseMenu = '<RecentApps>'
			self.menuparser.CacheApplications = None
			self.menuparser.CacheSettings = None
		else:
			self.menuparser.ParseMenus()
			self.BaseMenu = self.menuparser.CacheApplications
		if isgio:
			self.monitor=gio.volume_monitor_get()
			self.monitor.connect("drive-changed",self.on_drive_changed)
			self.allgio =  gio.app_info_get_all()
		else:self.allgio = None
		self.Launcher = Launcher.Launcher()
		self.recent_manager = gtk.recent_manager_get_default()
		self.recent_manager.connect("changed", self.onRecentChanged)
		self.recents_changed = True
		self.recents = None
		self.ItemComments = {}
		self.Menu = self.BaseMenu
		self.PrevMenu = []
		self.searchresults = 0
		##### Load IconFactory##################################
		self.IconFactory = IconFactory.IconFactory()
		##### Load webbookmarks##################################
		try:
			self.webbookmarker = bookmarks.BookmarksMenu().getBookmarks()
		except:
			self.webbookmarker = None
		##### Construct the menu###########################
		self.menuitems = 'settings','places','auxiliary','recent','recentapps','webbookmarks','favorites','shutdown','all'
		for item in self.menuitems:
			#print 'Loading item to memory: ',item
			self.Restart(item)
		gc.collect()
示例#25
0
文件: cmd.py 项目: rgwan/re-lab
	def cli_on_open (self,wg,event,fname=None):
		home = expanduser("~")
		if fname is None:
			fname = self.app.file_open('Open',None,os.path.join(home,".oletoy"))
			if fname:
				manager = gtk.recent_manager_get_default()
				manager.add_item(fname)
		if fname:
			offset = 0
			f = open(fname,"rb")
			buf = f.read()
			if buf:
				self.cli_on_new(wg,event,buf,fname)
			f.close()
示例#26
0
 def init(self):
     """Initializes the application"""
     self.cb = CFAppCallbacks()
     self.__shutdown_tasks = []
     self.config = Config(self, self.options.config)
     self.userdb = UserDB(self)
     try:
         self._check_version()
     except:
         logging.exception("Exception during version update:")
     self.run_listener()
     self.plugins = PluginManager(self)
     self.datasources = DatasourceManager(self)
     self.recent_manager = gtk.recent_manager_get_default()
     autocompletion.setup(self)
示例#27
0
    def __init__(self, exec_path=None):
        self.recent_manager = gtk.recent_manager_get_default()
        self.recent_filter = gtk.RecentFilter()
        self.recent_filter.add_application(self.app_name)
        self._stored_comparisons = []
        # Should be argv[0] to support roundtripping in uninstalled use
        if exec_path:
            self.app_exec = os.path.abspath(exec_path)

        if not os.path.exists(self.recent_path):
            os.makedirs(self.recent_path)

        self._clean_recent_files()
        self._update_recent_files()
        self.recent_manager.connect("changed", self._update_recent_files)
示例#28
0
文件: recent.py 项目: d4goxn/dotfiles
    def __init__(self, exec_path=None):
        self.recent_manager = gtk.recent_manager_get_default()
        self.recent_filter = gtk.RecentFilter()
        self.recent_filter.add_application(self.app_name)
        self._stored_comparisons = []
        # Should be argv[0] to support roundtripping in uninstalled use
        if exec_path:
            self.app_exec = os.path.abspath(exec_path)

        if not os.path.exists(self.recent_path):
            os.makedirs(self.recent_path)

        self._clean_recent_files()
        self._update_recent_files()
        self.recent_manager.connect("changed", self._update_recent_files)
示例#29
0
 def init(self):
     """Initializes the application"""
     self.cb = CFAppCallbacks()
     self.__shutdown_tasks = []
     self.config = Config(self, self.options.config)
     self.userdb = UserDB(self)
     try:
         self._check_version()
     except:
         logging.exception('Exception during version update:')
     self.run_listener()
     self.plugins = PluginManager(self)
     self.datasources = DatasourceManager(self)
     self.recent_manager = gtk.recent_manager_get_default()
     autocompletion.setup(self)
示例#30
0
    def __init__( self, mintMenuWin, toggleButton, de ):

        self.Win = mintMenuWin
        self.toggleButton = toggleButton
        self.de = de

        #The Glade file for the plugin
        self.gladefile = os.path.join( os.path.dirname( __file__ ), "recent.glade" )

        #Read GLADE file
        self.wTree = gtk.glade.XML( self.gladefile, "window1" )

        #Set 'window' property for the plugin (Must be the root widget)
        self.window = self.wTree.get_widget( "window1" )

        #Set 'heading' property for plugin
        self.heading = _("Recent documents")

        #This should be the first item added to the window in glade
        self.content_holder = self.wTree.get_widget( "eventbox1" )

        #Specify plugin width
        self.width = 250

        #Plugin icon
        self.icon = 'mate-folder.png'

        self.gconf_dir = '/apps/mintMenu/plugins/recent'
        self.client = mateconf.client_get_default()
        self.client.add_dir( '/apps/mintMenu/plugins/recent', mateconf.CLIENT_PRELOAD_NONE )
        self.client.notify_add( '/apps/mintMenu/plugins/recent/height', self.RegenPlugin )
        self.client.notify_add( '/apps/mintMenu/plugins/recent/width', self.RegenPlugin )
        self.client.notify_add( '/apps/mintMenu/plugins/recent/num_recent_docs_to_show', self.RegenPlugin )
        self.client.notify_add( '/apps/mintMenu/plugins/recent/recent_font_size', self.RegenPlugin )

        self.FileList=[]
        self.RecManagerInstance = gtk.recent_manager_get_default()
        self.RecManagerInstance.connect("changed",self.DoRecent)


        self.RegenPlugin()
        self.wTree.get_widget( "RecentTabs" ).set_current_page(1)

        #Connect event handlers
        dic = { "on_ClrBtn_clicked" : self.clrmenu}
        self.wTree.signal_autoconnect( dic )
示例#31
0
    def fill(self, screen):
        if screen:
            manager = gtk.recent_manager_get_for_screen(screen)
        else:
            manager = gtk.recent_manager_get_default()

        items = manager.get_items()
        items.sort(lambda a, b: cmp(b.get_visited(), a.get_visited()))

        added = 0

        for item in items:
            if item.has_group('pluma'):
                self.append(gio.File(item.get_uri()))
                added += 1

                if added >= self._maxitems:
                    break
示例#32
0
        def fill(self, screen):
                if screen:
                        manager = gtk.recent_manager_get_for_screen(screen)
                else:
                        manager = gtk.recent_manager_get_default()

                items = manager.get_items()
                items.sort(lambda a, b: cmp(b.get_visited(), a.get_visited()))

                added = 0

                for item in items:
                        if item.has_group('gedit'):
                                self.append(gio.File(item.get_uri()))
                                added += 1

                                if added >= self._maxitems:
                                        break
示例#33
0
 def open_file(self,filepath):
   try:
     f = open(filepath,'r')
     self.filepath = os.path.abspath(filepath)
     buf = self.code_editor.get_buffer()
     buf.begin_user_action()
     text = f.read()
     f.close()
     buf.begin_not_undoable_action()
     text=text.encode('UTF-8')
     buf.set_text(text)
     buf.end_not_undoable_action()
     buf.end_user_action()
     manager = gtk.recent_manager_get_default()
     manager.add_item('file://'+filepath)
   except StandardError,e:
     print e
     note = osso.SystemNote(self._parent.context)
     result = note.system_note_dialog('An error occurs opening file :\n'+str(e))
示例#34
0
文件: viewCmd.py 项目: renyxa/re-lab
	def cli_on_save (self,wg,event):
		pn = self.clinb.get_current_page()
		if pn != -1:
			script = self.scripts[pn]
			fname = script[2].get_label_text()
			home = expanduser("~")
			fname = self.app.file_open('Save',None,script[1],fname)
			if fname:
				txt = script[0].get_text(script[0].get_start_iter(),script[0].get_end_iter())
				f = open(fname,'wb')
				f.write(txt)
				f.close()
				manager = gtk.recent_manager_get_default()
				manager.add_item(fname)
				# need to change tab label and store fname
				dname,pname = os.path.split(fname)
				script[1] = dname
				script[2].change_text(pname)
		self.save_state()
    def gnome_recent_documents_complete(pattern):
        """Find the files maching the pattern amongst the list
           of recently opened document maintained by gnome
        """
        pattern = os.path.expanduser(pattern)
        manager = gtk.recent_manager_get_default()

        for item in manager.get_items():
            uri = urlparse.urlparse(item.get_uri())
            if uri.scheme != 'file':
                continue

            path = urllib.unquote(uri.path)
            # The recent documents list can contains files that
            # have been deleted in the meantime so we also test
            # if the file really exists
            if (os.path.basename(path).startswith(pattern)
                    and os.path.exists(path)):
                yield path
示例#36
0
    def gnome_recent_documents_complete(pattern):
        """Find the files maching the pattern amongst the list
           of recently opened document maintained by gnome
        """
        pattern = os.path.expanduser(pattern)
        manager = gtk.recent_manager_get_default()

        for item in manager.get_items():
            uri = urlparse.urlparse(item.get_uri())
            if uri.scheme != 'file':
                continue

            path = urllib.unquote(uri.path)
            # The recent documents list can contains files that
            # have been deleted in the meantime so we also test
            # if the file really exists
            if (os.path.basename(path).startswith(pattern)
                    and os.path.exists(path)):
                yield path
示例#37
0
文件: cli.py 项目: AlexP11223/re-lab
	def cli_on_save (self,wg,event):
		pn = self.clinb.get_current_page()
		if pn != -1:
			script = self.scripts[pn]
			fname = script[2].get_label_text()
			home = expanduser("~")
			fname = self.app.file_open('Save',None,script[1],fname)
			if fname:
				txt = script[0].get_text(script[0].get_start_iter(),script[0].get_end_iter())
				f = open(fname,'wb')
				f.write(txt)
				f.close()
				manager = gtk.recent_manager_get_default()
				manager.add_item(fname)
				# need to change tab label and store fname
				dname,pname = os.path.split(fname)
				script[1] = dname
				script[2].change_text(pname)
		self.save_state()
示例#38
0
def _init_add():
    def ignore(filename, recent_data=None):
        return False

    # windows
    if sys.platform.startswith('win'):
        try:
            from win32ui import AddToRecentFileList

            def add(filename, recent_data=None):
                AddToRecentFileList(filename)
                return True

        except ImportError:
            return ignore

    # linux
    elif not sys.platform.startswith('darwin'):

        import urllib

        try:
            import gtk
            gtk_manager = gtk.recent_manager_get_default()
        except:
            return ignore

        def add(filename, recent_data=None):
            uri = 'file://%s' % urllib.quote(filename)
            if recent_data:
                gtk_manager.add_full(uri, recent_data)
            else:
                gtk_manager.add_item(uri)
            return True

    # mac
    else:
        return ignore

    return add
示例#39
0
文件: recent.py 项目: BRRussell/Comix
    def __init__(self, ui, window):
        self._window = window
        self._manager = gtk.recent_manager_get_default()
        gtk.RecentChooserMenu.__init__(self, self._manager)

        self.set_sort_type(gtk.RECENT_SORT_MRU)
        self.set_show_tips(True)

        rfilter = gtk.RecentFilter()
        rfilter.add_pixbuf_formats()
        rfilter.add_mime_type('application/x-zip')
        rfilter.add_mime_type('application/zip')
        rfilter.add_mime_type('application/x-rar')
        rfilter.add_mime_type('application/x-tar')
        rfilter.add_mime_type('application/x-gzip')
        rfilter.add_mime_type('application/x-bzip2')
        rfilter.add_mime_type('application/x-cbz')
        rfilter.add_mime_type('application/x-cbr')
        rfilter.add_mime_type('application/x-cbt')
        self.add_filter(rfilter)

        self.connect('item_activated', self._load)
示例#40
0
文件: recent.py 项目: yamaka67/Comix
    def __init__(self, ui, window):
        self._window = window
        self._manager = gtk.recent_manager_get_default()
        gtk.RecentChooserMenu.__init__(self, self._manager)

        self.set_sort_type(gtk.RECENT_SORT_MRU)
        self.set_show_tips(True)

        rfilter = gtk.RecentFilter()
        rfilter.add_pixbuf_formats()
        rfilter.add_mime_type('application/x-zip')
        rfilter.add_mime_type('application/zip')
        rfilter.add_mime_type('application/x-rar')
        rfilter.add_mime_type('application/x-tar')
        rfilter.add_mime_type('application/x-gzip')
        rfilter.add_mime_type('application/x-bzip2')
        rfilter.add_mime_type('application/x-cbz')
        rfilter.add_mime_type('application/x-cbr')
        rfilter.add_mime_type('application/x-cbt')
        self.add_filter(rfilter)

        self.connect('item_activated', self._load)
示例#41
0
    def _get_items(cls, max_days, for_application_named=None):
        manager = recent_manager_get_default()
        items = manager.get_items()
        item_leaves = []
        for item in items:
            if for_application_named:
                low_apps = [A.lower() for A in item.get_applications()]
                if for_application_named.lower() not in low_apps:
                    continue
            day_age = item.get_age()
            if max_days >= 0 and day_age > max_days:
                continue
            if not item.exists():
                continue

            uri = item.get_uri()
            name = item.get_short_name()
            if item.is_local():
                leaf = FileLeaf(gio.File(uri).get_path())
            else:
                leaf = UrlLeaf(uri, name)
            item_leaves.append((leaf, item.get_modified()))
        for lf, date in sorted(item_leaves, key=lambda t: t[1], reverse=True):
            yield lf
示例#42
0
	def _get_items(cls, max_days, for_application_named=None):
		manager = recent_manager_get_default()
		items = manager.get_items()
		item_leaves = []
		for item in items:
			if for_application_named:
				low_apps = [A.lower() for A in item.get_applications()]
				if for_application_named.lower() not in low_apps:
					continue
			day_age = item.get_age()
			if max_days >= 0 and day_age > max_days:
				continue
			if not item.exists():
				continue

			uri = item.get_uri()
			name = item.get_short_name()
			if item.is_local():
				leaf = FileLeaf(gio.File(uri).get_path())
			else:
				leaf = UrlLeaf(uri, name)
			item_leaves.append((leaf, item.get_modified()))
		for lf, date in sorted(item_leaves, key=lambda t: t[1], reverse=True):
			yield lf
示例#43
0
    def create_documents_submenu(self, menu):
        recent_manager = gtk.recent_manager_get_default()

        chooser_menu = gtk.RecentChooserMenu(recent_manager)
        recent_item = self.append_menu_item(menu, _("Recent Documents"), "document-open-recent", None)
        recent_item.set_submenu(chooser_menu)

        def set_sensitivity_recent_menu(widget=None):
            recent_item.set_sensitive(recent_manager.props.size > 0)
        recent_manager.connect("changed", set_sensitivity_recent_menu)
        set_sensitivity_recent_menu()

        def open_recent_document(widget):
            self.open_uri(widget.get_current_uri())
        chooser_menu.connect("item-activated", open_recent_document)

        chooser_menu.append(gtk.SeparatorMenuItem())

        item = self.append_menu_item(chooser_menu, _("Clear Recent Documents"), "gtk-clear", _("Clear all items from the recent documents list"))
        clear_dialog = self.ClearRecentDocumentsDialog(self.applet, recent_manager.purge_items)
        def purge_items_cb(widget):
            clear_dialog.show_all()
            clear_dialog.deiconify()
        item.connect("activate", purge_items_cb)
示例#44
0
    def __init__(self, file='', first_run=False):
        super(FileDialog,self).__init__('Select file', None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))

        self.file = file

        self.timer_id = None

        # Set dialog resizeable and auto-shrink
        self.set_resizable(False)
        ui.gtk2.common.set_bokken_icon(self)

        # The Ok Button.
        self.butt_ok = self.action_area.get_children()[0]
        self.butt_ok.connect("clicked", self.fast_start)
        self.butt_ok.set_sensitive(False)
        # The Cancel button.
        self.butt_cancel = self.action_area.get_children()[1]
        self.butt_cancel.connect("clicked", self.cancel)

        # Window position
        self.set_position(gtk.WIN_POS_CENTER)

        # Main Vertical Box
        self.main_vbox = gtk.VBox(False, 2)
        self.main_vbox.set_border_width(7)

        # Logo
        self.logo = gtk.Image()
        self.logo.set_from_file(datafile_path('bokken.svg'))
        # Logo label
        self.logo_text = gtk.Label()
        self.logo_text.set_markup('<span size=\'12000\'>Welcome to <b>Bokken '+glob.version+'</b></span>')

        # Common label
        self.label = gtk.Label('Select a target or enter the path manually.')
        self.label.set_padding(0, 3)
        self.label.set_alignment(0, 0.5)

        # Radare targets label
        self.radare_label = gtk.Label()
        self.radare_label.set_markup('Valid inputs are: <b>PE, ELF and mach0</b> files')
        self.radare_label.set_padding(0, 2)

        # Horizontal Separator
        self.hseparator1 = gtk.HSeparator()

        self.plugins = []

        from ui.radare_core import Core as UICore
        self.plugins = UICore.get_plugins()

        # Horizontal Separator
        self.hseparator2 = gtk.HSeparator()

        # File selection Horizontal Box
        self.hbox = gtk.HBox(False, 0)
        # TextEntry
        self.model = gtk.ListStore(str)
        self.input_entry = gtk.ComboBoxEntry(self.model, column=0)
        self.input_entry.get_child().connect("activate", self.fast_start)
        self.input_entry.connect("changed", self._validate_cb)
        #self.input_entry = gtk.Entry(100)
        if self.file:
            self.input_entry.get_child().set_text(self.file)
        # Recent file manager
        self.manager = gtk.recent_manager_get_default()
        items = self.manager.get_items()
        for element in items[:10]:
            self.model.append([element.get_uri_display()])
        # Select file button
        icon = gtk.Image()
        icon.set_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_MENU)
        self.select_button = gtk.Button()
        self.select_button.set_image(icon)
        self.select_button.connect("clicked", self.select_file)
        # Pack elements into hbox
        self.hbox.pack_start(self.input_entry, True, True, 2)
        self.hbox.pack_start(self.select_button, False, False, 2)

        # File options Horizontal Box
        self.options_hbox = gtk.HBox(False, 2)

        # Radare option Vertical Box
        self.radare_box = gtk.VBox(False, 0)
        self.vseparator = gtk.VSeparator()
        self.radare_box_2 = gtk.VBox(False, 0)
        self.radare_box_3 = gtk.VBox(False, 0)
        # pack the boxes
        self.options_hbox.pack_start(self.radare_box, True, True, 0)
        self.options_hbox.pack_start(self.vseparator, False, False, 5)
        self.options_hbox.pack_start(self.radare_box_2, True, True, 0)

        # HSeparator
        self.hseparator3 = gtk.HSeparator()
        # Analysis options label
        self.anal_label = gtk.Label()
        self.anal_label.set_markup("<b>Analysis options:</b>")
        # Advanced Analysis options label
        self.adv_anal_label = gtk.Label()
        self.adv_anal_label.set_markup("<b>Advanced options:</b>")

        # Radare options
        self.anal_bin = gtk.CheckButton(label='Analyze program')
        self.anal_bin.set_active(True)
        self.anal_bin.connect("toggled", self._no_anal)
        self.anal_depth_label = gtk.Label('Max analysis depth: ')
        self.anal_depth_entry = gtk.Entry(3)
        self.anal_depth_entry.set_width_chars(3)
        self.anal_depth_entry.set_text('16')
        self.radare_dasm = gtk.CheckButton(label='Lower case disassembly')
        self.radare_dasm.set_active(True)
        self.io_va = gtk.CheckButton(label='Don\'t use VA')
        self.asm_syntax = gtk.CheckButton(label='Use AT&T syntax')
        self.asm_bytes = gtk.CheckButton(label='Don\'t show asm bytes')

        # Bottom radare2 options
        self.hseparator5 = gtk.HSeparator()
        self.bits_label = gtk.Label('Bits:')
        self.bits = gtk.combo_box_new_text()
        #self.bits.set_size_request(70, -1)
        self.arch_label = gtk.Label('Architecture:')
        self.arch = gtk.combo_box_new_text()
        self.arch.connect("changed", self._arch_changed)
        self.arch.append_text('Auto')
        for plugin in self.plugins:
            self.arch.append_text('%s (%s)' % (plugin.name, plugin.arch))
            #self.arch.append_text('%s (%s) - %s' % (plugin.name, plugin.arch, plugin.desc))
        self.arch.set_active(0)
        self.start_addr = gtk.CheckButton(label='Start address: ')
        self.start_addr.connect("toggled", self._start_addr_ctl)
        self.start_addr_label = gtk.Label()
        self.start_addr_label.set_markup('<b>0x</b>')
        self.start_addr_label.set_padding(0, 5)
        self.start_addr_address = gtk.Entry(12)
        self.start_addr_address.set_width_chars(12)
        self.start_addr_address.set_sensitive(False)

        # More radare2 options
        self.stack_check = gtk.CheckButton(label='Show stack pointer')
        self.pseudo_check = gtk.CheckButton(label='Enable pseudo syntax')
        self.flow_lines = gtk.CheckButton(label='Show flow lines')
        self.flow_lines.connect("toggled", self._flow_lines_ctl)
        self.flow_lines_label = gtk.Label('Columns for flow lines: ')
        self.flow_lines_entry = gtk.Entry(3)
        self.flow_lines_entry.set_width_chars(3)
        self.flow_lines_entry.set_text('20')
        self.flow_lines_entry.set_sensitive(False)

        # Pack them
        self.flow_hbox = gtk.HBox(False)
        self.depth_hbox = gtk.HBox(False)
        self.radare_box_2.pack_start(self.pseudo_check, False, False, 2)
        self.radare_box_2.pack_start(self.stack_check, False, False, 2)
        self.radare_box_2.pack_start(self.asm_bytes, False, False, 2)
        self.radare_box_2.pack_start(self.flow_lines, False, False, 2)
        self.flow_hbox.pack_start(self.flow_lines_label, False, False, 2)
        self.flow_hbox.pack_start(self.flow_lines_entry, False, False, 2)
        self.radare_box_2.pack_start(self.flow_hbox, False, False, 2)
        self.depth_hbox.pack_start(self.anal_depth_label, False, False, 2)
        self.depth_hbox.pack_start(self.anal_depth_entry, False, False, 2)

        self.radare_box.pack_start(self.anal_bin, False, False, 2)
        self.radare_box.pack_start(self.depth_hbox, False, False, 2)
        self.radare_box.pack_start(self.radare_dasm, False, False, 2)
        self.radare_box.pack_start(self.io_va, False, False, 2)
        self.radare_box.pack_start(self.asm_syntax, False, False, 2)
        self.start_addr_hbox = gtk.HBox(False, 0)
        self.start_addr_hbox.pack_start(self.start_addr, False, False, 0)
        self.start_addr_hbox.pack_start(self.start_addr_label, False, False, 2)
        self.start_addr_hbox.pack_start(self.start_addr_address, True, True, 2)
        self.radare_box_3.pack_start(self.hseparator5, False, False, 5)
        self.radare_box_3.pack_start(self.adv_anal_label, False, False, 5)
        self.radare_box_3.pack_start(self.start_addr_hbox, False, False, 2)
        self.arch_hbox = gtk.HBox(False, 0)
        self.arch_hbox.pack_start(self.arch_label, False, False, 2)
        self.arch_hbox.pack_start(self.arch, True, True, 2)
        self.radare_box_3.pack_start(self.arch_hbox, False, False, 2)
        self.bits_hbox = gtk.HBox(False, 0)
        self.bits_hbox.pack_start(self.bits_label, False, False, 2)
        self.bits_hbox.pack_start(self.bits, False, False, 2)
        #self.radare_box_3.pack_start(self.bits_hbox, False, False, 2)
        self.arch_hbox.pack_start(self.bits_hbox, False, False, 2)

        # Pack elements into main_vbox
        self.main_vbox.pack_start(self.logo, False, False, 0)
        self.main_vbox.pack_start(self.logo_text, False, False, 0)
        self.main_vbox.pack_start(self.hseparator1, False, False, 2)
        self.main_vbox.pack_start(self.hseparator2, False, False, 2)
        self.main_vbox.pack_start(self.label, False, False, 2)
        self.main_vbox.pack_start(self.radare_label, False, False, 1)
        self.main_vbox.pack_start(self.hbox, False, False, 2)
        self.main_vbox.pack_start(self.hseparator3, False, False, 2)
        self.main_vbox.pack_start(self.anal_label, False, False, 2)
        self.main_vbox.pack_start(self.options_hbox, False, False, 2)
        self.main_vbox.pack_start(self.radare_box_3, False, False, 2)

        self.vbox.pack_start(self.main_vbox, True, True, 0)
        self.set_focus(self.input_entry.get_child())
        self.show_all()
示例#45
0
def add_to_recent(uri):
    if hasattr(gtk, "recent_manager_get_default"):
        # add the file to the list of recently opened files
        manager = gtk.recent_manager_get_default()
        manager.add_item(uri)
示例#46
0
from translate.storage import factory

import gtk

rf = gtk.RecentFilter()
for name, extensions, mimetypes in factory.supported_files():
    if extensions:
        for extension in extensions:
            if extension in ("txt"):
                continue
            rf.add_pattern("*.%s" % extension)
            for compress_extension in factory.decompressclass.keys():
                rf.add_pattern("*.%s.%s" % (extension, compress_extension))
    if mimetypes:
        for mimetype in mimetypes:
            rf.add_mime_type(mimetype)
for app in ("virtaal", "poedit", "kbabel", "lokalize", "gtranslator"):
    rf.add_application(app)

rm = gtk.recent_manager_get_default()

rc = gtk.RecentChooserMenu()
# For now we don't handle non-local files yet
rc.set_local_only(True)
rc.set_show_not_found(False)
rc.set_show_numbers(True)
rc.set_show_tips(True)
rc.set_sort_type(gtk.RECENT_SORT_MRU)
rc.add_filter(rf)
rc.set_limit(15)
示例#47
0
 def __init__(self):
     deskbar.interfaces.Module.__init__(self)
     self._recent_manager = gtk.recent_manager_get_default()
示例#48
0
文件: file.py 项目: jbicha/gjots2
    def write_file(self, prompt="", exporting=0, reuse_password=1):
        """
		
		Top level file writing - with prompting if necessary. If no
		prompt just use the default file and don't check about
		overwriting it.

		Always lock the file before writing - leave it locked (and
		remove any other locks) unless exporting.
		
		If exporting then only write the current selection - no need
		to change the default filename to this one; otherwise, write
		the root item and change the default filename to this one.

		If we already know the password and reuse_password is 0 then
		just save the sucker.

		Return filename on success, "" on error
		
		"""

        if self.gui.debug:
            print inspect.getframeinfo(inspect.currentframe())[2], vars()

        if self.gui.readonly or not self.filename:
            if not prompt or len(prompt) == 0:
                prompt = _("Save as ...")

        retval = ""
        while 1:  # use 'while' simply so that we can use break:
            if prompt:
                self._file_dialog(prompt, gtk.FILE_CHOOSER_ACTION_SAVE)
                if self.fileselectionValue == OK and self.prompt_filename:
                    dirname, basename = os.path.split(self.prompt_filename)

                    # we may need to use "fully expanded name" here:
                    if self.filename == self.prompt_filename:
                        if exporting:
                            self.gui.err_msg(_("That file is already open!"))
                            return ""
                        if self._check_timestamp(self.filename,
                                                 self.filename_timestamp):
                            return ""
                        retval = self._do_store(self.filename,
                                                selection=exporting,
                                                reuse_password=reuse_password)
                        if not exporting:
                            try:
                                s = os.stat(self.filename)
                                self.filename_timestamp = s.st_mtime
                            except:
                                pass
                        break

                    reason, pid = self.lock_file(self.prompt_filename)

                    if reason == 2:
                        self.gui.err_msg(
                            _("%s is locked by pid %d") % (basename, pid))
                        return ""
                    if reason == 1:
                        self.gui.err_msg(
                            _("Can't make a lockfile in ") + dirname)
                        return ""

                    # We know that the directory is writable, so we can
                    # create a file here. See if it already exists, if so,
                    # is it writable, if so should we overwrite it?:
                    try:
                        f = open(self.prompt_filename)
                        f.close()

                        if not os.access(self.prompt_filename, os.W_OK):
                            self.unlock_file(self.prompt_filename)
                            self.gui.err_msg(
                                _("%s is not writable") % basename)
                            return ""
                        general = general_dialog(
                            self.gui,
                            _("gjots2: %s already exists.") % basename,
                            _("overwrite %s?") % basename, YES | CANCEL, 0, 0,
                            "", "", "", "", "")
                        if not general.get_value() == OK:
                            self.unlock_file(self.prompt_filename)
                            return ""
                    except IOError:
                        pass

                    retval = self._do_store(self.prompt_filename,
                                            selection=exporting,
                                            reuse_password=reuse_password)
                    if exporting:
                        self.unlock_file(self.prompt_filename)
                    else:
                        if retval:
                            self.close()
                            self.filename = self.prompt_filename
                            self.gui.set_title(basename)
                            try:
                                s = os.stat(self.filename)
                                self.filename_timestamp = s.st_mtime
                            except:
                                pass
                    break
                else:  # self.fileselectionValue != OK
                    return ""
            else:  # just save the sucker
                # assert exporting == 0
                if self._check_timestamp(self.filename,
                                         self.filename_timestamp):
                    return ""
                retval = self._do_store(self.filename,
                                        selection=exporting,
                                        reuse_password=reuse_password)
                try:
                    s = os.stat(self.filename)
                    self.filename_timestamp = s.st_mtime
                except:
                    pass
                break

# developers may want to enable this to check the before & after file images:
#		if self.gui.dev:
#			os.system("meld " + self.prompt_filename + " " + self.prompt_filename + "~")

        gtk.recent_manager_get_default().add_full(
            "file://" + self.filename, {
                "mime_type": "application/gjots",
                "app_name": "gjots2",
                "app_exec": "gjots2"
            })
        return retval
示例#49
0
	def initialize(self):
		"""Set up change callback"""
		manager = recent_manager_get_default()
		gobject_connect_weakly(manager, "changed", self._recent_changed)
示例#50
0
    def __init__(self, has_pyew, has_radare, core='', file=''):
        super(FileDialog,
              self).__init__('Select file', None,
                             gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                             (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                              gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))

        self.has_pyew = has_pyew
        self.has_radare = has_radare

        self.core = core
        self.file = file

        self.timer_id = None

        # Set dialog resizeable and auto-shrink
        self.set_policy(False, False, True)
        self.set_icon_from_file(
            os.path.dirname(__file__) + os.sep + 'data' + os.sep +
            'bokken.svg')

        # the cancel button
        self.butt_ok = self.action_area.get_children()[0]
        self.butt_ok.connect("clicked", self.fast_start)
        self.butt_cancel = self.action_area.get_children()[1]
        #self.butt_cancel.connect("clicked", self.cancel)

        # Window position
        self.set_position(gtk.WIN_POS_CENTER)

        # Main Vertical Box
        self.main_vbox = gtk.VBox(False, 2)
        self.main_vbox.set_border_width(7)

        # Logo
        self.logo = gtk.Image()
        self.logo.set_from_file(
            os.path.dirname(__file__) + os.sep + 'data' + os.sep +
            'bokken.svg')
        # Logo label
        self.logo_text = gtk.Label()
        self.logo_text.set_markup(
            '<span size=\'12000\'>Welcome to <b>Bokken 1.5</b></span>')

        # Common label
        self.label = gtk.Label('Select a target or enter the path manually.')
        self.label.set_padding(0, 3)
        self.label.set_alignment(0, 0.5)

        # Pyew targets label
        self.pyew_label = gtk.Label()
        self.pyew_label.set_markup(
            'Valid inputs are: <b>PE/ELF, PDF, plain text files and URLs</b>')
        self.pyew_label.set_padding(0, 2)

        # Radare targets label
        self.radare_label = gtk.Label()
        self.radare_label.set_markup(
            'Valid inputs are: <b>PE, ELF, mach0 and java/dex classes</b>')
        self.radare_label.set_padding(0, 2)

        # Horizontal Separator
        self.hseparator1 = gtk.HSeparator()

        # Core selection label and combo
        self.core_label = gtk.Label('Select backend to use: ')
        self.core_label.set_alignment(0, 0.5)
        self.core_combo = gtk.combo_box_new_text()

        if self.has_pyew:
            self.core_combo.append_text('Pyew')
        if self.has_radare:
            self.core_combo.append_text('Radare')

        if not self.core:
            self.core_combo.set_active(0)
        elif self.has_radare != self.has_pyew:
            self.core_combo.set_active(0)
        elif self.core == 'pyew':
            self.core_combo.set_active(0)
        elif self.core == 'radare':
            self.core_combo.set_active(1)
        self.core = self.core_combo.get_active_text().lower()

        # Core combo Horizontal Box
        self.core_hbox = gtk.HBox(False, 0)
        self.core_hbox.pack_start(self.core_label, True, True, 2)
        self.core_hbox.pack_start(self.core_combo, False, False, 2)
        # Horizontal Separator
        self.hseparator2 = gtk.HSeparator()

        # File selection Horizontal Box
        self.hbox = gtk.HBox(False, 0)
        # TextEntry
        self.model = gtk.ListStore(str)
        self.input_entry = gtk.ComboBoxEntry(self.model, column=0)
        self.input_entry.get_child().connect("activate", self.fast_start)
        self.input_entry.connect("changed", self._validate_cb)
        #self.input_entry = gtk.Entry(100)
        if self.file:
            self.input_entry.get_child().set_text(self.file)
        # Recent file manager
        self.manager = gtk.recent_manager_get_default()
        items = self.manager.get_items()
        for element in items[:10]:
            self.model.append([element.get_display_name()])
        # Select file button
        icon = gtk.Image()
        icon.set_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_MENU)
        self.select_button = gtk.Button()
        self.select_button.set_image(icon)
        self.select_button.connect("clicked", self.select_file)
        # Pack elements into hbox
        self.hbox.pack_start(self.input_entry, True, True, 2)
        self.hbox.pack_start(self.select_button, False, False, 2)

        # File options Horizontal Box
        self.options_hbox = gtk.HBox(False, 2)
        # Pyew option Vertical Box
        self.pyew_box = gtk.VBox(False, 0)
        # Radare option Vertical Box
        self.radare_box = gtk.VBox(False, 0)
        # pack the boxes
        self.options_hbox.pack_start(self.pyew_box, False, False, 0)
        self.options_hbox.pack_start(self.radare_box, False, False, 0)

        # HSeparator
        self.hseparator3 = gtk.HSeparator()
        # Analysis options label
        self.anal_label = gtk.Label()
        self.anal_label.set_markup("<b>Analysis options:</b>")

        # Pyew options
        self.deep_anal = gtk.CheckButton(label='Deep analysis')
        self.case_dasm = gtk.CheckButton(label='Lower case disassembly')
        self.case_dasm.set_active(True)
        self.pyew_box.pack_start(self.deep_anal, False, False, 2)
        self.pyew_box.pack_start(self.case_dasm, False, False, 2)
        # It's here to avoid errors during start up
        self.core_combo.connect("changed", self._on_change)

        # Radare options
        self.anal_bin = gtk.CheckButton(label='Analyze program')
        self.anal_bin.set_active(True)
        self.radare_dasm = gtk.CheckButton(label='Lower case disassembly')
        self.radare_dasm.set_active(True)
        self.io_va = gtk.CheckButton(label='Don\'t use VA')
        self.asm_syntax = gtk.CheckButton(label='Use AT&T syntax')
        self.asm_bytes = gtk.CheckButton(label='Don\'t show asm bytes')
        self.anal_bin.connect("toggled", self._no_anal)
        self.radare_box.pack_start(self.anal_bin, False, False, 2)
        self.radare_box.pack_start(self.radare_dasm, False, False, 2)
        self.radare_box.pack_start(self.io_va, False, False, 2)
        self.radare_box.pack_start(self.asm_syntax, False, False, 2)
        self.radare_box.pack_start(self.asm_bytes, False, False, 2)

        # Pack elements into main_vbox
        self.main_vbox.pack_start(self.logo, False, False, 0)
        self.main_vbox.pack_start(self.logo_text, False, False, 0)
        self.main_vbox.pack_start(self.hseparator1, False, False, 2)
        self.main_vbox.pack_start(self.core_hbox, False, False, 2)
        self.main_vbox.pack_start(self.hseparator2, False, False, 2)
        self.main_vbox.pack_start(self.label, False, False, 2)
        self.main_vbox.pack_start(self.pyew_label, False, False, 1)
        self.main_vbox.pack_start(self.radare_label, False, False, 1)
        self.main_vbox.pack_start(self.hbox, False, False, 2)
        self.main_vbox.pack_start(self.hseparator3, False, False, 2)
        self.main_vbox.pack_start(self.anal_label, False, False, 2)
        self.main_vbox.pack_start(self.options_hbox, False, False, 2)

        self.vbox.pack_start(self.main_vbox)
        self.set_focus(self.input_entry.get_child())
        self.show_all()

        if self.core == 'pyew':
            self.radare_box.set_visible(False)
            self.radare_label.set_visible(False)
        elif self.core == 'radare':
            self.pyew_box.set_visible(False)
            self.pyew_label.set_visible(False)
        else:
            self.radare_box.set_visible(False)
            self.radare_label.set_visible(False)
示例#51
0
    def __init__(self):
        RecentlyUsedManager.__init__(self)
        self.recent_manager = gtk.recent_manager_get_default()
        self.recent_manager.set_limit(-1)

        self.recent_manager.connect("changed", lambda m: self.emit("reload"))
示例#52
0
    def __init__(self, pyroom_config):
        self.current = 0
        self.buffers = []
        self.config = pyroom_config.config
        self.gui = GUI(pyroom_config, self)
        self.preferences = Preferences(gui=self.gui,
                                       pyroom_config=pyroom_config)
        try:
            self.recent_manager = gtk.recent_manager_get_default()
        except AttributeError:
            self.recent_manager = None
        self.status = self.gui.status
        self.window = self.gui.window
        self.window.add_accel_group(make_accel_group(self))
        self.textbox = self.gui.textbox
        self.UNNAMED_FILENAME = FILE_UNNAMED

        self.autosave_timeout_id = ''
        self.autosave_elapsed = ''

        self.new_buffer()

        self.textbox.connect('key-press-event', self.key_press_event)

        self.textbox.set_pixels_below_lines(
            int(self.config.get("visual", "linespacing")))
        self.textbox.set_pixels_above_lines(
            int(self.config.get("visual", "linespacing")))
        self.textbox.set_pixels_inside_wrap(
            int(self.config.get("visual", "linespacing")))

        # Autosave timer object
        autosave.start_autosave(self)

        self.window.show_all()
        self.window.fullscreen()

        # Handle multiple monitors
        screen = gtk.gdk.screen_get_default()
        root_window = screen.get_root_window()
        mouse_x, mouse_y, mouse_mods = root_window.get_pointer()
        current_monitor_number = screen.get_monitor_at_point(mouse_x, mouse_y)
        monitor_geometry = screen.get_monitor_geometry(current_monitor_number)
        self.window.move(monitor_geometry.x, monitor_geometry.y)
        self.window.set_geometry_hints(None,
                                       min_width=monitor_geometry.width,
                                       min_height=monitor_geometry.height,
                                       max_width=monitor_geometry.width,
                                       max_height=monitor_geometry.height)

        # Defines the glade file functions for use on closing a buffer
        self.wTree = gtk.glade.XML(
            os.path.join(pyroom_config.pyroom_absolute_path,
                         "interface.glade"), "SaveBuffer")
        self.dialog = self.wTree.get_widget("SaveBuffer")
        self.dialog.set_transient_for(self.window)
        dic = {
            "on_button-close_clicked": self.unsave_dialog,
            "on_button-cancel_clicked": self.cancel_dialog,
            "on_button-save_clicked": self.save_dialog,
        }
        self.wTree.signal_autoconnect(dic)

        #Defines the glade file functions for use on exit
        self.aTree = gtk.glade.XML(
            os.path.join(pyroom_config.pyroom_absolute_path,
                         "interface.glade"), "QuitSave")
        self.quitdialog = self.aTree.get_widget("QuitSave")
        self.quitdialog.set_transient_for(self.window)
        dic = {
            "on_button-close2_clicked": self.quit_quit,
            "on_button-cancel2_clicked": self.cancel_quit,
            "on_button-save2_clicked": self.save_quit,
        }
        self.aTree.signal_autoconnect(dic)
        self.keybindings = define_keybindings(self)
        # this sucks, shouldn't have to call this here, textbox should
        # have its background and padding color from GUI().__init__() already
        self.gui.apply_theme()
示例#53
0
def run():
    try:
        global gui
        global mainwin
        global sb2
        global ser
        global id
        global nb
        global tw
        global sctw
        global sb
        global sertime
        global vbox
        global con
        global scon
        global p
        global b
        global pgm
        global recentmanager
        locale_path = _search_locales()
        gettext.bindtextdomain(APP_NAME, locale_path)
        gettext.textdomain(APP_NAME)
        locale.bindtextdomain(APP_NAME, locale_path)
        #global spinner
        #perform cleanup prior to this
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        id = misc.makeWorkdir()
        ser = serialio.sconsole()
        p = prefs.preferences()
        recentmanager = gtk.recent_manager_get_default()
        sertime = None
        gui = gtk.Builder()
        gui.set_translation_domain(APP_NAME)
        try:
            path = os.path.join(os.getcwd(), "ui", "main.ui")
            if os.path.exists(path):
                gui.add_from_file(path)
            else:
                raise NameError(_("System error"))
        except:
            try:
                path = os.path.join(sys.prefix, "local", "share", "gnoduino",
                                    "ui", "main.ui")
                if os.path.exists(path):
                    gui.add_from_file(path)
                else:
                    raise NameError(_("System error"))
            except:
                try:
                    path = os.path.join(sys.prefix, "share", "gnoduino", "ui",
                                        "main.ui")
                    if os.path.exists(path):
                        gui.add_from_file(path)
                    else:
                        raise NameError(_("System error"))
                except Exception, e:
                    print(e)
                    raise SystemExit(_("Cannot load ui file"))
        mainwin = gui.get_object("top_win")
        mainwin.set_icon_from_file(misc.getPixmapPath("gnoduino.png"))
        mw = int(p.getSafeValue("default.window.width", 640))
        mh = int(p.getSafeValue("default.window.height", 480))
        if (mw and mh):
            mainwin.set_default_size(mw, mh)
        mainwin.connect("configure-event", cb_configure_event)
        mainwin.connect("key-press-event", getKeyPEvent)
        mainwin.connect("key-release-event", getKeyREvent)
        vbox = gui.get_object("vpan")
        sb = gui.get_object("statusbar1")
        sb.set_has_resize_grip(False)
        sb2 = gui.get_object("statusbar2")
        sb2.set_has_resize_grip(False)
        setupSpinner()
        config.cur_editor_font = p.getSafeValue(
            "editor.font", p.getDefaultValue("editor.font")).replace(",", " ")
        config.cur_console_font = p.getSafeValue(
            "console.font",
            p.getDefaultValue("console.font")).replace(",", " ")
        config.build_verbose = p.getSafeValue(
            "build.verbose", p.getDefaultValue("build.verbose"))
        config.show_numbers = p.getSafeValue("show.numbers",
                                             p.getDefaultValue("show.numbers"))
        config.user_library = p.getValue("user.library")
        menu(gui)
        """build menus"""
        sub = gtk.Menu()
        b = board.Board()
        pgm = programmer.Programmer()
        maingroup = gtk.RadioMenuItem(None, None)
        for i in b.getBoards():
            menuItem = gtk.RadioMenuItem(maingroup, i['desc'])
            if i['id'] == b.getBoard() + 1:
                menuItem.set_active(True)
            menuItem.connect('toggled', selectBoard, i['id'])
            sub.append(menuItem)
        gui.get_object("board").set_submenu(sub)
        (con, tw) = createCon()
        misc.setConsoleTags(tw)
        """setup default serial port"""
        if config.serial_baud_rate == -1:
            config.serial_baud_rate = p.getSafeValue(
                "serial.debug_rate", p.getDefaultValue("serial.debug_rate"))
        getSerialPorts()
        populateSerialPortMenu()
        glib.timeout_add(1000, getSerialPorts)
        createRecentMenu()
        populateExamples()
        populateImport()

        sub = gtk.Menu()
        maingroup = gtk.RadioMenuItem(None, None)
        for i in pgm.getProgrammers():
            menuItem = gtk.RadioMenuItem(maingroup, i['desc'])
            if i['id'] == pgm.getProgrammer() + 1:
                menuItem.set_active(True)
            menuItem.connect('activate', selectProgrammer, i['id'])
            sub.append(menuItem)
        gui.get_object("programmer").set_submenu(sub)
        gui.get_object("burn").connect('activate', burnBootloader)

        nb = gtk.Notebook()
        nb.connect("switch-page", setupPage)
        sv = createPage(nb)
        vbox.pack1(nb, shrink=True, resize=True)
        (scon, sctw) = createScon()
        vbox.pack2(con, shrink=False, resize=False)
        vbox.connect("notify::position", vbox_move_handle)
        cpos = int(p.getSafeValue("console.height", mh - 120))
        vbox.set_position(cpos)

        mainwin.set_focus(sv)
        mainwin.show_all()
        mainwin.connect("delete-event", quit)
        gui.get_object("ser_monitor").connect("activate", cserial, sertime,
                                              sctw)
        gui.get_object("serial").connect("clicked", cserial, sertime, sctw)
        gui.get_object("upload").connect("clicked", upload, ser)
        for i in buttons:
            w = gtk.Image()
            w.set_from_file(misc.getPixmapPath(i[1]))
            o = gui.get_object(i[0])
            o.set_icon_widget(w)
            o.show_all()
            if i[2] != None:
                o.connect("clicked", i[2])
        if (sys.argv[1:]):
            if sys.argv[1:][0] == "--help" or sys.argv[1:][0] == "-h":
                print _("--help    Print the command line options")
                print _("--version Output version information and exit")
                sys.exit(0)
            if sys.argv[1:][0] == "--version" or sys.argv[1:][0] == "-v":
                print "gnoduino %s" % gnoduino.__version__
                sys.exit(0)
            for f in sys.argv[1:]:
                processFile(f)
        gtk.main()
示例#54
0
    def __init__(self, core, main):
        super(TopButtons,self).__init__(False, 1)

        self.main = main

        self.uicore = core
        self.toolbox = self
        self.dependency_check = self.main.dependency_check

        self.img_path = os.path.dirname(__file__) + os.sep + 'data' + os.sep
        self.options_dict = {'String':' ', 'String no case':'i ', 'Hexadecimal':'x ', 'Regexp':'e '}

        self.main_tb = gtk.Toolbar()
        self.main_tb.set_style(gtk.TOOLBAR_ICONS)

        # New file button
        self.new_tb = gtk.MenuToolButton(gtk.STOCK_NEW)
        self.new_tb.set_label('New')
        self.new_tb.set_tooltip_text('Open new file')
        self.new_tb.connect("clicked", self.new_file)
        self.main_tb.insert(self.new_tb, 0)

        # Recent files menu
        self.manager = gtk.recent_manager_get_default()
        self.recent_menu = gtk.RecentChooserMenu(self.manager)
        self.new_tb.set_menu(self.recent_menu)
        self.new_tb.set_arrow_tooltip_text('Recent opened files')
        self.recent_menu.connect('item-activated', self.recent_kb)

        # Separator
        self.sep = gtk.SeparatorToolItem()
        self.main_tb.insert(self.sep, 1)

        # Assembler button
        self.asm_tb = gtk.ToolButton(gtk.STOCK_EXECUTE)
        self.asm_tb.set_tooltip_text('Open assembler dialog')
        self.asm_tb.connect("clicked", self._assembler)
        self.main_tb.insert(self.asm_tb, 2)

        # Bindiff button
        self.diff_tb = gtk.ToolButton(gtk.STOCK_REFRESH)
        self.diff_tb.set_tooltip_text('Do binary diffing')
        self.diff_tb.connect("clicked", self._do_diff)
        self.main_tb.insert(self.diff_tb, 3)

        # Section bars button
        self.sections_tb = gtk.ToolButton(gtk.STOCK_SORT_ASCENDING)
        self.sections_tb.set_tooltip_text('Extended sections information')
        self.sections_tb.connect("clicked", self._do_sections)
        self.main_tb.insert(self.sections_tb, 4)

        # Calculator button
        self.image = gtk.Image()
        self.image.set_from_file(os.path.dirname(__file__)+os.sep+'data'+os.sep+'calc.png')
        self.calc_tb = gtk.ToolButton()
        self.calc_tb.set_icon_widget(self.image)
        self.calc_tb.set_tooltip_text('Show calculator')
        self.calc_tb.connect("clicked", self._do_calc)
        self.main_tb.insert(self.calc_tb, 5)

        # File magic button
        self.magic_tb = gtk.ToolButton(gtk.STOCK_INFO)
        self.magic_tb.set_tooltip_text('Show file magic')
        self.magic_tb.connect("clicked", self._do_file_magic)
        self.main_tb.insert(self.magic_tb, 6)

        # Separator
        self.sep = gtk.SeparatorToolItem()
        self.main_tb.insert(self.sep, 7)

        # Search components
        self.search_combo_tb = gtk.ToolItem()
        self.search_combo_align = gtk.Alignment(yalign=0.5)
        store = gtk.ListStore(gtk.gdk.Pixbuf, str)
        self.search_combo = gtk.ComboBox(store)
        rendererText = gtk.CellRendererText()
        rendererPix = gtk.CellRendererPixbuf()
        self.search_combo.pack_start(rendererPix, False)
        self.search_combo.pack_start(rendererText, True)
        self.search_combo.add_attribute(rendererPix, 'pixbuf', 0)
        self.search_combo.add_attribute(rendererText, 'text', 1)

        options = {
            'String':gtk.gdk.pixbuf_new_from_file(os.path.dirname(__file__) + os.sep + 'data' + os.sep + 'icon_string_16.png'),
            'String no case':gtk.gdk.pixbuf_new_from_file(os.path.dirname(__file__) + os.sep + 'data' + os.sep + 'icon_string_no_case_16.png'),
            'Hexadecimal':gtk.gdk.pixbuf_new_from_file(os.path.dirname(__file__) + os.sep + 'data' + os.sep + 'icon_hexadecimal_16.png'),
            'Regexp':gtk.gdk.pixbuf_new_from_file(os.path.dirname(__file__) + os.sep + 'data' + os.sep + 'icon_regexp_16.png')
        }

        for option in options.keys():
            store.append([options[option], option])
        self.search_combo.set_active(0)
        self.search_combo_align.add(self.search_combo)
        self.search_combo_tb.add(self.search_combo_align)
        self.main_tb.insert(self.search_combo_tb, 8)

        # Separator
        self.sep = gtk.SeparatorToolItem()
        self.sep.set_draw(False)
        self.main_tb.insert(self.sep, 9)

        self.search_entry_tb = gtk.ToolItem()
        self.search_entry = gtk.Entry(100)
        self.search_entry.set_text('Text to search')
        self.search_entry.set_icon_from_stock(1, gtk.STOCK_FIND)
        self.search_entry.set_icon_tooltip_text(1, 'Search')
        self.search_entry.connect("activate", self.search)
        self.search_entry.connect("icon-press", self.search)
        self.search_entry.connect('focus-in-event', self._clean, 'in')
        self.search_entry.connect('focus-out-event', self._clean, 'out')
        self.search_entry_tb.add(self.search_entry)
        self.main_tb.insert(self.search_entry_tb, 10)

        # Separator
        self.sep = gtk.SeparatorToolItem()
        self.main_tb.insert(self.sep, 11)

        # Cheatsheet button
        self.cheatsheet_tb = gtk.ToolButton(gtk.STOCK_JUSTIFY_FILL)
        self.cheatsheet_tb.set_tooltip_text('Show assembler reference sheet')
        self.cheatsheet_tb.connect("clicked", self.create_cheatsheet_dialog)
        self.main_tb.insert(self.cheatsheet_tb, 12)

        # Separator
        self.sep = gtk.SeparatorToolItem()
        self.sep.set_expand(True)
        self.sep.set_draw(False)
        self.main_tb.insert(self.sep, 13)

        # Exit button
        self.exit_tb = gtk.ToolButton(gtk.STOCK_QUIT)
        self.exit_tb.set_label('Quit')
        self.exit_tb.connect("clicked", self.main.quit)
        self.exit_tb.set_tooltip_text('Have a nice day ;-)')
        self.main_tb.insert(self.exit_tb, 14)

        # Throbber
        self.throbber = throbber.Throbber()
        self.throbber_tb = gtk.ToolItem()
        self.throbber_tb.add(self.throbber)
        self.main_tb.insert(self.throbber_tb, 15)

        self.toolbox.pack_start(self.main_tb, True, True)

        self.show_all()
示例#55
0
文件: gui.py 项目: mlang/freedots
 def open(self, filename):
     self.score = musicxml.Score(filename)
     self.update_buffer()
     gtk.recent_manager_get_default().add_item(filename)
     self.openFileActionGroup.set_sensitive(True)
示例#56
0
    def create_menu_bar_and_toolbar(self, main_box):
        debug(DEBUG_WINDOW)

        manager = gtk.UIManager()
        self._manager = manager

        self.add_accel_group(manager.get_accel_group())

        action_group = gtk.ActionGroup("TalukaWindowAlwaysSensitiveActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        action_group.add_actions(always_sensitive_menu_entries, self)
        action_group.add_toggle_actions(always_sensitive_toggle_menu_entries,
                                        self)

        manager.insert_action_group(action_group, 0)
        #g_object_unref (action_group); FIXME: Do i need this?
        self._always_sensitive_action_group = action_group

        action_group = gtk.ActionGroup("TalukaWindowActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        action_group.add_actions(menu_entries, self)
        manager.insert_action_group(action_group, 0)
        #g_object_unref (action_group); FIXME see above
        self._action_group = action_group

        # set short labels to use in the toolbar
        action = action_group.get_action("FileSave")
        action.set_property("short_label", _("Save"))
        #		action = action_group.get_action("FilePrint") TODO Don't forget to uncomment these lines
        #		action.set_property("short_label", _("Print"))
        #		action = action_group.get_action("SearchFind")
        #		action.set_property("short_label", _("Find"))
        #		action = action_group.get_action("SearchReplace")
        #		action.set_property("short_label", _("Replace"))

        # set which actions should have priority on the toolbar
        action = action_group.get_action("FileSave")
        action.set_property("is_important", True)
        action = action_group.get_action("EditUndo")
        action.set_property("is_important", True)

        action_group = gtk.ActionGroup("TalukaQuitWindowActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        action_group.add_actions(quit_menu_entries, self)

        manager.insert_action_group(action_group, 0)
        #g_object_unref (action_group); FIXME: see above
        self._quit_action_group = action_group

        action_group = gtk.ActionGroup("TalukaCloseWindowActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        action_group.add_actions(close_menu_entries, self)

        manager.insert_action_group(action_group, 0)
        #g_object_unref (action_group); FIXME
        self._close_action_group = action_group

        action_group = gtk.ActionGroup("TalukaWindowPanesActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        action_group.add_toggle_actions(panes_toggle_menu_entries, self)

        manager.insert_action_group(action_group, 0)
        #g_object_unref (action_group); FIXME
        self._panes_action_group = action_group

        # now load the UI definition
        ui_file = os.path.join(reloc.DATADIR, 'taluka/taluka-ui.xml')
        manager.add_ui_from_file(ui_file)

        # show tooltips in the statusbar
        manager.connect("connect_proxy", connect_proxy_cb, self)
        manager.connect("disconnect_proxy", disconnect_proxy_cb, self)

        # recent files menu
        action_group = gtk.ActionGroup("RecentFilesActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        self._recents_action_group = action_group
        manager.insert_action_group(action_group, 0)
        #g_object_unref (action_group); FIXME see above

        recent_manager = gtk.recent_manager_get_default()
        self._recents_handler_id = recent_manager.connect(
            "changed", recent_manager_changed, self)
        self.update_recent_files_menu()

        # languages menu
        action_group = gtk.ActionGroup("LanguagesActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        self._languages_action_group = action_group
        manager.insert_action_group(action_group, 0)
        self.create_languages_menu()

        # list of open documents menu
        action_group = gtk.ActionGroup("DocumentsListActions")
        action_group.set_translation_domain(
            "")  # TODO: Should it be NULL instead of ""?
        self._documents_list_action_group = action_group
        manager.insert_action_group(action_group, 0)

        self._menubar = manager.get_widget("/MenuBar")
        main_box.pack_start(self._menubar, False, False, 0)

        self._toolbar = manager.get_widget("/ToolBar")
        main_box.pack_start(self._toolbar, False, False, 0)

        self.set_toolbar_style(None)

        self._toolbar_recent_menu = self.setup_toolbar_open_button(
            self._toolbar)

        self._toolbar.foreach(set_non_homogeneus)

        self._toolbar.connect_after("show", self.toolbar_visibility_changed)
        self._toolbar.connect_after("hide", self.toolbar_visibility_changed)
示例#57
0
文件: Utils.py 项目: johnsonc/swarm
def add_to_recent(uri):
    if hasattr(gtk, "recent_manager_get_default"):
        # add the file to the list of recently opened files
        manager = gtk.recent_manager_get_default()
        manager.add_item(uri)
示例#58
0
文件: file.py 项目: jbicha/gjots2
    def read_file(self, prompt, filename, readonly, import_after):
        """

		Top level file reading - with prompting and locking of files.
		Reads items in after "import_after" if set, otherwise to root.

		Returns filename read in or ""

		"""

        if self.gui.debug:
            print inspect.getframeinfo(inspect.currentframe())[2], vars()

        if prompt and not filename:
            self._file_dialog(prompt, gtk.FILE_CHOOSER_ACTION_OPEN)
            if self.fileselectionValue != OK or not self.prompt_filename:
                return ""
        else:
            if not filename:
                filename = os.environ["HOME"] + "/.gjotsfile"
            self.prompt_filename = filename

        dirname, basename = os.path.split(self.prompt_filename)
        if import_after or self.fileselection_readonly:
            readonly = 1

        if not os.access(self.prompt_filename, os.R_OK):
            self.gui.err_msg(_("%s is not readable") % basename)
            return ""

        gtk.recent_manager_get_default().add_full(
            "file://" + self.prompt_filename, {
                "mime_type": "application/gjots",
                "app_name": "gjots2",
                "app_exec": "gjots2"
            })

        # lock the file
        while not readonly:
            reason, pid = self.lock_file(self.prompt_filename)
            if reason == 0:
                # it's locked, all in order...
                break
            if reason == 1:
                msg = _("%s: no permission") % basename
            else:
                msg = _("%s: locked by process number %d") % (basename, pid)
            general = general_dialog(self.gui,
                                     title=_("gjots2: can't lock file."),
                                     prompt=msg,
                                     buttons=TRYAGAIN | CANCEL | READONLY,
                                     secretp=0,
                                     feedback="",
                                     field1_label="",
                                     field1_default="",
                                     field2_label="",
                                     field2_default="")
            if general.get_value() == CANCEL:
                raise LockingError
            if general.get_value() == READONLY:
                self.gui.set_readonly(1, quietly=1)
                readonly = 1

        retval = self._do_load(self.prompt_filename, import_after)
        self.filename_timestamp = 0
        if retval:
            if not import_after:
                self.filename = self.prompt_filename
                self.filename_timestamp = os.stat(self.filename).st_mtime
                if readonly:
                    self.gui.set_readonly(1, quietly=1)
        else:
            self.unlock_file(self.prompt_filename)
            self.filename = ""
            self.gui.set_readonly(0, quietly=1)
        return retval
示例#59
0
    def __init__(self, no_dialog=False):
        self.settings = EventCore()
        self.gui_is_active = False
        # during initialization any dialog (e.g. "Unit change") is not allowed
        # we set the final value later
        self.no_dialog = True
        self._batch_queue = []
        self._undo_states = []
        self.gui = gtk.Builder()
        gtk_build_file = get_ui_file_location(GTKBUILD_FILE)
        if gtk_build_file is None:
            gtk.main_quit()
        self.gui.add_from_file(gtk_build_file)
        if pycam.Utils.get_platform() == pycam.Utils.PLATFORM_WINDOWS:
            gtkrc_file = get_ui_file_location(GTKRC_FILE_WINDOWS)
            if gtkrc_file:
                gtk.rc_add_default_file(gtkrc_file)
                gtk.rc_reparse_all_for_settings(gtk.settings_get_default(),
                                                True)
        self.window = self.gui.get_object("ProjectWindow")
        self.settings.set("main_window", self.window)
        # show stock items on buttons
        # increase the initial width of the window (due to hidden elements)
        self.window.set_default_size(400, -1)
        # initialize the RecentManager (TODO: check for Windows)
        if False and pycam.Utils.get_platform(
        ) == pycam.Utils.PLATFORM_WINDOWS:
            # The pyinstaller binary for Windows fails mysteriously when trying
            # to display the stock item.
            # Error message: Gtk:ERROR:gtkrecentmanager.c:1942:get_icon_fallback: assertion failed: (retval != NULL)
            self.recent_manager = None
        else:
            try:
                self.recent_manager = gtk.recent_manager_get_default()
            except AttributeError:
                # GTK 2.12.1 seems to have problems with "RecentManager" on
                # Windows. Sadly this is the version, that is shipped with the
                # "appunti" GTK packages for Windows (April 2010).
                # see http://www.daa.com.au/pipermail/pygtk/2009-May/017052.html
                self.recent_manager = None
        # file loading
        self.last_dirname = None
        self.last_task_settings_uri = None
        self.last_model_uri = None
        # define callbacks and accelerator keys for the menu actions
        for objname, callback, data, accel_key in (
            ("LoadTaskSettings", self.load_task_settings_file, None,
             "<Control>t"), ("SaveTaskSettings", self.save_task_settings_file,
                             lambda: self.last_task_settings_uri, None),
            ("SaveAsTaskSettings", self.save_task_settings_file, None,
             None), ("OpenModel", self.load_model_file, None,
                     "<Control>o"), ("Quit", self.destroy, None, "<Control>q"),
            ("GeneralSettings", self.toggle_preferences_window, None,
             "<Control>p"), ("UndoButton", self._restore_undo_state, None,
                             "<Control>z"), ("HelpUserManual", self.show_help,
                                             "User_Manual", "F1"),
            ("HelpIntroduction", self.show_help, "Introduction", None),
            ("HelpSupportedFormats", self.show_help, "SupportedFormats",
             None), ("HelpModelTransformations", self.show_help,
                     "ModelTransformations",
                     None), ("HelpToolTypes", self.show_help, "ToolTypes",
                             None), ("HelpProcessSettings", self.show_help,
                                     "ProcessSettings", None),
            ("HelpBoundsSettings", self.show_help, "BoundsSettings",
             None), ("HelpTaskSetup", self.show_help, "TaskSetup", None),
            ("HelpGCodeExport", self.show_help, "GCodeExport",
             None), ("HelpTouchOff", self.show_help, "TouchOff",
                     None), ("HelpSimulation", self.show_help, "Simulation",
                             None), ("Help3DView", self.show_help, "3D_View",
                                     None), ("HelpServerMode", self.show_help,
                                             "ServerMode", None),
            ("HelpCommandLine", self.show_help, "CommandlineExamples",
             None), ("HelpHotkeys", self.show_help, "KeyboardShortcuts",
                     None), ("ProjectWebsite", self.show_help,
                             "http://pycam.sourceforge.net",
                             None), ("DevelopmentBlog", self.show_help,
                                     "http://fab.senselab.org/pycam", None),
            ("Forum", self.show_help,
             "http://sourceforge.net/projects/pycam/forums", None),
            ("BugTracker", self.show_help,
             "http://sourceforge.net/tracker/?group_id=237831&atid=1104176",
             None),
            ("FeatureRequest", self.show_help,
             "http://sourceforge.net/tracker/?group_id=237831&atid=1104179",
             None)):
            item = self.gui.get_object(objname)
            action = "activate"
            if data is None:
                item.connect(action, callback)
            else:
                item.connect(action, callback, data)
            if accel_key:
                key, mod = gtk.accelerator_parse(accel_key)
                accel_path = "<pycam>/%s" % objname
                item.set_accel_path(accel_path)
                gtk.accel_map_change_entry(accel_path, key, mod, True)
        # LinkButton does not work on Windows: https://bugzilla.gnome.org/show_bug.cgi?id=617874
        if pycam.Utils.get_platform() == pycam.Utils.PLATFORM_WINDOWS:

            def open_url(widget, data=None):
                webbrowser.open(widget.get_uri())

            gtk.link_button_set_uri_hook(open_url)
        # no undo is allowed at the beginning
        self.gui.get_object("UndoButton").set_sensitive(False)
        self.settings.register_event("model-change-before",
                                     self._store_undo_state)
        self.settings.register_event(
            "model-change-after",
            lambda: self.settings.emit_event("visual-item-updated"))
        # set the availability of ODE
        self.enable_ode_control = self.gui.get_object("SettingEnableODE")
        self.settings.add_item("enable_ode",
                               self.enable_ode_control.get_active,
                               self.enable_ode_control.set_active)
        self.settings.register_event("parallel-processing-changed",
                                     self.update_ode_settings)
        # configure drag-n-drop for config files and models
        self.settings.set("configure-drag-drop-func",
                          self.configure_drag_and_drop)
        self.settings.get("configure-drag-drop-func")(self.window)
        # other events
        self.window.connect("destroy", self.destroy)
        self.window.connect("delete-event", self.destroy)
        # the settings window
        self.gui.get_object("CloseSettingsWindow").connect(
            "clicked", self.toggle_preferences_window, False)
        self.gui.get_object("ResetPreferencesButton").connect(
            "clicked", self.reset_preferences)
        self.preferences_window = self.gui.get_object("GeneralSettingsWindow")
        self.preferences_window.connect("delete-event",
                                        self.toggle_preferences_window, False)
        self._preferences_window_position = None
        self._preferences_window_visible = False
        # "about" window
        self.about_window = self.gui.get_object("AboutWindow")
        self.about_window.set_version(VERSION)
        self.gui.get_object("About").connect("activate",
                                             self.toggle_about_window, True)
        # we assume, that the last child of the window is the "close" button
        # TODO: fix this ugly hack!
        self.gui.get_object("AboutWindowButtons").get_children()[-1].connect(
            "clicked", self.toggle_about_window, False)
        self.about_window.connect("delete-event", self.toggle_about_window,
                                  False)
        # menu bar
        uimanager = gtk.UIManager()
        self.settings.set("gtk-uimanager", uimanager)
        self._accel_group = uimanager.get_accel_group()

        # send a "delete" event on "CTRL-w" for every window
        def handle_window_close(accel_group, window, *args):
            window.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE))

        self._accel_group.connect_group(ord('w'), gtk.gdk.CONTROL_MASK,
                                        gtk.ACCEL_LOCKED, handle_window_close)
        self.settings.add_item("gtk-accel-group", lambda: self._accel_group)
        for obj in self.gui.get_objects():
            if isinstance(obj, gtk.Window):
                obj.add_accel_group(self._accel_group)
        # preferences tab
        preferences_book = self.gui.get_object("PreferencesNotebook")

        def clear_preferences():
            for child in preferences_book.get_children():
                preferences_book.remove(child)

        def add_preferences_item(item, name):
            preferences_book.append_page(item, gtk.Label(name))

        self.settings.register_ui_section("preferences", add_preferences_item,
                                          clear_preferences)
        for obj_name, label, priority in (("GeneralSettingsPrefTab", "General",
                                           -50), ("ProgramsPrefTab",
                                                  "Programs", 50)):
            obj = self.gui.get_object(obj_name)
            obj.unparent()
            self.settings.register_ui("preferences", label, obj, priority)
        # general preferences
        general_prefs = self.gui.get_object("GeneralPreferencesBox")

        def clear_general_prefs():
            for item in general_prefs.get_children():
                general_prefs.remove(item)

        def add_general_prefs_item(item, name):
            general_prefs.pack_start(item, expand=False, padding=3)

        self.settings.register_ui_section("preferences_general",
                                          add_general_prefs_item,
                                          clear_general_prefs)
        for obj_name, priority in (("SettingEnableODE", 10),
                                   ("TaskSettingsDefaultFileBox", 30)):
            obj = self.gui.get_object(obj_name)
            obj.unparent()
            self.settings.register_ui("preferences_general", None, obj,
                                      priority)
        # set defaults
        self.cutter = None
        # add some dummies - to be implemented later ...
        self.settings.add_item("cutter", lambda: self.cutter)
        main_tab = self.gui.get_object("MainTabs")

        def clear_main_tab():
            while main_tab.get_n_pages() > 0:
                main_tab.remove_page(0)

        def add_main_tab_item(item, name):
            main_tab.append_page(item, gtk.Label(name))

        # TODO: move these to plugins, as well
        self.settings.register_ui_section("main", add_main_tab_item,
                                          clear_main_tab)
        main_window = self.gui.get_object("WindowBox")

        def clear_main_window():
            main_window.foreach(lambda x: main_window.remove(x))

        def add_main_window_item(item, name, **extra_args):
            # some widgets may want to override the defaults
            args = {"expand": False, "fill": False}
            args.update(extra_args)
            main_window.pack_start(item, **args)

        main_tab.unparent()
        self.settings.register_ui_section("main_window", add_main_window_item,
                                          clear_main_window)
        self.settings.register_ui("main_window",
                                  "Tabs",
                                  main_tab,
                                  -20,
                                  args_dict={
                                      "expand": True,
                                      "fill": True
                                  })
        # autoload task settings file on startup
        autoload_enable = self.gui.get_object("AutoLoadTaskFile")
        autoload_box = self.gui.get_object("StartupTaskFileBox")
        autoload_source = self.gui.get_object("StartupTaskFile")

        # TODO: fix the extension filter
        #for one_filter in get_filters_from_list(FILTER_CONFIG):
        #    autoload_source.add_filter(one_filter)
        #    autoload_source.set_filter(one_filter)
        def get_autoload_task_file(autoload_source=autoload_source):
            if autoload_enable.get_active():
                return autoload_source.get_filename()
            else:
                return ""

        def set_autoload_task_file(filename):
            if filename:
                autoload_enable.set_active(True)
                autoload_box.show()
                autoload_source.set_filename(filename)
            else:
                autoload_enable.set_active(False)
                autoload_box.hide()
                autoload_source.unselect_all()

        def autoload_enable_switched(widget, box):
            if not widget.get_active():
                set_autoload_task_file(None)
            else:
                autoload_box.show()

        autoload_enable.connect("toggled", autoload_enable_switched,
                                autoload_box)
        self.settings.add_item("default_task_settings_file",
                               get_autoload_task_file, set_autoload_task_file)

        def disable_gui():
            self.menubar.set_sensitive(False)
            main_tab.set_sensitive(False)

        def enable_gui():
            self.menubar.set_sensitive(True)
            main_tab.set_sensitive(True)

        self.settings.register_event("gui-disable", disable_gui)
        self.settings.register_event("gui-enable", enable_gui)
        # configure locations of external programs
        for auto_control_name, location_control_name, browse_button, key in (
            ("ExternalProgramInkscapeAuto", "ExternalProgramInkscapeControl",
             "ExternalProgramInkscapeBrowse", "inkscape"),
            ("ExternalProgramPstoeditAuto", "ExternalProgramPstoeditControl",
             "ExternalProgramPstoeditBrowse", "pstoedit")):
            self.gui.get_object(auto_control_name).connect(
                "clicked", self._locate_external_program, key)
            location_control = self.gui.get_object(location_control_name)
            self.settings.add_item("external_program_%s" % key,
                                   location_control.get_text,
                                   location_control.set_text)
            self.gui.get_object(browse_button).connect(
                "clicked", self._browse_external_program_location, key)
        # set the icons (in different sizes) for all windows
        gtk.window_set_default_icon_list(*get_icons_pixbuffers())
        # load menu data
        gtk_menu_file = get_ui_file_location(GTKMENU_FILE)
        if gtk_menu_file is None:
            gtk.main_quit()
        uimanager.add_ui_from_file(gtk_menu_file)
        # make the actions defined in the GTKBUILD file available in the menu
        actiongroup = gtk.ActionGroup("menubar")
        for action in [
                action for action in self.gui.get_objects()
                if isinstance(action, gtk.Action)
        ]:
            actiongroup.add_action(action)
        # the "pos" parameter is optional since 2.12 - we can remove it later
        uimanager.insert_action_group(actiongroup, pos=-1)
        # the "recent files" sub-menu
        if not self.recent_manager is None:
            recent_files_menu = gtk.RecentChooserMenu(self.recent_manager)
            recent_files_menu.set_name("RecentFilesMenu")
            recent_menu_filter = gtk.RecentFilter()
            case_converter = pycam.Utils.get_case_insensitive_file_pattern
            for filter_name, patterns in FILTER_MODEL:
                if not isinstance(patterns, (list, set, tuple)):
                    patterns = [patterns]
                # convert it into a mutable list (instead of set/tuple)
                patterns = list(patterns)
                for index in range(len(patterns)):
                    patterns[index] = case_converter(patterns[index])
                for pattern in patterns:
                    recent_menu_filter.add_pattern(pattern)
            recent_files_menu.add_filter(recent_menu_filter)
            recent_files_menu.set_show_numbers(True)
            # non-local files (without "file://") are not supported. yet
            recent_files_menu.set_local_only(False)
            # most recent files to the top
            recent_files_menu.set_sort_type(gtk.RECENT_SORT_MRU)
            # show only ten files
            recent_files_menu.set_limit(10)
            uimanager.get_widget("/MenuBar/FileMenu/OpenRecentModelMenu")\
                    .set_submenu(recent_files_menu)
            recent_files_menu.connect("item-activated",
                                      self.load_recent_model_file)
        else:
            self.gui.get_object("OpenRecentModel").set_visible(False)
        # load the menubar and connect functions to its items
        self.menubar = uimanager.get_widget("/MenuBar")
        # dict of all merge-ids
        menu_merges = {}

        def clear_menu(menu_key):
            for merge in menu_merges.get(menu_key, []):
                uimanager.remove_ui(merge)

        def append_menu_item(menu_key, base_path, widget, name):
            merge_id = uimanager.new_merge_id()
            if widget:
                action_group = widget.props.action_group
                if not action_group in uimanager.get_action_groups():
                    uimanager.insert_action_group(action_group, -1)
                widget_name = widget.get_name()
                item_type = gtk.UI_MANAGER_MENUITEM
            else:
                widget_name = name
                item_type = gtk.UI_MANAGER_SEPARATOR
            uimanager.add_ui(merge_id, base_path, name, widget_name, item_type,
                             False)
            if not menu_key in menu_merges:
                menu_merges[menu_key] = []
            menu_merges[menu_key].append(merge_id)

        def get_menu_funcs(menu_key, base_path):
            append_func = lambda widget, name: \
                    append_menu_item(menu_key, base_path, widget, name)
            clear_func = lambda: clear_menu(menu_key)
            return append_func, clear_func

        for ui_name, base_path in (("view_menu", "/MenuBar/ViewMenu"),
                                   ("file_menu", "/MenuBar/FileMenu"),
                                   ("edit_menu", "/MenuBar/EditMenu"),
                                   ("export_menu",
                                    "/MenuBar/FileMenu/ExportMenu")):
            append_func, clear_func = get_menu_funcs(ui_name, base_path)
            self.settings.register_ui_section(ui_name, append_func, clear_func)
        self.settings.register_ui("file_menu", "Quit",
                                  self.gui.get_object("Quit"), 100)
        self.settings.register_ui("file_menu", "QuitSeparator", None, 95)
        self.settings.register_ui("main_window", "Main", self.menubar, -100)
        # initialize plugins
        self.plugin_manager = pycam.Plugins.PluginManager(core=self.settings)
        self.plugin_manager.import_plugins()
        # some more initialization
        self.reset_preferences()
        # TODO: preferences are not loaded until the new format is stable
        #self.load_preferences()
        #self.load_task_settings()
        self.settings.register_event("notify-file-saved",
                                     self.add_to_recent_file_list)
        self.settings.register_event("notify-file-opened",
                                     self.add_to_recent_file_list)
        # fallback - in case of a failure when opening a model file
        model = pycam.Importers.TestModel.get_test_model()
        self.settings.get("models").add_model(model, "Tiny pyramid")
        # Without this "gkt.main_iteration" loop the task settings file
        # control would not be updated in time.
        while gtk.events_pending():
            gtk.main_iteration()
        autoload_task_filename = self.settings.get(
            "default_task_settings_file")
        if autoload_task_filename:
            self.open_task_settings_file(autoload_task_filename)
        self.update_all_controls()
        self.no_dialog = no_dialog
        if not self.no_dialog:
            # register a logging handler for displaying error messages
            pycam.Utils.log.add_gtk_gui(self.window, logging.ERROR)
            self.window.show()