Ejemplo n.º 1
0
    def quit(self):
        if self.changes_made and self.prompt(
                text=_('There are unsaved changes.\n\nSave before exiting?'),
                title=_('Save changes?')):
            self.langdb.save()

        self.config.save()
        gtk.main_quit()
Ejemplo n.º 2
0
 def handler_save(self):
     """Save the contents of the current open database."""
     try:
         self.config.current_database.save()
     except Exception, exc:
         self.gui.show_error(text=str(exc), title=_('Error saving database!'))
         print _( 'Error saving database: "%s"') % (exc)
         return
Ejemplo n.º 3
0
    def handler_emaildb(self):
        db = self.config.current_database

        try:
            db.save()
        except Exception, exc:
            self.gui.show_error(_('Unable to save database before e-mailing!'))
            print _('Unable to save database before e-mailing: "%s"') % (exc)
            return
Ejemplo n.º 4
0
    def check_pos_text(self, text=None):
        """If text was entered into cmb_pos, handle that text."""
        if text is None:
            text = self.cmb_pos.child.get_text()

        if not text:
            self.set_status(_('No part-of-speech specified.'))
            self.select_pos(None)
            self.cmb_pos.grab_focus()
            return

        shortcut, name = ('|' in text) and (
            [substr.strip() for substr in text.split('|')]) or ('_', text)
        # Search for POS on value and shortcut
        pos = \
            self.langdb.find(section='parts_of_speech', name=name, shortcut=shortcut) + \
            self.langdb.find(section='parts_of_speech', name=text, shortcut=text)

        if pos:
            # NOTE: If more than one part of speech matches, we use the first one
            self.select_pos(pos[0])

            if pos[0].id != self.current_root.pos_id:
                self.set_sensitive(btn_ok=False,
                                   btn_add_root=True,
                                   btn_mod_root=True)
                self.set_visible(btn_ok=False,
                                 btn_add_root=True,
                                 btn_mod_root=True)
            else:
                self.set_sensitive(btn_ok=True,
                                   btn_add_root=False,
                                   btn_mod_root=False)
                self.set_visible(btn_ok=True,
                                 btn_add_root=False,
                                 btn_mod_root=False)

            if self._new_root:
                # If we are working with a new root, there is not sense in
                # trying to modify it.
                self.set_visible(btn_mod_root=False)
        else:
            # If we get here, we have a new part of speech
            self.set_status(_('Part of speech not found.'))
            self.select_pos(None)
            return

        # Select the focus to the first button in the list that is both visible and active
        for btn in (self.btn_ok, self.btn_add_root, self.btn_mod_root):
            if btn.get_property('visible') and btn.get_property('sensitive'):
                btn.grab_focus()
Ejemplo n.º 5
0
    def check_root_text(self, text=None):
        """If text was entered into C{ent_root}, handle that text."""
        if text is None:
            text = self.ent_root.get_text()

        if not text:
            self.set_status(_('A root must be specified.'))
            self.select_root(None)
            return

        # First check if the text in entry is that of an existing root:
        roots = self.langdb.find(section='roots', value=text)

        if roots and len(roots) > 0:
            # NOTE: If more than one root matches, we use the first one
            self.select_root(roots[0])
        else:
            # If we get here, we have a new root on our hands
            self.select_root(None)  # Deselect root
            self.ent_root.set_text(text)
            self.current_root = Root(value=unicode(text),
                                     user_id=self.config.user['id'],
                                     date=datetime.datetime.now())
            self._new_root = True
            self.select_pos(None)  # Deselect POS

            self.set_visible(btn_ok=False, btn_add_root=True)
            self.set_sensitive(cmb_pos=True, btn_add_root=False)
            self.cmb_pos.child.grab_focus()
