コード例 #1
0
ファイル: Format.py プロジェクト: ice-pice/pybliographer
    def __init__ (self, parent = None):

        Utils.GladeWindow.__init__ (self, parent)

        # Fill the output format drop-down menu
        menu = gtk.Menu ()
        self._w_menu.set_menu (menu)
        
        outlist = Autoload.available ('output')
        outlist.sort ()
        
        for avail in outlist:
            Utils.popup_add (menu, avail, self._menu_select, avail)

        self._w_menu.set_history (0)
        self.menu_item = outlist [0]

        self._w_style_entry.set_default_path (FormatDialog.style)
        self._w_style.set_text (FormatDialog.style)

        if FormatDialog.output:
            self._w_output_entry.set_default_path (FormatDialog.output)
            self._w_output.set_text (FormatDialog.output)
        
        self._w_format.show ()
        return
コード例 #2
0
def StartViewer(entry, key, stringuri, parent=None, document=None):

    if not is_interactive(): return

    from Pyblio.GnomeUI import Utils

    uri = Fields.URL(stringuri)
    scheme, location, path, parameters, query, fragment = uri.url
    fileuri = uri.get_url()

    if uri.invalid or uri.inexact:
        message = Utils.Callback(
            _("Warning: This URL is marked as Invalid or Approximate: %s\nContinue?"
              ) % fileuri)
        if not message.answer(): return

    if document:
        document.statusbar.push(document.context_id,
                                _(u"Determining Mime Type… "))

    try:
        mimetype = gio.content_type_guess(fileuri)
    except RuntimeError, mesg:
        Utils.error_dialog(
            _("Cannot determine mime type for item %s ") % entry.key.key,
            _("URL in question is: %s\n"
              "You should check the url or path given for errors.\n"
              "Details: %s") % (fileuri, mesg))
        if document:
            document.statusbar.pop(document.context_id)
        return
コード例 #3
0
ファイル: Resource.py プロジェクト: ice-pice/pybliographer
def StartViewer (entry, key, stringuri, parent=None, document=None):

    if not is_interactive (): 	return

    from Pyblio.GnomeUI import Compat, Utils    


    uri = Fields.URL (stringuri)
    scheme, location, path, parameters, query, fragment  = uri.url
    fileuri = uri.get_url ()
    
    if uri.invalid or uri.inexact:
	message = Utils.Callback (
	    _("Warning: This URL is marked as Invalid or Approximate: %s\nContinue?") % fileuri)
	if not message.answer (): return

    if document:
	document.statusbar.set_status (_("Determining Mime Type ... "))

    try:
	mimetype =  Compat.get_mime_type (fileuri)
    except RuntimeError, mesg:
	Utils.error_dialog(_("Cannot determine mime type for item %s ") % entry.key.key, 
			   _("URL in question is: %s\n"
			   "You should check the url or path given for errors.\n"
			   "Details: %s")
			   % (fileuri, mesg))
	if document:
	    document.statusbar.pop ()
	return
コード例 #4
0
 def format_query (self, style, format, output):
     try:
         file = open (output, 'w')
     except IOError, err:
         Utils.error_dialog_s(_(u"can’t open file “%s” for writing:\n%s")
                              % (output, str(err)))
         return
コード例 #5
0
ファイル: Fields.py プロジェクト: ice-pice/pybliographer
 def init_page_1 (self):
     
     self.fields1 = self.xml.get_widget('f_list_1')
     rend = gtk.CellRendererText()
     col = gtk.TreeViewColumn(_('Name'), rend, text = 0)
     self.fields1.append_column(col)
     rend = gtk.CellRendererText()
     col = gtk.TreeViewColumn(_('Type'), rend, text = 1)
     self.fields1.append_column(col)
     
     self.fm = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
                             gobject.TYPE_STRING, gobject.TYPE_PYOBJECT)
     self.sfm = gtk.TreeModelSort(self.fm)
     self.sfm.set_sort_column_id(2, gtk.SORT_ASCENDING)
     self.fields1.set_model(self.sfm)
     self.s1 = self.fields1.get_selection()
     self.s1.connect ('changed', self.list_1_select)
     self.fields = copy.copy (Config.get ('base/fields').data)
     for key, item in  self.fields.iteritems():
         self.fm.append((item.name,
                         _typename [item.type], key, item)) 
     
     self.name1 = self.xml.get_widget('name1')
     self.menu1 = self.xml.get_widget('type1')
     menu = gtk.Menu ()
     self.menu1.set_menu (menu)
     self.menu_items = _typename.keys ()
     for item in self.menu_items:
         Utils.popup_add (menu, _typename [item], self.select_menu, item)
     self.menu1.set_history (0)
     self.current_menu = self.menu_items [0]
     self.check()
コード例 #6
0
    def on_documentation (self, *args):
        import gobject

        timestamp = gtk.gdk.CURRENT_TIME
        try:
            gtk.show_uri (None, "help:pybliographer", timestamp)
            
        except gobject.GError, msg:
            Utils.error_dialog_s(_(u"Can’t display documentation:\n%s") % msg)
コード例 #7
0
ファイル: Editor.py プロジェクト: GNOME/pybliographer
 def update_content (self, entry, text):
     if text [0] == '@' and hasattr (entry, 'set_native'):
         try:
             entry.set_native (self.field, string.lstrip (text [1:]))
             
         except Exceptions.ParserError, msg:
             Utils.error_dialog (_("Error in native string parsing"), str (msg))
             return -1
         
         return 1
