def __init__(self, URL=None, action='enter/edit', parent=None): gtk.Button.__init__(self) self.parent_widget = parent self.url = URL or Fields.URL() self.newuri = None assert isinstance(URL, Fields.URL) self.action = action assert action in Resource.CHOOSER_ACTIONS, "Invalid file chooser action" self.connect("clicked", self.cb_clicked) self.box = gtk.HBox(False, 4) self.add(self.box) self.image = gtk.Image() pixbuf = self.render_icon(gtk.STOCK_NEW, gtk.ICON_SIZE_MENU) self.image.set_from_pixbuf(pixbuf) self.box.pack_start(self.image, False, False, 0) self.label = gtk.Label(self.url.get_url() or _('Enter/Select an URL')) self.label.set_ellipsize(pango.ELLIPSIZE_START) self.label.set_alignment(0.0, 0.5) self.box.pack_start(self.label) self.sep = gtk.VSeparator() self.box.pack_start(self.sep, False, False, 0) self.icon = gtk.image_new_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_MENU) self.box.pack_start(self.icon, False, False, 0) self.title = "Enter/Edit URL" self.dialog = None self.current_name = None self.show_all()
def format(database, style, output, file=sys.stdout, id='Bibliography'): output = Autoload.get_by_name("output", output).data url = None style = os.path.splitext(style)[0] if os.path.exists(style + '.xml'): url = Fields.URL(style + '.xml') else: from Pyblio import version full = os.path.join(version.pybdir, 'Styles', style) full = full + '.xml' if os.path.exists(full): url = Fields.URL(full) Utils.generate(url, output, database, database.keys(), file) return
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
def run(self): response = gtk.FileChooserDialog.run(self) uri = self.get_uri() invalid = self.invalid_w.get_active() inexact = self.inexact_w.get_active() date = self.date_w.get_text() note = self.note_w.get_text() #print 'DIALOG RUN:', uri, invalid, inexact, date, note return response, Fields.URL(uri, invalid=invalid, inexact=inexact, date=date, note=note)
def bibopen (entity, how = None): ''' Generic function to open a bibliographic database ''' def simple_try (url, how): # url is Fields.URL instance, only to be passed to opener base = None if how == None: listedmethods = Autoload.available ("format") for method in listedmethods: opener = get_by_name (method, 'open') if opener: base = opener (url, 1) if base is not None: return base return None opener = get_by_name (how, 'open') if opener: base = opener (url, 0) else: raise Exceptions.FormatError (_(u"method “%s” provides no opener") % how) return base # Consider the reference as an URL: url is an Fields.URL instance url = Fields.URL (entity) if url.url [0] == 'file' and not os.path.exists (url.url [2]): raise Exceptions.FileError (_(u"File “%s” does not exist") % url.get_url ()) # eventually load a new module if how is None: handler = Autoload.get_by_regexp ("format", url.get_url ()) if handler: how = handler.name base = simple_try (url, how) if base is None: raise Exceptions.FormatError (_(u"don’t know how to open “%s”") % entity) return base
def bibnew (name, type = None): opener = get_by_name (type, 'new') if opener is None: if os.path.exists (name): raise IOError, "file `%s' exists" % name file = open (name, 'w') file.close () return bibopen (name, type) # Consider the reference as an URL url = list (urlparse.urlparse (name)) if url [0] == '': # Consider we handle a local file url [0] = 'file' url [2] = os.path.expanduser (url [2]) return opener (Fields.URL(url))
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
def next(self): current = None data = '' table = {} # Skip whitespace while 1: line = self.file.readline() if line == '': return table line = string.rstrip(line) if line != '': break while 1: head = header.match(line) if head: if current: if table.has_key(current): table[current].append(data) else: table[current] = [data] current = string.strip(head.group(1)) data = head.group(2) else: cont = contin.match(line) if cont: data = data + ' ' + cont.group(1) line = self.file.readline() if line == '': break line = string.rstrip(line) if line == '': break # don't forget the last item if current: if table.has_key(current): table[current].append(data) else: table[current] = [data] # create the entry with the actual fields norm = {} type = Types.get_entry('article') if table.has_key('PMID'): norm['url'] = Fields.URL(medurl + table['PMID'][0]) norm['medline-pmid'] = Fields.Text(table['PMID'][0]) del table['PMID'] if table.has_key('UI'): norm[one_to_one['UI']] = Fields.Text(table['UI'][0]) del table['UI'] if table.has_key('AU'): group = Fields.AuthorGroup() for au in table['AU']: # analyze the author by ourself. first, last, lineage = [], [], [] for part in string.split(au, ' '): if part.isupper(): # in upper-case, this is a first name if len(last) > 0: first.append(part) else: # if there is no last name, there can't be a first name last.append(part) else: if len(first) > 0: # there was a first name, this must be a lineage lineage.append(part) else: last.append(part) if len(first) > 1: print "medline: long first name found. skipping." first = first[0:1] if len(first) > 0: first = string.join(first[0], '. ') + '.' else: first = None if len(last) > 0: last = string.join(last, ' ') else: last = None if len(lineage) > 0: lineage = string.join(lineage, ' ') else: lineage = None group.append(Fields.Author((None, first, last, lineage))) norm[one_to_one['AU']] = group del table['AU'] if table.has_key('DP'): fields = string.split(table['DP'][0], ' ') norm[one_to_one['DP']] = Fields.Date(fields[0]) del table['DP'] # The simple fields... for f in table.keys(): f_mapped = one_to_one.get(f, 'medline-%s' % (f.lower())) text_type = Types.get_field(f_mapped).type norm[f_mapped] = text_type(string.join(table[f], " ; ")) return Base.Entry(None, type, norm)
# get option values for opt, value in optlist: if opt == '-o' or opt == '--output': outfile = value continue if opt == '-s' or opt == '--style': style = value continue # get the specified style url = None style = os.path.splitext(style)[0] if os.path.exists(style + '.xml'): url = Fields.URL(style + '.xml') else: from Pyblio import version full = os.path.join(version.pybdir, 'Styles', style) full = full + '.xml' if os.path.exists(full): url = Fields.URL(full) if not url: error(_(u"can’t find style “%s”") % style) spstyle = os.path.split(style)[1] # adjust parameters to the chosen style if spstyle == 'abbrvau': sep = '; ' format = 'textau'
def update_content(self, entry, text): entry[self.field] = Fields.URL(text) return
import sys from Pyblio import Fields, Autoload from Pyblio.Open import bibopen from Pyblio.Style import Utils db = bibopen(sys.argv[2]) keys = db.keys() keys.sort() url = Fields.URL(sys.argv[3]) Utils.generate(url, Autoload.get_by_name('output', sys.argv[4]).data, db, keys, sys.stdout)
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))