Ejemplo n.º 6
0
    def create_source_from_file(self, filename):
        """Create a model.Source for the given filename."""
        fname      = os.path.split(filename)[1]
        dlg_source = self.gui.dlg_source

        dlg_source.clear()

        if dlg_source.run(fname) == RESPONSE_CANCEL:
            return None

        while not dlg_source.has_valid_input():
            self.gui.show_error(
                _('Please fill in a name for the source'),
                title='Incomplete information'
            )
            if dlg_source.run(fname) == RESPONSE_CANCEL:
                return None

        name = dlg_source.name
        desc = dlg_source.description
        import_user_id = self.config.user['id']

        src = Source(
            name           = name,
            filename       = fname,
            desc           = desc,
            import_user_id = import_user_id
        )
        return src
Ejemplo n.º 7
0
    def check_root_text(self, text=None):
        """If text was entered into C{ent_root}, handle that text."""
        if text is None:
            text = self.ent_root.get_text()

        if not text:
            self.set_status(_('A root must be specified.'))
            self.select_root(None)
            return

        # First check if the text in entry is that of an existing root:
        roots = self.langdb.find(section='roots', value=text)

        if roots and len(roots) > 0:
            # NOTE: If more than one root matches, we use the first one
            self.select_root(roots[0])
        else:
            # If we get here, we have a new root on our hands
            self.select_root(None) # Deselect root
            self.ent_root.set_text(text)
            self.current_root = Root(
                value   = unicode(text),
                user_id = self.config.user['id'],
                date    = datetime.datetime.now()
            )
            self._new_root = True
            self.select_pos(None)  # Deselect POS

            self.set_visible(btn_ok=False, btn_add_root=True)
            self.set_sensitive(cmb_pos=True, btn_add_root=False)
            self.cmb_pos.child.grab_focus()
Ejemplo n.º 8
0
    def prompt(self, text, title=_('Prompt')):
        self.dlg_prompt.set_markup(escape(text))
        self.dlg_prompt.set_title(title)
        res = self.dlg_prompt.run()
        self.dlg_prompt.hide()

        return res == gtk.RESPONSE_YES
Ejemplo n.º 9
0
    def handler_saveas(self):
        """Display a "Save as" dialog and try to save the language database to
            the selected file."""
        filename = self.gui.get_save_filename()
        if filename is None:
            return

        if not filename.endswith('.xldb'):
            filename = filename + '.xldb'

        if os.path.exists(filename) and not self.gui.prompt(_( 'File "%s" already exists.\n\nOverwrite?' % (filename) )):
            return

        try:
            self.config.current_database.save(filename)
        except Exception, exc:
            self.gui.show_error(text=str(exc), title=_('Error saving database to file %s') % (filename))
            print _('Error saving database to %s: %s') % (filename, exc)
Ejemplo n.º 10
0
    def check_pos_text(self, text=None):
        """If text was entered into cmb_pos, handle that text."""
        if text is None:
            text = self.cmb_pos.child.get_text()

        if not text:
            self.set_status(_('No part-of-speech specified.'))
            self.select_pos(None)
            self.cmb_pos.grab_focus()
            return

        shortcut, name = ('|' in text) and ( [substr.strip() for substr in text.split('|')] ) or ('_', text)
        # Search for POS on value and shortcut
        pos = \
            self.langdb.find(section='parts_of_speech', name=name, shortcut=shortcut) + \
            self.langdb.find(section='parts_of_speech', name=text, shortcut=text)

        if pos:
            # NOTE: If more than one part of speech matches, we use the first one
            self.select_pos(pos[0])

            if pos[0].id != self.current_root.pos_id:
                self.set_sensitive(btn_ok=False, btn_add_root=True, btn_mod_root=True)
                self.set_visible(btn_ok=False, btn_add_root=True, btn_mod_root=True)
            else:
                self.set_sensitive(btn_ok=True, btn_add_root=False, btn_mod_root=False)
                self.set_visible(btn_ok=True, btn_add_root=False, btn_mod_root=False)

            if self._new_root:
                # If we are working with a new root, there is not sense in
                # trying to modify it.
                self.set_visible(btn_mod_root=False)
        else:
            # If we get here, we have a new part of speech
            self.set_status(_('Part of speech not found.'))
            self.select_pos(None)
            return

        # Select the focus to the first button in the list that is both visible and active
        for btn in (self.btn_ok, self.btn_add_root, self.btn_mod_root):
            if btn.get_property('visible') and btn.get_property('sensitive'):
                btn.grab_focus()