コード例 #8
0
ファイル: Editor.py プロジェクト: isabella232/pybliographer
    def update_content(self, entry, text):
        if text[0] == '@' and hasattr(entry, 'set_native'):
            try:
                entry.set_native(self.field, string.lstrip(text[1:]))

            except Exceptions.ParserError, msg:
                Utils.error_dialog(_("Error in native string parsing"),
                                   str(msg))
                return -1

            return 1
コード例 #9
0
    def simple_search(self, w, *arg):
        q = w.get_text().strip()
        if q:
            try:
                test = SearchCls.AnyTester(q.encode('latin-1'))
            except UnicodeEncodeError:
                Utils.error_dialog_s(_("your search text must contain\nlatin-1 characters only"))
                return
        else:
            test = None

        self.limit_view(q, test)
コード例 #10
0
ファイル: Fields.py プロジェクト: isabella232/pybliographer
    def apply(self, *arg):
        if not self.changed: return

        result = self.get()

        Config.set_and_save('base/fields', result)

        if self.parent:
            Utils.warning_dialog_s(
                self.parent,
                _("Some changes require to restart Pybliographic\n"
                  "to be correctly taken into account"))
コード例 #11
0
ファイル: Document.py プロジェクト: ice-pice/pybliographer
    def save_document (self, * arg):
        if self.data.key is None:
            self.save_document_as ()
            return

        file = self.data.key.url [2]
        
	if not self.modification_check ():
	    return
	
        Utils.set_cursor (self.w, 'clock')
        try:
            try:
                self.data.update (self.selection.sort)
            except (OSError, IOError), error:
                Utils.set_cursor (self.w, 'normal')
                self.w.error (_("Unable to save `%s':\n%s") % (str (self.data.key),
                                                               str (error)))
                return
        except:
            etype, value, tb = sys.exc_info ()
            traceback.print_exception (etype, value, tb)
            
            Utils.set_cursor (self.w, 'normal')
            self.w.error (_("An internal error occured during saving\nTry to Save As..."))
            return

        Utils.set_cursor (self.w, 'normal')

        # get the current modification date
        self.modification_date = os.stat (file) [stat.ST_MTIME]
        
        self.update_status (0)
        return
コード例 #12
0
ファイル: Editor.py プロジェクト: isabella232/pybliographer
 def update(self, database, entry):
     '''Updates and returns the new entry.'''
     new = None
     text = self.buff.get_text(self.buff.get_start_iter(),
                               self.buff.get_end_iter())
     try:
         text = text.encode('latin-1')
     except UnicodeError:
         Utils.error_dialog_s(self.w.get_toplevel(),
                              _("Your text contains non Latin-1 symbols"))
         return None
     try:
         new = self.database.create_native(text)
     except Exceptions.ParserError, msg:
         Utils.error_dialog(_("Error in native string parsing"), str(msg))
         return None
コード例 #13
0
ファイル: Document.py プロジェクト: ice-pice/pybliographer
    def merge_database (self, * arg):
        ''' add all the entries of another database to the current one '''
        # get a new file name
        (url, how) = FileSelector.URLFileSelection (_("Merge file"),
                                                    has_auto = True).run ()

        if url is None: return

        try:
            iterator = Open.bibiter (url, how = how)
            
        except (Exceptions.ParserError,
                Exceptions.FormatError,
                Exceptions.FileError,
                Exceptions.DateError), error:
            
            Utils.error_dialog (_("Open error"), error,
                                parent = self.w)
            return
コード例 #14
0
ファイル: Editor.py プロジェクト: GNOME/pybliographer
 def update(self, database, entry):
     '''Updates and returns the new entry.'''
     new  = None
     text = self.buff.get_text(
         self.buff.get_start_iter(),
         self.buff.get_end_iter())
     try:
         text = text.encode('latin-1')
     except UnicodeError:
         Utils.error_dialog_s(
             self.w.get_toplevel(),
             _("Your text contains non Latin-1 symbols"))
         return None
     try:
         new = self.database.create_native(text)
     except Exceptions.ParserError, msg:
         Utils.error_dialog(
             _("Error in native string parsing"), str(msg))
         return None
コード例 #15
0
    def query_database (self, * arg):
        ''' callback corresponding to the "Medline Query..." button '''

        data = MedlineUI (self.w).run ()
        if data is None: return
        
        url = apply (Query.medline_query, data)

        if url is None:
            # no result.
            Utils.error_dialog_s(_("Your query returned no result"))
            return
        elif url is -1:
            # error
            Utils.error_dialog_s(_("An error occurred during Medline Query"))
            return

        self.open_in_new(url, 'medline', no_name=True)
        return
コード例 #16
0
ファイル: Document.py プロジェクト: ice-pice/pybliographer
    def close_document_request (self):
        answer = self.confirm ()
        # remove autosave object with closing
        if answer and self.source_id:
            gobject.source_remove (self.source_id)

        # remove old autosave file
        if answer and self.data.key:
            if self.data.key.url [0] == 'file':
                old_file = self.data.key.url [2]
                old_auto_save = os.path.join (os.path.dirname (old_file),
                                'x-pyblio-save-' + os.path.basename (old_file))

                if os.path.exists (old_auto_save):
                    try:
                        os.remove (old_auto_save)
                    except (OSError, IOError), error:
                        Utils.set_cursor (self.w, 'normal')
                        self.w.error (_("Unable to remove autosave file `%s':\n%s") % (str (old_auto_save), str (error)))
                        return