Ejemplo n.º 11
0
    def handler_open(self):
        """Display an "Open" dialog and try to open the file as a language database."""
        if self.gui.changes_made and self.gui.prompt(
                    text=_('Save language database changes?'),
                    title=_('The language database you are\ncurrently working with has changed.\n\nSave changes?')
                ):
            self.config.current_database.save()

        filename = self.gui.get_open_filename()
        if filename is None:
            return

        if not os.path.exists(filename):
            self.gui.show_error(_('File does not exist: "%s"') % (filename))
            return

        # Get and save new user information
        self.gui.load_langdb(filename)

        # Ask the main GUI object to reload the database everywhere...
        self.gui.reload_database()
Ejemplo n.º 12
0
    def get_save_filename(self, title=_('Save...')):
        """Display an "Save" dialog and return the selected file.
            @rtype  str
            @return The filename selected in the "Save" dialog. None if the selection was cancelled."""
        self.save_chooser.set_title(title)
        res = self.save_chooser.run()
        self.save_chooser.hide()

        if res != gtk.RESPONSE_OK:
            return None

        return self.save_chooser.get_filename()
Ejemplo n.º 13
0
    def get_open_filename(self, title=_('Select language database to open')):
        """Display an "Open" dialog and return the selected file.
            @rtype  str
            @return The filename selected in the "Open" dialog. None if the selection was cancelled."""
        self.open_chooser.set_title(title)
        res = self.open_chooser.run()
        self.open_chooser.hide()

        if res != gtk.RESPONSE_OK:
            return None

        return self.open_chooser.get_filename()
Ejemplo n.º 14
0
    def handler_import(self):
        """Import words from a text file."""
        db = self.config.current_database
        user_id = self.config.user['id']
        filename = self.gui.get_open_filename(_('Open word list...'))

        if filename is None:
            return

        src = self.create_source_from_file(filename)
        if src is None:
            return

        db.import_source(src, filename=filename)
        self.gui.reload_database()
Ejemplo n.º 15
0
    def on_surface_form_selected(self, sf):
        """A proxied event handler for when a surface form is selected in the
            word list.

            See the documentation of spelt.gui.WordList.word_selected_handlers for
            the use of this method."""
        if sf is None:
            self.lbl_word.set_markup('')
            self.select_root(None)
            self.set_sensitive(btn_reject=False, btn_ignore=False)
            self.set_visible(btn_ok=False)
            return

        self.current_sf = sf
        self.lbl_status.hide()
        self.lbl_word.set_markup('<b>%s</b>' % sf.value)

        if self.langdb is None:
            return

        # Set GUI to its initial state
        self.set_sensitive(
            btn_reject=True,
            btn_ignore=True,
            btn_ok=True,
            btn_add_root=True,
            btn_mod_root=True,
            cmb_pos=True
        )
        self.set_visible(btn_ok=True, btn_add_root=False, btn_mod_root=False)

        if not sf.root_id:
            # sf does not have an associated root, so there's nothing to select
            # in the combo boxes.
            self.select_root(None)
        else:
            roots_found = self.langdb.find(id=sf.root_id, section='roots')
            # The roots_found list can have a maximum of 1 element, because we
            # search the database on ID's. ID's are guaranteed to be unique by the
            # models (via it's inheritence of IDModel).
            if roots_found:
                self.select_root(roots_found[0])
            else:
                raise exceptions.RootError(_( 'No root object found with ID %d' % (sf.root_id) ))

        self.ent_root.grab_focus()