コード例 #17
0
    def close_document_request (self):
        answer = self.confirm ()
        # remove autosave object with closing
        if answer and self.source_id:
            gobject.source_remove (self.source_id)

        # remove old autosave file
        if answer and self.data.key:
            if self.data.key.url [0] == 'file':
                old_file = self.data.key.url [2]
                old_auto_save = os.path.join (os.path.dirname (old_file),
                                'x-pyblio-save-' + os.path.basename (old_file))

                if os.path.exists (old_auto_save):
                    try:
                        os.remove (old_auto_save)
                    except (OSError, IOError), error:
                        Utils.set_cursor (self.w, 'normal')
                        Utils.error_dialog_s(_(u"Unable to remove autosave file “%s”:\n%s") % (str (old_auto_save), str (error)))
                        return
コード例 #18
0
    def save_document_as (self, * arg):
        # get a new file name
        (url, how) = FileSelector.URLFileSelection(_(u"Save As…"),
                                                   has_auto=False,
                                                   is_save=True,
                                                   parent=self.w).run ()
        
        if url is None: return

        if os.path.exists (url):
            if not Utils.Callback (
		_(u"The file “%s” already exists.\nOverwrite it?")
		% url, parent = self.w).answer ():
                return

        try:
            file = open (url, 'w')
        except IOError, error:
            Utils.error_dialog_s(_("During opening:\n%s") % error [1])
            return
コード例 #19
0
    def merge_database (self, * arg):
        ''' add all the entries of another database to the current one '''
        # get a new file name
        (url, how) = FileSelector.URLFileSelection(_("Merge file"),
                                                   has_auto=True,
                                                   parent=self.w).run ()

        if url is None: return

        try:
            iterator = Open.bibiter (url, how = how)
            
        except (Exceptions.ParserError,
                Exceptions.FormatError,
                Exceptions.FileError,
                Exceptions.DateError), error:
            
            Utils.error_dialog (_("Open error"), error,
                                parent = self.w)
            return
コード例 #20
0
    def lyx_cite (self, * arg):

        import locale

        try:
            enc = locale.getpreferredencoding ()

        except AttributeError:
            enc = locale.getdefaultlocale()[1]

        
        entries = self.index.selection ()
        if not entries: return
        
        if self.lyx is None:
            from Pyblio import LyX

            try:
                self.lyx = LyX.LyXClient ()
            except IOError, msg:
                Utils.error_dialog_s(_(u"Can’t connect to LyX:\n%s") % msg)
                return
コード例 #21
0
    def clear_entries (self, * arg):
        if len (self.data) == 0: return

        if not Utils.Callback (_("Really remove all the entries?"),
                               parent = self.w).answer ():
            return

        keys = self.data.keys ()
        for key in keys:
            del self.data [key]

        self.redisplay_index (1)
        return
コード例 #22
0
    def modification_check (self):
	"""Check for external modification, if necessary,
	ask user for permission to save.
	Returns True if no modifications or overwrite accepted by user."""
 
        if self.modification_date:
            mod_date = os.stat (self.data.key.url [2]) [stat.ST_MTIME]
            
            if mod_date > self.modification_date:
                return  Utils.Callback (
		    _("The database has been externally modified.\nOverwrite changes?"),
		    self.w).answer ()
	    
	return True
コード例 #23
0
    def drag_received (self, entries):
        for entry in entries:
            
            if self.data.would_have_key (entry.key):
                if not Utils.Callback (_(u"An entry called “%s” already exists.\nRename and add it anyway?")
                                       % entry.key.key, parent = self.w).answer ():
                    continue
                
            self.changed = 1
            self.data.add (entry)

        self.redisplay_index ()
        self.index.set_scroll (entries [-1])
        return
コード例 #24
0
    def confirm (self):
        ''' eventually ask for modification cancellation '''
        
        if not self.changed:
            return True

        result = Utils.Callback (_("The database has been modified.\nSave changes?"),
                                 self.w, cancel_add=True).answer()
        if result == 2:
            return False
        elif result and self.modification_check ():
            self.save_document ()
            return True
        else:
            return True
コード例 #25
0
ファイル: Editor.py プロジェクト: isabella232/pybliographer
    def update(self, database, entry):
        modified = False

        key = string.strip(self.key.get_text())
        if key == '':
            self.entry.key = None
            modified = True
        else:
            if not key_re.match(key):
                Utils.error_dialog_s(self.w.get_toplevel(),
                                     _("Invalid key format"))
                return None

            key = Key.Key(database, key)

            if key != self.entry.key:
                if database.has_key(key):
                    Utils.error_dialog_s(
                        self.w.get_toplevel(),
                        _(u"Key “%s” already exists") % str(key.key))
                    return None

                self.entry.key = key
                modified = True

        modified = self.type != self.entry.type or modified

        for item in self.content:
            try:
                result = item.update(self.entry)

            except UnicodeError:
                f = Types.get_field(item.field)

                Utils.error_dialog_s(
                    self.w.get_toplevel(),
                    _(u"The “%s” field contains a non Latin-1 symbol") %
                    f.name)
                return None

            if result == -1: return None

            modified = result or modified

        modified |= self.lt_update()

        if not modified:
            fields = self.entry.keys()
            fields.sort()

            if fields != self.fields: modified = 1

        if modified:
            return self.entry

        return entry
コード例 #26
0
    def autosave (self, url, how):
        ''' autosave file as x-pyblio-save-filename '''

        if self.data.key.url [0] != 'file': return False

        name = self.data.key.url [2]

        # create an autosave file
        save = os.path.join (os.path.dirname (name),
                            'x-pyblio-save-' + os.path.basename (name))

        if self.changed:

            try:
                savefile = open (save, 'w')
            except (IOError, OSError), error:
                Utils.error_dialog_s(_("Error during autosaving:\n%s") % error [1])
                return False

            iterator = Selection.Selection (sort = Sort.Sort([Sort.KeySort()]))
            Open.bibwrite (iterator.iterator (self.data.iterator ()),
                           out = savefile, how = how, database=self.data)

            savefile.close ()
コード例 #27
0
ファイル: Editor.py プロジェクト: GNOME/pybliographer
    def update (self, database, entry):
        modified = False
        
        key = string.strip (self.key.get_text ())
        if key == '':
            self.entry.key = None
            modified = True
        else:
            if not key_re.match (key):
                Utils.error_dialog_s(self.w.get_toplevel(),
                                     _("Invalid key format"))
                return None

            key = Key.Key (database, key)

            if key != self.entry.key:
                if database.has_key (key):
                     Utils.error_dialog_s(
                         self.w.get_toplevel(),
                         _(u"Key “%s” already exists") % str (key.key))
                     return None
                
                self.entry.key = key
                modified = True
                
        modified = self.type != self.entry.type or modified
        
        for item in self.content:
            try:
                result = item.update(self.entry)
                
            except UnicodeError:
                f = Types.get_field(item.field)
                
                Utils.error_dialog_s(
                    self.w.get_toplevel(),
                    _(u"The “%s” field contains a non Latin-1 symbol") %
                    f.name)
                return None
            
            if result == -1: return None
            
            modified = result or modified

        modified |= self.lt_update()

        if not modified:
            fields = self.entry.keys()
            fields.sort()

            if fields != self.fields: modified = 1
        
        if modified:
            return self.entry
        
        return entry
コード例 #28
0
ファイル: Editor.py プロジェクト: isabella232/pybliographer
    def create_field(self, *arg):
        text = string.strip(string.lower(self.newfield.get_text()))
        if not re.match(r"[a-z][\w_-]*$", text):
            if not Utils.Callback(
                    "The fieldname '%s' looks invalid.\nReally proceed?" %
                    text,
                    parent=self.w.get_toplevel()).answer():
                return

        # update the current entry
        current = self.update(self.database, copy.deepcopy(self.entry))
        if current is None:
            return
        self.entry = current
        newtype = Types.get_field(text).type
        self.entry[text] = newtype(_newcontent[newtype])
        self.update_notebook()
コード例 #29
0
    def edit_entry (self, entries):
        if not (type (entries) is types.ListType):
            entries = self.index.selection ()
        
        l = len (entries)

        if l == 0: return

        if l > 5:
            if not Utils.Callback (_("Really edit %d entries?")
                                   % l, parent = self.w).answer ():
                return

        for entry in entries:
            edit = Editor.Editor (self.data, entry, self.w)
            edit.Subscribe ('commit-edition', self.commit_edition)

        return
コード例 #30
0
ファイル: Editor.py プロジェクト: isabella232/pybliographer
    def update(self, entry):
        (day, month, year) = (None, None, None)

        text = string.strip(self.day.get_chars(0, -1)).encode('latin-1')
        if text != '':
            try:
                day = int(text)
            except ValueError:
                Utils.error_dialog_s(self.day.get_toplevel(),
                                     ("Invalid day field in date"))
                return -1

        text = string.strip(self.month.get_chars(0, -1)).encode('latin-1')
        if text != '':
            try:
                month = int(text)
            except ValueError:
                Utils.error_dialog_s(self.day.get_toplevel(),
                                     ("Invalid day field in date"))
                return -1

        text = string.strip(self.year.get_chars(0, -1)).encode('latin-1')
        if text != '':
            try:
                year = int(text)
            except ValueError:
                Utils.error_dialog_s(self.day.get_toplevel(),
                                     ("Invalid day field in date"))
                return -1

        if self.initial == (day, month, year): return 0

        if (day, month, year) == (None, None, None):
            del entry[self.field]
            return 1

        try:
            entry[self.field] = Fields.Date((year, month, day))
        except Exceptions.DateError, error:
            Utils.error_dialog_s(self.day.get_toplevel(), str(error))
            return -1
コード例 #31
0
ファイル: Editor.py プロジェクト: GNOME/pybliographer
    def update (self, entry):
        (day, month, year) = (None, None, None)
        
        text = string.strip (self.day.get_chars (0, -1)).encode ('latin-1')
        if text != '':
            try: day = int (text)
            except ValueError:
                Utils.error_dialog_s(self.day.get_toplevel(),
                                    ("Invalid day field in date"))
                return -1
        
        text = string.strip (self.month.get_chars (0, -1)).encode ('latin-1')
        if text != '':
            try: month = int (text)
            except ValueError:
                Utils.error_dialog_s(self.day.get_toplevel(),
                                    ("Invalid day field in date"))
                return -1
        
        text = string.strip (self.year.get_chars (0, -1)).encode ('latin-1')
        if text != '':
            try: year = int (text)
            except ValueError: 
                Utils.error_dialog_s(self.day.get_toplevel(),
                                    ("Invalid day field in date"))
                return -1
        
        if self.initial == (day, month, year): return 0

        if (day, month, year) == (None, None, None):
            del entry [self.field]
            return 1

        try:
            entry [self.field] = Fields.Date ((year, month, day))
        except Exceptions.DateError, error:
            Utils.error_dialog_s(self.day.get_toplevel(),
                                 str(error))
            return -1