Ejemplo n.º 16
0
    def on_surface_form_selected(self, sf):
        """A proxied event handler for when a surface form is selected in the
            word list.

            See the documentation of spelt.gui.WordList.word_selected_handlers for
            the use of this method."""
        if sf is None:
            self.lbl_word.set_markup('')
            self.select_root(None)
            self.set_sensitive(btn_reject=False, btn_ignore=False)
            self.set_visible(btn_ok=False)
            return

        self.current_sf = sf
        self.lbl_status.hide()
        self.lbl_word.set_markup('<b>%s</b>' % sf.value)

        if self.langdb is None:
            return

        # Set GUI to its initial state
        self.set_sensitive(btn_reject=True,
                           btn_ignore=True,
                           btn_ok=True,
                           btn_add_root=True,
                           btn_mod_root=True,
                           cmb_pos=True)
        self.set_visible(btn_ok=True, btn_add_root=False, btn_mod_root=False)

        if not sf.root_id:
            # sf does not have an associated root, so there's nothing to select
            # in the combo boxes.
            self.select_root(None)
        else:
            roots_found = self.langdb.find(id=sf.root_id, section='roots')
            # The roots_found list can have a maximum of 1 element, because we
            # search the database on ID's. ID's are guaranteed to be unique by the
            # models (via it's inheritence of IDModel).
            if roots_found:
                self.select_root(roots_found[0])
            else:
                raise exceptions.RootError(
                    _('No root object found with ID %d' % (sf.root_id)))

        self.ent_root.grab_focus()
Ejemplo n.º 17
0
    def __init_widgets(self):
        """Get and initialize widgets from the Glade object."""
        # TODO: Add support for filters
        self.store = gtk.ListStore(gobject.TYPE_PYOBJECT)

        self.treeview = self.glade_xml.get_widget('tvw_words')
        self.treeview.set_model(self.store)

        # Add columns
        cell = gtk.CellRendererText()
        col  = gtk.TreeViewColumn(_('Surface Form'))
        col.pack_start(cell)
        col.set_cell_data_func(cell, self.__render_word)
        self.treeview.append_column(col)

        # Connect signals
        self.treeview.connect('row-activated', self.__on_row_activated, self.store)

        # Load data if available
        self.refresh()
Ejemplo n.º 18
0
    def __init_widgets(self):
        """Get and initialize widgets from the Glade object."""
        # TODO: Add support for filters
        self.store = gtk.ListStore(gobject.TYPE_PYOBJECT)

        self.treeview = self.glade_xml.get_widget('tvw_words')
        self.treeview.set_model(self.store)

        # Add columns
        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_('Surface Form'))
        col.pack_start(cell)
        col.set_cell_data_func(cell, self.__render_word)
        self.treeview.append_column(col)

        # Connect signals
        self.treeview.connect('row-activated', self.__on_row_activated,
                              self.store)

        # Load data if available
        self.refresh()
Ejemplo n.º 19
0
 def show_error(self, text, title=_('Error!')):
     self.dlg_error.set_markup(escape(text))
     self.dlg_error.set_title(title)
     self.dlg_error.run()
     self.dlg_error.hide()
Ejemplo n.º 20
0
    def handler_quit(self):
        """Quit the application after confirmation."""
        self.gui.quit()

    def handler_emaildb(self):
        db = self.config.current_database

        try:
            db.save()
        except Exception, exc:
            self.gui.show_error(_('Unable to save database before e-mailing!'))
            print _('Unable to save database before e-mailing: "%s"') % (exc)
            return

        subj = _('Language database: ') + str(db).decode('utf-8')
        openmailto.mailto('', subject=subj, attach=db.filename)

    def handler_import(self):
        """Import words from a text file."""
        db = self.config.current_database
        user_id = self.config.user['id']
        filename = self.gui.get_open_filename(_('Open word list...'))

        if filename is None:
            return

        src = self.create_source_from_file(filename)
        if src is None:
            return