コード例 #32
0
ファイル: Search.py プロジェクト: GNOME/pybliographer
    def __init__(self, parent=None):
        Utils.Builder.__init__(self, parent)

        # the tree model contains a string that explains the query,
        # and a python object representing the actual query.
        
        self._model = gtk.TreeStore(str, object)
        self._w_tree.set_model(self._model)

        # the view does not display the python column, of course.
        col = gtk.TreeViewColumn ('field', gtk.CellRendererText (), text = 0)
        self._w_tree.append_column (col)

        self._w_tree.expand_all ()
        
        # The root of the search tree is the full database
        self._model.append (None, (_("Full database"), None))


        # Monitor the selected items
        self._selection = self._w_tree.get_selection ()
        self._selection.connect ('changed', self.selection)
        
        field_items = [' - any field - '] + \
                      list(Config.get('gnome/searched').data) + \
                      [' - type - ', ' - key - ']

        for f in field_items:
            self._w_field.append_text(f)

        self._w_field.set_active(0)

        # connect a menu to the right button
        self.menu = gtk.Menu ()
        self.delete_button = Utils.popup_add (self.menu, _("Delete"),
                                              self.search_delete)

        # We are set up.
        self.show()
コード例 #33
0
    def delete_entry (self, * arg):
        ''' removes the selected list of items after confirmation '''
        entries = self.index.selection ()
        l = len (entries)
        if l == 0: return

        offset = self.index.get_item_position (entries [-1])

        if l > 1:
            question = _("Remove all the %d entries?") % len (entries)
        else:
            question = _(u"Remove entry “%s”?") % entries [0].key.key
            
        if not Utils.Callback (question,
                               parent = self.w).answer ():
            return

        for entry in entries:
            del self.data [entry.key]
            
        self.redisplay_index (1)
        self.index.select_item (offset)
        return
コード例 #34
0
    def open_document (self, url, how = None, no_name = False):

        Utils.set_cursor (self.w, 'clock')

        orig_url = Fields.URL (url)
        url = orig_url.get_url ()

        restore = False

        if orig_url.url [0] == 'file':

            name = orig_url.url [2]
            auto_save = os.path.join (os.path.dirname (name),
                            'x-pyblio-save-' + os.path.basename (name))

            if os.path.exists (auto_save):
                mod_date = os.stat (name) [stat.ST_MTIME]
                mod_date_auto = os.stat (auto_save) [stat.ST_MTIME]
                if mod_date < mod_date_auto:
                    restore = Utils.Callback (_("An autosave file was found which is newer than the original file.\nDo you want to restore it?"), self.w).answer ()

                    if restore: url = auto_save


        try:
            data = Open.bibopen (url, how = how)
            
        except (Exceptions.ParserError,
                Exceptions.FormatError,
                Exceptions.FileError,
                Exceptions.DateError), error:
            
            Utils.set_cursor (self.w, 'normal')
            Utils.error_dialog (_("Open error"), error,
                                parent = self.w)
            return
コード例 #35
0
ファイル: Document.py プロジェクト: ice-pice/pybliographer
    def open_document (self, url, how = None, no_name = False):

        Utils.set_cursor (self.w, 'clock')

        orig_url = Fields.URL (url)
        url = orig_url.get_url ()

        restore = False

        if orig_url.url [0] == 'file':

            name = orig_url.url [2]
            auto_save = os.path.join (os.path.dirname (name),
                            'x-pyblio-save-' + os.path.basename (name))

            if os.path.exists (auto_save):
                mod_date = os.stat (name) [stat.ST_MTIME]
                mod_date_auto = os.stat (auto_save) [stat.ST_MTIME]
                if mod_date < mod_date_auto:
                    restore = Utils.Callback (_("An autosave file was found which is newer than the original file.\nDo you want to restore it?"), self.w).answer ()

                    if restore: url = auto_save


        try:
            data = Open.bibopen (url, how = how)
            
        except (Exceptions.ParserError,
                Exceptions.FormatError,
                Exceptions.FileError,
                Exceptions.DateError), error:
            
            Utils.set_cursor (self.w, 'normal')
            Utils.error_dialog (_("Open error"), error,
                                parent = self.w)
            return
コード例 #36
0
ファイル: Index.py プロジェクト: GNOME/pybliographer
    def display (self, iterator):

        # clear the access table
        self.access = []

        Utils.set_cursor (self.w, 'clock')

        self.model.clear ()

        for entry in iterator:
            row = []

            i = 0

            for f in self.fields:
                row.append (i)
                i = i + 1

                if f == '-key-':
                    row.append ((str (entry.key.key)).decode ('latin-1'))

                elif f == '-type-':
                    row.append (str (entry.type.name)) ## ascii

                elif f == '-author/editor-':
                    row.append (userformat.author_editor_format
                                (entry).decode ('latin-1'))

                elif f == '-author/title-':
                    row.append (userformat.author_title_format
                                (entry).decode ('latin-1'))

                elif entry.has_key (f):

                    if Types.get_field (f).type == Fields.AuthorGroup:
                        text = join (map (lambda a: str (a.last), entry [f]), ', ')
                    elif Types.get_field (f).type == Fields.Date:
                        text = str (entry [f].year)
                    else:
                        text = str (entry [f])

                    row.append (text.decode ('latin-1'))
                else:
                    row.append ('')

            if True:
                row.append (i)
                if Resource.is_viewable (entry):
                    row.append (self.gvpixbuf)
                else:
                    row.append (None)

            iter = self.model.append  ()

            apply (self.model.set, [iter] + row)

            self.access.append (entry)

            entry = iterator.next ()

        Utils.set_cursor (self.w, 'normal')
        return
コード例 #37
0
class Document (Connector.Publisher):
    
    def __init__ (self, database):

        self.uim = gtk.UIManager ()

        self.recents = None
        self.viewables = None
	
        self.actiongroup = gtk.ActionGroup ('Main')
        
        self.actiongroup.add_actions ([
            # id     stock            label         accel   tooltip   callback
            ('File', None,                _('_File')),
            ('EditMenu', None,            _('_Edit')),
	    ('ViewMenu', None,            _('_View')),
            ('CiteMenu', None,            _('_Cite')),
            ('Settings', None,            _('_Settings')),
            ('HelpMenu', None,            _('_Help')),
            ('Recent', None, _('Recent documents')),
            
            ('New',  gtk.STOCK_NEW,   None,         None,   None,     self.new_document),
            ('Open', gtk.STOCK_OPEN,  None,         None,   _('Open a file'), self.ui_open_document),
            ('Open_URL', None, _(u'Open _Location…'), '<control>l',   None, self.ui_open_location),
            ('Save', gtk.STOCK_SAVE,  None,         None,   _('Save the current file'), self.save_document),
            ('Save_As', gtk.STOCK_SAVE_AS,  None,         None,   None,     self.save_document_as),
            ('Close', gtk.STOCK_CLOSE,  None,         None,   None,     self.close_document),
            ('Quit', gtk.STOCK_QUIT,  None,         None,   None,     self.exit_application),

            ('Merge',   None, _(u'Merge With…'),    '<control>g',  None, self.merge_database),
            ('Medline', None, _(u'Medline Query…'), '<control>m',  None, self.query_database),



            ('Cut', gtk.STOCK_CUT,  None,         None,   None,     self.cut_entry),
            ('Copy', gtk.STOCK_COPY,  None,         None,   None,     self.copy_entry),
            ('Paste', gtk.STOCK_PASTE,  None,         None,   None,     self.paste_entry),
            ('Clear', gtk.STOCK_CLEAR,  None,         None,   None,     self.clear_entries),
            ('Add', gtk.STOCK_ADD,  None,   '<shift><control>n',  _('Add a new entry'), self.add_entry),
            ('Edit', gtk.STOCK_EDIT,  None, '<shift><control>o',   None,     self.edit_entry),
            ('Delete', gtk.STOCK_DELETE,  None,         None,   None,     self.delete_entry),
            ('Find', gtk.STOCK_FIND,  None,         None,   None,     self.find_entries),
            
            ('Sort', None, _(u'S_ort…'), None,  None, self.sort_entries),
            ('Cite', gtk.STOCK_JUMP_TO,   _(u'Cite…'), None,  _('Cite key(s)'), self.lyx_cite),
            ('Format', gtk.STOCK_EXECUTE, _(u'Format…'), None,  None, self.format_entries),

            ('Fields', None, _(u'Fields…'), None,  None, self.set_fields),
            ('Preferences', gtk.STOCK_PREFERENCES,  None,         None,   None,     self.set_preferences),
            ('Forget', None, _('Forget all changes'),     None,   None,     self.forget_changes_cb),
            
            ('Contents', gtk.STOCK_HELP, None,   None,   None,     self.on_documentation),
            ('About', gtk.STOCK_ABOUT, None,   None,   None,     self.about),
	    ('ViewResource', None, _('_Resource'), None, None, self.view_entry),
            ])


        prev = self.actiongroup.get_action ('Recent')
        
        prev.set_property ('is-important', True)
        prev.set_property ('hide-if-empty', False)

        view_action = self.actiongroup.get_action ('ViewResource')
	view_action.set_property ('hide-if-empty', False)
        self.uim.insert_action_group (self.actiongroup, 0)
        self.uim.add_ui_from_string (uim_content)

        self.uim.ensure_update ()

        gp = os.path.join(Utils.glade_root, 'pyblio.ui')
        icon_file = os.path.join (version.pixmapsdir, 'pybliographic.png')

        self.xml = gtk.Builder()
        self.xml.set_translation_domain('pybliographer')
        self.xml.add_from_file(gp)
        self.xml.connect_signals(self)

        self.w = self.xml.get_object('main')
        self.w.set_icon_from_file(icon_file)
        self.paned = self.xml.get_object('main_pane')

        box = self.xml.get_object('table')
        menubar = (self.uim.get_widget ('/Menubar'))
        toolbar = (self.uim.get_widget ('/Toolbar'))
        box.attach(menubar, 0, 1, 0, 1, yoptions=0)
        box.attach(toolbar, 0, 1, 1, 2, yoptions=0)

        self.w.add_accel_group (self.uim.get_accel_group ())

        self.w.add_events (gtk.gdk.KEY_PRESS_MASK)
        
        self.w_save_btn = self.xml.get_object('_w_save_btn')
        self.w_save_mnu = self.xml.get_object('_w_save_mnu')

        self.quick_search = gtk.Entry()
        self.quick_search.set_icon_from_stock(gtk.ENTRY_ICON_PRIMARY, gtk.STOCK_FIND)
        self.quick_search.connect('activate', self.simple_search)

        tool_item = gtk.ToolItem()
        tool_item.add(self.quick_search)
        toolbar.insert(tool_item, -1)

        tool_item.show_all()

        # The Index list
        self.index = Index.Index (popup = self.uim.get_widget ('/Popup'))
        self.paned.add1 (self.index.w)
        
        self.index.Subscribe ('new-entry',      self.add_entry)
        self.index.Subscribe ('edit-entry',     self.edit_entry)