Ejemplo n.º 21
0
    def __create_dialogs(self):
        self.open_chooser = gtk.FileChooserDialog(
            title=_('Select language database to open'),
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))

        self.save_chooser = gtk.FileChooserDialog(
            title=_('Save as...'),
            action=gtk.FILE_CHOOSER_ACTION_SAVE,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))

        all_filter = gtk.FileFilter()
        all_filter.set_name(_('All files'))
        all_filter.add_pattern('*')

        langdb_filter = gtk.FileFilter()
        langdb_filter.set_name(_('Language Database'))
        langdb_filter.add_mime_type('text/xml')
        langdb_filter.add_pattern('*.' + LanguageDB.FILE_EXTENSION)

        self.open_chooser.add_filter(all_filter)
        self.open_chooser.add_filter(langdb_filter)
        self.save_chooser.add_filter(langdb_filter)
        self.save_chooser.add_filter(all_filter)

        # Message dialog
        self.dlg_error = gtk.MessageDialog(parent=self.main_window,
                                           flags=gtk.DIALOG_MODAL,
                                           type=gtk.MESSAGE_ERROR,
                                           buttons=gtk.BUTTONS_OK,
                                           message_format='')

        self.dlg_info = gtk.MessageDialog(parent=self.main_window,
                                          flags=gtk.DIALOG_MODAL,
                                          type=gtk.MESSAGE_INFO,
                                          buttons=gtk.BUTTONS_OK,
                                          message_format='')

        self.dlg_prompt = gtk.MessageDialog(parent=self.main_window,
                                            flags=gtk.DIALOG_MODAL,
                                            type=gtk.MESSAGE_QUESTION,
                                            buttons=gtk.BUTTONS_YES_NO,
                                            message_format='')

        # Source dialog wrapper
        self.dlg_source = DlgSource(self.glade, self.icon_filename)
        # LanguageDB loading dialog
        self.dlg_dbload = DlgDBLoad(self.glade, self)

        # About dialog
        def on_about_url(dialog, uri, data):
            if data == "mail":
                openmailto.mailto(uri)
            elif data == "url":
                openmailto.open(uri)

        self.dlg_about = gtk.AboutDialog()
        gtk.about_dialog_set_url_hook(on_about_url, "url")
        gtk.about_dialog_set_email_hook(on_about_url, "mail")
        self.dlg_about.set_name("Spelt")
        self.dlg_about.set_version(__version__)
        self.dlg_about.set_copyright(
            _("© Copyright 2007-2008 Zuza Software Foundation"))
        self.dlg_about.set_comments(
            _("A tool to categorize words from a language database according to its root."
              ))
        self.dlg_about.set_license(LICENSE)
        self.dlg_about.set_website(
            "http://translate.sourceforge.net/wiki/spelt/index")
        self.dlg_about.set_website_label(_("Spelt website"))
        self.dlg_about.set_authors(
            ["Walter Leibbrandt <*****@*****.**>"])
        self.dlg_about.set_translator_credits(_("translator-credits"))
        self.dlg_about.set_icon(self.main_window.get_icon())
        # XXX entries that we may want to add (commented out):
        #self.dlg_about.set_logo()
        self.dlg_about.set_documenters([
            "Friedel Wolff <*****@*****.**>",
            "Wynand Winterbach <*****@*****.**>",
            "Walter Leibbrandt <*****@*****.**>"
        ])
        #self.dlg_about.set_artists()

        # Set icon on all dialogs
        for dlg in (self.open_chooser, self.save_chooser, self.dlg_error,
                    self.dlg_info, self.dlg_prompt, self.dlg_about):
            dlg.set_icon_from_file(self.icon_filename)
Ejemplo n.º 22
0
 def show_info(self, text, title=_('Information')):
     self.dlg_info.set_markup(escape(text))
     self.dlg_info.set_title(title)
     self.dlg_info.run()
     self.dlg_info.hide()
Ejemplo n.º 23
0
 def check_work_done(self, sf):
     if sf is None:
         self.show_info(_('All work done!'))