##      self.index.Subscribe ('view-entry',     self.view_entry)
        self.index.Subscribe ('delete-entry',   self.delete_entry)
        self.index.Subscribe ('select-entry',   self.update_display)
        self.index.Subscribe ('select-entries', self.freeze_display)
        self.index.Subscribe ('drag-received',  self.drag_received)
        self.index.Subscribe ('drag-moved',     self.drag_moved)
        self.index.Subscribe ('click-on-field', self.sort_by_field)

        self.paned.show_all ()

        # The text area
        self.display = Entry.Entry ()
        self.paned.add2 (self.display.w)

        # Status bar
        self.statusbar = self.xml.get_object('statusbar')
        
        # set window size
        ui_width  = Utils.config.get_int ('/apps/pybliographic/ui/width') or -1
        ui_height = Utils.config.get_int ('/apps/pybliographic/ui/height') or -1

        if ui_width != -1 and ui_height != -1:
            self.w.set_default_size (ui_width, ui_height)

        # set paned size
        paned_height = Utils.config.get_int ('/apps/pybliographic/ui/paned') or -1
        self.paned.set_position (paned_height)
        
        self.w.show_all ()
        
        # application variables
        self.data      = database
        self.selection = Selection.Selection ()
        self.search_dg = None
        self.sort_dg   = None
        self.lyx       = None
        self.changed   = 0
        self.directory = None

        self.incremental_start  = None
        self.incremental_search = ''
        
        self.modification_date = None

        # for autosave
        self.source_id = None

        # set the default sort method
        default = Utils.config.get_string ('/apps/pybliographic/sort/default')
        if default is not None: default = pickle.loads (default)

        self.sort_view (default)

        self._title_set ()
        self._set_edit_actions (False)
        return

    def _title_set (self):
        
        if self.data.key is None:
            self.w.set_title (_('Unnamed bibliographic database'))
            return

        name = os.path.basename (self.data.key.url [2])
        
        self.w.set_title (name)
        return
        

    def set_preferences (self, * arg):
        from Pyblio.GnomeUI import Config
        Config.run(self.w)
        return

    def set_fields (self, * arg):
        from Pyblio.GnomeUI import Fields
        Fields.run (self.w)
        return
    
    def forget_changes_cb (self, * arg):
        Config.forget_changes()
        return
    

    def update_history (self, history):
        ''' fill the " Previous Documents " menu with the specified list of documents '''

        if self.recents:
            for mid in self.recents_mid:
                self.uim.remove_ui (mid)
                
            self.uim.remove_action_group (self.recents)

        self.recents_mid = []
        self.recents = gtk.ActionGroup ('Recent')

        self.uim.insert_action_group (self.recents, 1)

        for item in history:
            # Display name in the menu
            quoted   = string.replace (item [0], '_', '__')
        
            mid = self.uim.new_merge_id ()

            self.recents_mid.append (mid)
            
            action = gtk.Action (str (mid), quoted, None, None)
            self.recents.add_action (action)

            action.connect ('activate', self._history_open_cb, item)
        
            self.uim.add_ui (mid, '/Menubar/File/Recent', str (mid),
                             str (mid), gtk.UI_MANAGER_MENUITEM, False)

        return

    def _history_open_cb (self, id, w):

        file, type = w
        
        if not self.confirm (): return

        self.open_document (file, type)
        return
    
    
    def redisplay_index (self, changed = -1):
        ''' redisplays the index. If changed is specified, set the
        self.changed status to the given value '''
        
        if changed != -1:
            self.changed = changed

        self.index.display (self.selection.iterator (self.data.iterator ()))
        
        self.update_status ()
        return


    def format_query (self, style, format, output):
        try:
            file = open (output, 'w')
        except IOError, err:
            Utils.error_dialog_s(_(u"can’t open file “%s” for writing:\n%s")
                                 % (output, str(err)))
            return
        
        entries = map (lambda x: x.key, self.index.selection ())
        
        if not entries:
            iter    = self.selection.iterator (self.data.iterator ())
            entries = []
            
            e = iter.first ()
            while e:
                entries.append (e.key)
                e = iter.next ()

        url = Fields.URL (style)

        try:
            Pyblio.Style.Utils.generate (url, format, self.data, entries, file)
        except RuntimeError, err:
            print err
            Utils.error_dialog_s(_(u"Error while parsing “%s”:\n%s") % (style, err))
コード例 #38
0
ファイル: Resource.py プロジェクト: ice-pice/pybliographer
	
    elif mimetype in ['text/html', 'text/plain']:
	filename = fileuri

    else:
	filename, headers = urllib.urlretrieve (fileuri)
	
    if mimetype == 'application/x-gzip':
	try:
	    tempname = os.tmpnam ()
	    os.system ("gzip -d < %s >%s" %(filename, tempname))
	    filename = tempname
	    mimetype =  Compat.get_mime_type (filename)
	except RuntimeError, mesg:
	    Utils.error_dialog (_("IOError for item %s: cannot uncompress resource.")
				% entry.key.key, _("URL: %s\nDetails: %s")
				% (filename, mesg))
	    if document:
		document.statusbar.pop ()
	    return

    viewers = [
	item [1] for item in
	Config.get (config_viewers).data if item [0] == mimetype] or [
	item [1] for item in
	Config.get (config_viewers).data if item [0].endswith ('/*') and
	item [0] [:-2] == mimetype1]

    if viewers:
	cmd = viewers [0]
	command = userexit.resource_viewer_setup (
コード例 #39
0
    def save_document (self, * arg):
        if self.data.key is None:
            self.save_document_as ()
            return

        file = self.data.key.url [2]
        
	if not self.modification_check ():
	    return
	
        Utils.set_cursor (self.w, 'clock')
        try:
            try:
                self.data.update (Sort.Sort([Sort.KeySort()]))
            except (OSError, IOError), error:
                Utils.set_cursor (self.w, 'normal')
                Utils.error_dialog_s(_(u"Unable to save “%s”:\n%s") % (str (self.data.key),
                                                               str (error)))
                return
        except:
            etype, value, tb = sys.exc_info ()
            traceback.print_exception (etype, value, tb)
            
            Utils.set_cursor (self.w, 'normal')
            Utils.error_dialog_s(_(u"An internal error occurred during saving\nTry to Save As…"))
            return

        Utils.set_cursor (self.w, 'normal')

        # get the current modification date
        self.modification_date = os.stat (file) [stat.ST_MTIME]
        
        self.update_status (0)
        return
コード例 #40
0
    elif mimetype in ['text/html', 'text/plain']:
        filename = fileuri

    else:
        filename, headers = urllib.urlretrieve(fileuri)

    if mimetype == 'application/x-gzip':
        try:
            tempname = os.tmpnam()
            os.system("gzip -d < %s >%s" % (filename, tempname))
            filename = tempname
            mimetype = gio.content_type_guess(filename)
        except RuntimeError, mesg:
            Utils.error_dialog(
                _("IOError for item %s: cannot uncompress resource.") %
                entry.key.key,
                _("URL: %s\nDetails: %s") % (filename, mesg))
            if document:
                document.statusbar.pop(document.context_id)
            return

    viewers = [
        item[1]
        for item in Config.get(config_viewers).data if item[0] == mimetype
    ] or [
        item[1] for item in Config.get(config_viewers).data
        if item[0].endswith('/*') and item[0][:-2] == mimetype1
    ]

    if viewers:
        cmd = viewers[0]
コード例 #41
0
            errors = errors + msg.errors
        
        while entry:
            self.data.add (entry)
            while 1:
                try:
                    entry = iterator.next ()
                    break
                except Exceptions.ParserError, msg:
                    errors = errors + list (msg.errors)
                    continue

        self.redisplay_index (1)

        if errors:
            Utils.error_dialog (_("Merge status"), string.join (errors, '\n'),
                                parent = self.w)
        return

        
    def ui_open_document (self, * arg):
        ''' callback corresponding to "Open" '''
        
        if not self.confirm (): return

        # get a new file name
        (url, how) = FileSelector.URLFileSelection(_("Open file"),
                                                   parent=self.w).run ()

        if url is None: return
        self.open_document (url, how)
        return
コード例 #42
0
ファイル: Document.py プロジェクト: ice-pice/pybliographer
            errors = errors + msg.errors
        
        while entry:
            self.data.add (entry)
            while 1:
                try:
                    entry = iterator.next ()
                    break
                except Exceptions.ParserError, msg:
                    errors = errors + list (msg.errors)
                    continue

        self.redisplay_index (1)

        if errors:
            Utils.error_dialog (_("Merge status"), string.join (errors, '\n'),
                                parent = self.w)
        return

        
    def ui_open_document (self, * arg):
        ''' callback corresponding to "Open" '''
        
        if not self.confirm (): return

        # get a new file name
        (url, how) = FileSelector.URLFileSelection (_("Open file")).run ()

        if url is None: return
        self.open_document (url, how)
        return
コード例 #43
0
ファイル: Index.py プロジェクト: isabella232/pybliographer
    def display(self, iterator):

        # clear the access table
        self.access = []

        Utils.set_cursor(self.w, 'clock')

        self.model.clear()

        for entry in iterator:
            row = []

            i = 0

            for f in self.fields:
                row.append(i)
                i = i + 1

                if f == '-key-':
                    row.append((str(entry.key.key)).decode('latin-1'))

                elif f == '-type-':
                    row.append(str(entry.type.name))  ## ascii

                elif f == '-author/editor-':
                    row.append(
                        userformat.author_editor_format(entry).decode(
                            'latin-1'))

                elif f == '-author/title-':
                    row.append(
                        userformat.author_title_format(entry).decode(
                            'latin-1'))

                elif entry.has_key(f):

                    if Types.get_field(f).type == Fields.AuthorGroup:
                        text = join(map(lambda a: str(a.last), entry[f]), ', ')
                    elif Types.get_field(f).type == Fields.Date:
                        text = str(entry[f].year)
                    else:
                        text = str(entry[f])

                    row.append(text.decode('latin-1'))
                else:
                    row.append('')

            if True:
                row.append(i)
                if Resource.is_viewable(entry):
                    row.append(self.gvpixbuf)
                else:
                    row.append(None)

            iter = self.model.append()

            apply(self.model.set, [iter] + row)

            self.access.append(entry)

            entry = iterator.next()

        Utils.set_cursor(self.w, 'normal')
        return
コード例 #44
0
 def changed (self):
     if not self.warning:
         self.warning = True
         Utils.warning_dialog_s(self.parent, _("Some changes require to restart Pybliographic\n"
                                "to be correctly taken into account"))