Пример #1
0
    def create_dynamic_view(self, at):
        """Create a caption dynamic view for the given annotation-type.
        """
        p=self.controller.package
        ident='v_caption_%s' % at.id
        if p.get(ident) is not None:
            dialog.message_dialog(_("A caption dynamic view for %s already seems to exist.") % self.get_title(at))
            return True
        v=p.create_view(id=ident,
                        mimetype='application/x-advene-ruleset')
        v.title=_("Caption %s annotations") % self.controller.get_title(at)

        # Build the ruleset
        r=RuleSet()
        catalog=self.controller.event_handler.catalog

        ra=catalog.get_action("AnnotationCaption")
        action=Action(registeredaction=ra, catalog=catalog)
        action.add_parameter('message', 'annotation/content/data')

        rule=Rule(name=_("Caption the annotation"),
                  event=Event("AnnotationBegin"),
                  condition=Condition(lhs='annotation/type/id',
                                      operator='equals',
                                      rhs='string:%s' % at.id),
                  action=action)
        r.add_rule(rule)

        v.content.data=r.xml_repr()

        p.views.append(v)
        self.controller.notify('ViewCreate', view=v)
        self.controller.activate_stbv(v)
        return True
Пример #2
0
    def validate(self, button=None):
        # Get the query
        l=self.eq.invalid_items()
        if l:
            self.log(_("Invalid query.\nThe following fields have an invalid value:\n%s")
                     % ", ".join(l))
            return True
        self.eq.update_value()
        query=self.eq.model
        # Store the query itself in the _interactive query
        self.querycontainer.content.data = query.xml_repr()

        label=_("Expert search")
        c=self.controller.build_context(here=self.here)
        try:
            res=c.evaluateValue("here/query/_interactive")
        except AdveneTalesException as e:
            # Display a dialog with the value
            dialog.message_dialog(_("TALES error in interactive expression:\n%s" % str(e)),
                                  icon=Gtk.MessageType.ERROR)
            return True

        # Close the search window
        self.close()

        # Set the result attribute for the InteractiveResult view
        self.result=res

        # And display the result in the same viewbook or window
        self.controller.gui.open_adhoc_view('interactiveresult', destination=self._destination,
                                            label=label, query=query, result=res)
        return True
Пример #3
0
        def validate(b):
            m = self.mergerview.store
            suffix = self.suffix_entry.get_text().strip()
            if not suffix:
                dialog.message_dialog(_("The suffix cannot be empty."), icon=Gtk.MessageType.ERROR)
                return True

            annotation_count = 0
            type_count = 0
            # Let's use differ methods to copy elements
            differ = Differ(source=self.sourcepackage, destination=self.destpackage, controller=self.controller)
            batch_id=object()
            for l in m:
                if l[self.mergerview.COLUMN_APPLY]:
                    source_at = l[self.mergerview.COLUMN_ELEMENT]
                    logger.debug("Copying %s (%d annotations)", source_at.title, len(source_at.annotations))
                    type_count += 1
                    dest_at = differ.copy_annotation_type(source_at, generate_id=True)
                    dest_at.title = "%s %s" % (dest_at.title, suffix)
                    self.controller.notify('AnnotationTypeCreate', annotationtype=dest_at, immediate=True, batch=batch_id)
                    for a in source_at.annotations:
                        annotation_count += 1
                        # Since we copied the annotation type before, copy_annotation should use the translated name
                        new_a = differ.copy_annotation(a, generate_id=True)
                        self.controller.notify('AnnotationCreate', annotation=new_a, immediate=True, batch=batch_id)
            logger.info(_("Copied %d annotations from %d types"), annotation_count, type_count)
            self.close()
            return True
Пример #4
0
    def convert_to_annotations(self, *p):
        """Convert bookmarks to annotations with a fixed duration.
        """
        at=self.controller.gui.ask_for_annotation_type(text=_("Select the annotation type to generate"), create=True)

        if at is None:
            return True

        d=dialog.entry_dialog(title=_("Choose a duration"),
                              text=_("Enter the standard duration (in ms) of created annotations."),
                              default="2000")
        if d is None:
            return True

        try:
            d=int(d)
        except ValueError:
            # Use a default value
            d=2000
        ti=HistoryImporter(package=self.controller.package,
                           controller=self.controller,
                           defaulttype=at,
                           elements=self.bookmarks,
                           duration=d)
        ti.process_file('history')
        self.controller.package._modified=True
        self.log(_('Converted from bookmarks'))
        self.log(ti.statistics_formatted())
        # Feedback
        dialog.message_dialog(
            _("Conversion completed.\n%s annotations generated.") % ti.statistics['annotation'])
        return True
Пример #5
0
 def update_modified(self, l):
     b = self.textview.get_buffer()
     impossible = []
     batch_id = object()
     for a in l:
         m = b.get_mark("b_%s" % a.id)
         if not m:
             break
         beginiter = b.get_iter_at_mark(m)
         m = b.get_mark("e_%s" % a.id)
         if not m:
             break
         enditer = b.get_iter_at_mark(m)
         new_content = helper.title2content(
             b.get_text(beginiter, enditer,
                        False).strip(ZERO_WIDTH_NOBREAK_SPACE), a.content,
             a.type.getMetaData(config.data.namespace, 'representation')
             if self.options['default-representation'] else
             self.options['representation'])
         if new_content is None:
             impossible.append(a)
         elif a.content.data != new_content:
             self.controller.notify('EditSessionStart',
                                    element=a,
                                    immediate=True)
             a.content.data = new_content
             self.controller.notify("AnnotationEditEnd",
                                    annotation=a,
                                    batch=batch_id)
             self.controller.notify('EditSessionEnd', element=a)
     if impossible:
         dialog.message_dialog(label=_(
             "Cannot convert the following annotations,\nthe representation pattern is too complex.\n%s"
         ) % ",".join([a.id for a in impossible]))
     return True
Пример #6
0
 def processing_ended(self, msg=None):
     if _thread.get_ident() != self.main_thread_id:
         self.do_gui_operation(self.processing_ended, msg=msg)
         return True
     self.progress_callback(1.0)
     if self.controller.cached_duration == 0:
         # Importing into an videoless package. Use the maximum timestamp as duration.
         try:
             self.controller.cached_duration = max(
                 a.fragment.end
                 for a in self.controller.package.annotations)
         except ValueError:
             # Max on empty annotation sequence will raise a ValueError
             self.controller.cached_duration = 0
         self.controller.notify('DurationUpdate',
                                duration=self.controller.cached_duration)
     self.controller.notify("PackageActivate",
                            package=self.controller.package)
     self.close()
     if msg is None:
         msg = _('Completed conversion: %(message)s\n%(statistics)s') % {
             'message': self.importer.output_message,
             'statistics': self.importer.statistics_formatted()
         }
     dialog.message_dialog(msg, modal=False)
     self.log(msg)
Пример #7
0
    def convert_to_annotations(self, *p):
        """Convert bookmarks to annotations with a fixed duration.
        """
        at=self.controller.gui.ask_for_annotation_type(text=_("Select the annotation type to generate"), create=True)

        if at is None:
            return True

        d=dialog.entry_dialog(title=_("Choose a duration"),
                              text=_("Enter the standard duration (in ms) of created annotations."),
                              default="2000")
        if d is None:
            return True

        try:
            d=int(d)
        except ValueError:
            # Use a default value
            d=2000
        ti=HistoryImporter(package=self.controller.package,
                           controller=self.controller,
                           defaulttype=at,
                           elements=self.bookmarks,
                           duration=d)
        ti.process_file('history')
        self.controller.package._modified=True
        self.log(_('Converted from bookmarks'))
        self.log(ti.statistics_formatted())
        # Feedback
        dialog.message_dialog(
            _("Conversion completed.\n%s annotations generated.") % ti.statistics['annotation'])
        return True
Пример #8
0
 def update_modified(self, l):
     b=self.textview.get_buffer()
     impossible=[]
     batch_id=object()
     for a in l:
         m = b.get_mark("b_%s" % a.id)
         if not m:
             break
         beginiter = b.get_iter_at_mark(m)
         m = b.get_mark("e_%s" % a.id)
         if not m:
             break
         enditer  = b.get_iter_at_mark(m)
         new_content = helper.title2content(b.get_text(beginiter, enditer, False).strip(ZERO_WIDTH_NOBREAK_SPACE),
                                            a.content,
                                            a.type.getMetaData(config.data.namespace, 'representation') if self.options['default-representation'] else self.options['representation'])
         if new_content is None:
             impossible.append(a)
         elif a.content.data != new_content:
             self.controller.notify('EditSessionStart', element=a, immediate=True)
             a.content.data = new_content
             self.controller.notify("AnnotationEditEnd", annotation=a, batch=batch_id)
             self.controller.notify('EditSessionEnd', element=a)
     if impossible:
         dialog.message_dialog(label=_("Cannot convert the following annotations,\nthe representation pattern is too complex.\n%s") % ",".join( [ a.id for a in impossible ] ))
     return True
Пример #9
0
    def validate(self, button=None):
        # Get the query
        l=self.eq.invalid_items()
        if l:
            self.log(_("Invalid query.\nThe following fields have an invalid value:\n%s")
                     % ", ".join(l))
            return True
        self.eq.update_value()
        query=self.eq.model
        # Store the query itself in the _interactive query
        self.querycontainer.content.data = query.xml_repr()

        label=_("Expert search")
        c=self.controller.build_context(here=self.here)
        try:
            res=c.evaluateValue("here/query/_interactive")
        except AdveneTalesException as e:
            # Display a dialog with the value
            dialog.message_dialog(_("TALES error in interactive expression:\n%s" % str(e)),
                icon=Gtk.MessageType.ERROR)
            return True

        # Close the search window
        self.close()

        # Set the result attribute for the InteractiveResult view
        self.result=res

        # And display the result in the same viewbook or window
        self.controller.gui.open_adhoc_view('interactiveresult', destination=self._destination,
                                            label=label, query=query, result=res)
        return True
Пример #10
0
 def csv_export(self, name=None):
     if name is None:
         name=dialog.get_filename(title=_("Export data to file..."),
                                           default_file="advene_data.csv",
                                           action=Gtk.FileChooserAction.SAVE,
                                           button=Gtk.STOCK_SAVE)
     if name is None:
         return True
     try:
         f=open(name, 'w', encoding='utf-8')
     except IOError as e:
         dialog.message_dialog(label=_("Error while exporting data to %(filename)s: %(error)s"
                                       % {
                     'filename': name,
                     'error': str(e),
                     }),
                               icon=Gtk.MessageType.ERROR)
     w=csv.writer(f)
     tv=self.widget.treeview
     store, paths=tv.get_selection().get_selected_rows()
     source=[ store.get_iter(p) for p in paths ]
     if not source:
         source=tv.get_model()
     w.writerow( (_("Element title"), _("Element type"), _("Element id")) )
     for r in source:
         w.writerow( (str(r[COLUMN_CONTENT]).encode('utf-8'), str(r[COLUMN_TYPE]).encode('utf-8'), r[COLUMN_ID]) )
     f.close()
     self.log(_("Data exported to %s") % name)
Пример #11
0
 def csv_export(self, name=None):
     if name is None:
         name = dialog.get_filename(title=_("Export data to file..."),
                                    default_file="advene_data.csv",
                                    action=Gtk.FileChooserAction.SAVE,
                                    button=Gtk.STOCK_SAVE)
     if name is None:
         return True
     try:
         f = open(name, 'w', encoding='utf-8')
     except IOError as e:
         dialog.message_dialog(label=_(
             "Error while exporting data to %(filename)s: %(error)s" % {
                 'filename': name,
                 'error': str(e),
             }),
                               icon=Gtk.MessageType.ERROR)
     w = csv.writer(f)
     tv = self.widget.treeview
     store, paths = tv.get_selection().get_selected_rows()
     source = [store.get_iter(p) for p in paths]
     if not source:
         source = tv.get_model()
     w.writerow((_("Element title"), _("Element type"), _("Element id")))
     for r in source:
         w.writerow((str(r[COLUMN_CONTENT]).encode('utf-8'),
                     str(r[COLUMN_TYPE]).encode('utf-8'), r[COLUMN_ID]))
     f.close()
     self.log(_("Data exported to %s") % name)
Пример #12
0
        def move_annotation(i, an, typ, position=None):
            if an.relations and an.type != typ:
                dialog.message_dialog(
                    _("Cannot delete the annotation : it has relations."),
                    icon=gtk.MESSAGE_WARNING)
                return True

            self.transmuted_annotation = self.controller.transmute_annotation(
                an, typ, delete=True)
            return self.transmuted_annotation
Пример #13
0
 def check_validity(self):
     iv = self.edit.invalid_items()
     if iv:
         dialog.message_dialog(_(
             "The following items seem to be\ninvalid TALES expressions:\n\n%s"
         ) % "\n".join(iv),
                               icon=Gtk.MessageType.ERROR)
         return False
     else:
         return True
Пример #14
0
 def check_validity(self):
     iv=self.edit.invalid_items()
     if iv:
         dialog.message_dialog(
             _("The following items seem to be\ninvalid TALES expressions:\n\n%s") %
             "\n".join(iv),
             icon=gtk.MESSAGE_ERROR)
         return False
     else:
         return True
Пример #15
0
 def validate(self, *p):
     l=self.check_modified()
     if l:
         if self.options['representation'] and not parsed_representation.match(self.options['representation']):
             dialog.message_dialog(label=_("Cannot validate the update.\nThe representation pattern is too complex."))
             return True
         self.ignore_updates = True
         self.update_modified(l)
         self.ignore_updates = False
     return True
Пример #16
0
        def move_annotation(i, an, typ, position=None):
            if an.relations and an.type != typ:
                dialog.message_dialog(_("Cannot delete the annotation : it has relations."),
                                      icon=gtk.MESSAGE_WARNING)
                return True

            self.transmuted_annotation=self.controller.transmute_annotation(an,
                                                                            typ,
                                                                            delete=True)
            return self.transmuted_annotation
Пример #17
0
    def new_tag(self, *p):
        """Enter a new tag.
        """
        d = gtk.Dialog(title=_("New tag name"),
                       parent=None,
                       flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                       buttons=(
                           gtk.STOCK_CANCEL,
                           gtk.RESPONSE_CANCEL,
                           gtk.STOCK_OK,
                           gtk.RESPONSE_OK,
                       ))
        l = gtk.Label(_("Enter a new tag name and select its color."))
        d.vbox.pack_start(l, expand=False)

        hb = gtk.HBox()
        hb.pack_start(gtk.Label(_("Name")), expand=False)
        tagname = gtk.Entry()
        hb.pack_start(tagname, expand=False)
        d.vbox.pack_start(hb, expand=False)

        hb = gtk.HBox()
        hb.pack_start(gtk.Label(_("Color")), expand=False)
        colorbutton = gtk.ColorButton()
        colorbutton.set_color(gtk.gdk.color_parse('red'))
        hb.pack_start(colorbutton, expand=False)
        d.vbox.pack_start(hb, expand=False)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)
        d.show_all()
        dialog.center_on_mouse(d)

        res = d.run()
        ret = None
        if res == gtk.RESPONSE_OK:
            try:
                tag = unicode(tagname.get_text())
            except ValueError:
                tag = None
            color = colorbutton.get_color()
        else:
            tag = None
        d.destroy()

        if tag and not tag in self.tags:
            if not re.match('^[\w\d_]+$', tag):
                dialog.message_dialog(_("The tag contains invalid characters"),
                                      icon=gtk.MESSAGE_ERROR)
                return True
            self.tags.append(tag)
            self.controller.package._tag_colors[tag] = "#%04x%04x%04x" % (
                color.red, color.green, color.blue)
            self.controller.notify('TagUpdate', tag=tag)
            self.refresh()
        return True
Пример #18
0
    def new_tag(self, *p):
        """Enter a new tag.
        """
        d = Gtk.Dialog(title=_("New tag name"),
                       parent=self.controller.gui.gui.win,
                       flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
                       buttons=(
                           Gtk.STOCK_CANCEL,
                           Gtk.ResponseType.CANCEL,
                           Gtk.STOCK_OK,
                           Gtk.ResponseType.OK,
                       ))
        l = Gtk.Label(label=_("Enter a new tag name and select its color."))
        d.vbox.pack_start(l, False, True, 0)

        hb = Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Name")), False, False, 0)
        tagname = Gtk.Entry()
        hb.pack_start(tagname, False, True, 0)
        d.vbox.pack_start(hb, False, True, 0)

        hb = Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Color")), False, False, 0)
        colorbutton = Gtk.ColorButton()
        colorbutton.set_color(Gdk.color_parse('red'))
        hb.pack_start(colorbutton, False, True, 0)
        d.vbox.pack_start(hb, False, True, 0)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)
        d.show_all()
        dialog.center_on_mouse(d)

        res = d.run()
        if res == Gtk.ResponseType.OK:
            try:
                tag = tagname.get_text()
            except ValueError:
                tag = None
            color = colorbutton.get_color()
        else:
            tag = None
        d.destroy()

        if tag and not tag in self.tags:
            if not re.match(r'^[\w\d_]+$', tag):
                dialog.message_dialog(_("The tag contains invalid characters"),
                                      icon=Gtk.MessageType.ERROR)
                return True
            self.tags.append(tag)
            self.controller.package._tag_colors[tag] = "#%04x%04x%04x" % (
                color.red, color.green, color.blue)
            self.controller.notify('TagUpdate', tag=tag)
            self.refresh()
        return True
Пример #19
0
 def save_transcription(self, filename=None):
     if os.path.splitext(filename)[1] == '':
         # No extension was given. Add '.txt'
         filename=filename+'.txt'
     try:
         f=open(filename, "w")
     except IOError, e:
         dialog.message_dialog(
             _("Cannot save the file: %s") % unicode(e),
             icon=gtk.MESSAGE_ERROR)
         return True
Пример #20
0
 def display_stats(self, m, at):
     """Display statistics about the annotation type.
     """
     msg=_("<b>Statistics about %s</b>\n\n") % self.controller.get_title(at)
     msg += "%d annotations\n" % len(at.annotations)
     msg += "Min duration : %s\n" % helper.format_time(min( a.duration for a in at.annotations))
     msg += "Max duration : %s\n" % helper.format_time(max( a.duration for a in at.annotations))
     msg += "Mean duration : %s\n" % helper.format_time(sum( a.duration for a in at.annotations) / len(at.annotations))
     msg += "Total duration : %s\n" % helper.format_time(sum( a.duration for a in at.annotations))
     dialog.message_dialog(msg)
     return True
Пример #21
0
 def update_value(self):
     if not self.editable:
         return False
     iv = self.invalid_items()
     if iv:
         dialog.message_dialog(_(
             "The following items seem to be\ninvalid TALES expressions:\n\n%s"
         ) % "\n".join(iv),
                               icon=Gtk.MessageType.ERROR)
         return False
     for e in self.editlist:
         e.update_value()
     return True
Пример #22
0
 def update_value(self):
     if not self.editable:
         return False
     iv=self.invalid_items()
     if iv:
         dialog.message_dialog(
             _("The following items seem to be\ninvalid TALES expressions:\n\n%s") %
             "\n".join(iv),
             icon=gtk.MESSAGE_ERROR)
         return False
     for e in self.editlist:
         e.update_value()
     return True
Пример #23
0
    def new_tag(self, *p):
        """Enter a new tag.
        """
        d = gtk.Dialog(title=_("New tag name"),
                       parent=None,
                       flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                       buttons=( gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                 gtk.STOCK_OK, gtk.RESPONSE_OK,
                                 ))
        l=gtk.Label(_("Enter a new tag name and select its color."))
        d.vbox.pack_start(l, expand=False)

        hb=gtk.HBox()
        hb.pack_start(gtk.Label(_("Name")), expand=False)
        tagname=gtk.Entry()
        hb.pack_start(tagname, expand=False)
        d.vbox.pack_start(hb, expand=False)

        hb=gtk.HBox()
        hb.pack_start(gtk.Label(_("Color")), expand=False)
        colorbutton=gtk.ColorButton()
        colorbutton.set_color(gtk.gdk.color_parse('red'))
        hb.pack_start(colorbutton, expand=False)
        d.vbox.pack_start(hb, expand=False)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)
        d.show_all()
        dialog.center_on_mouse(d)

        res=d.run()
        ret=None
        if res == gtk.RESPONSE_OK:
            try:
                tag=unicode(tagname.get_text())
            except ValueError:
                tag=None
            color=colorbutton.get_color()
        else:
            tag=None
        d.destroy()

        if tag and not tag in self.tags:
            if not re.match('^[\w\d_]+$', tag):
                dialog.message_dialog(_("The tag contains invalid characters"),
                                               icon=gtk.MESSAGE_ERROR)
                return True
            self.tags.append(tag)
            self.controller.package._tag_colors[tag]="#%04x%04x%04x" % (color.red, color.green, color.blue)
            self.controller.notify('TagUpdate', tag=tag)
            self.refresh()
        return True
Пример #24
0
 def validate(self, *p):
     l = self.check_modified()
     if l:
         if self.options[
                 'representation'] and not helper.parsed_representation.match(
                     self.options['representation']):
             dialog.message_dialog(label=_(
                 "Cannot validate the update.\nThe representation pattern is too complex."
             ))
             return True
         self.ignore_updates = True
         self.update_modified(l)
         self.ignore_updates = False
     return True
Пример #25
0
    def new_tag(self, *p):
        """Enter a new tag.
        """
        d = Gtk.Dialog(title=_("New tag name"),
                       parent=self.controller.gui.gui.win,
                       flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
                       buttons=( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                 Gtk.STOCK_OK, Gtk.ResponseType.OK,
                                 ))
        l=Gtk.Label(label=_("Enter a new tag name and select its color."))
        d.vbox.pack_start(l, False, True, 0)

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Name")), False, False, 0)
        tagname=Gtk.Entry()
        hb.pack_start(tagname, False, True, 0)
        d.vbox.pack_start(hb, False, True, 0)

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Color")), False, False, 0)
        colorbutton=Gtk.ColorButton()
        colorbutton.set_color(Gdk.color_parse('red'))
        hb.pack_start(colorbutton, False, True, 0)
        d.vbox.pack_start(hb, False, True, 0)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)
        d.show_all()
        dialog.center_on_mouse(d)

        res=d.run()
        if res == Gtk.ResponseType.OK:
            try:
                tag=tagname.get_text()
            except ValueError:
                tag=None
            color=colorbutton.get_color()
        else:
            tag=None
        d.destroy()

        if tag and not tag in self.tags:
            if not re.match('^[\w\d_]+$', tag):
                dialog.message_dialog(_("The tag contains invalid characters"),
                                               icon=Gtk.MessageType.ERROR)
                return True
            self.tags.append(tag)
            self.controller.package._tag_colors[tag]="#%04x%04x%04x" % (color.red, color.green, color.blue)
            self.controller.notify('TagUpdate', tag=tag)
            self.refresh()
        return True
Пример #26
0
 def save_transcription(self, filename=None):
     if os.path.splitext(filename)[1] == '':
         # No extension was given. Add '.txt'
         filename=filename+'.txt'
     try:
         with open(filename, "w", encoding='utf-8') as f:
             f.writelines(self.generate_transcription())
     except IOError as e:
         dialog.message_dialog(
             _("Cannot save the file: %s") % str(e),
             icon=Gtk.MessageType.ERROR)
         return True
     self.message(_("Transcription saved to %s") % filename)
     self.sourcefile=filename
     return True
Пример #27
0
 def save_transcription(self, filename=None):
     if os.path.splitext(filename)[1] == '':
         # No extension was given. Add '.txt'
         filename=filename+'.txt'
     try:
         with open(filename, "w", encoding='utf-8') as f:
             f.writelines(self.generate_transcription())
     except IOError as e:
         dialog.message_dialog(
             _("Cannot save the file: %s") % str(e),
             icon=Gtk.MessageType.ERROR)
         return True
     self.message(_("Transcription saved to %s") % filename)
     self.sourcefile=filename
     return True
Пример #28
0
 def processing_ended(self, msg=None):
     if _thread.get_ident() != self.main_thread_id:
         self.do_gui_operation(self.processing_ended, msg=msg)
         return True
     self.progress_callback(1.0)
     self.controller.notify("PackageActivate",
                            package=self.controller.package)
     self.close()
     if msg is None:
         msg = _('Completed conversion: %(message)s\n%(statistics)s') % {
             'message': self.importer.output_message,
             'statistics': self.importer.statistics_formatted()
         }
     dialog.message_dialog(msg, modal=False)
     self.log(msg)
Пример #29
0
    def export_as_static_view(self, ident=None):
        """Propose to export the view as a static view.

        The as_html() method must be implemented.
        """
        title=None
        if ident is None:
            title, ident=self.controller.package._idgenerator.new_from_title("export " + self._label)
            title, ident=dialog.get_title_id(title=_("HTML export"),
                                      text=_("Specify a name for the export view"),
                                      element_title=title,
                                      element_id=ident)
            if ident is None:
                return True
        if title is None:
            title=ident
        # Create the view
        v=self.controller.package.createView(
            ident=ident,
            author=config.data.userid,
            date=helper.get_timestamp(),
            clazz='*',
            content_mimetype="text/html",
            )
        v.title=title
        v.content.data=self.as_html()
        self.controller.package.views.append(v)
        self.controller.notify('ViewCreate', view=v)
        d=dialog.message_dialog(_("View successfully exported as %s.\nOpen it in the web browser ?") % v.title, icon=Gtk.MessageType.QUESTION)
        if d:
            c=self.controller.build_context(here=v)
            self.controller.open_url(c.evaluateValue('package/view/%s/absolute_url' % ident))
        return True
Пример #30
0
 def csv_export(self, name=None):
     if name is None:
         name=dialog.get_filename(title=_("Export data to file..."),
                                           default_file="advene_data.csv",
                                           action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                           button=gtk.STOCK_SAVE)
     if name is None:
         return True
     try:
         f=open(name, 'w')
     except IOError, e:
         dialog.message_dialog(label=_("Error while exporting data to %(filename)s: %(error)s"
                                       % {
                     'filename': name,
                     'error': unicode(e),
                     }), icon=gtk.MESSAGE_ERROR)
Пример #31
0
    def export_as_static_view(self, ident=None):
        """Propose to export the view as a static view.

        The as_html() method must be implemented.
        """
        title = None
        if ident is None:
            title, ident = self.controller.package._idgenerator.new_from_title("export " + self._label)
            title, ident = dialog.get_title_id(
                title=_("HTML export"),
                text=_("Specify a name for the export view"),
                element_title=title,
                element_id=ident,
            )
            if ident is None:
                return True
        if title is None:
            title = ident
        # Create the view
        v = self.controller.package.create_view(ident=ident, mimetype="text/html")
        v.title = title
        v.content.data = self.as_html()
        self.controller.notify("ViewCreate", view=v)
        d = dialog.message_dialog(
            _("View successfully exported as %s.\nOpen it in the web browser ?") % v.title, icon=gtk.MESSAGE_QUESTION
        )
        if d:
            c = self.controller.build_context(here=v)
            self.controller.open_url(c.evaluate("package/view/%s/absolute_url" % ident))
        return True
Пример #32
0
    def import_annotations_cb(self, button=None):
        if not self.controller.gui:
            self.message(_("Cannot import annotations: no existing interface"))
            return True
        at=self.controller.gui.ask_for_annotation_type(text=_("Select the annotation type to import"), create=False)
        if at is None:
            return True

        self.imported_type=at

        if not self.buffer_is_empty():
            if not dialog.message_dialog(_("This will overwrite the current textual content. Are you sure?"),
                                                  icon=gtk.MESSAGE_QUESTION):
                return True

        b=self.textview.get_buffer()
        begin,end=b.get_bounds()
        b.delete(begin, end)

        last_time=None
        for a in at.annotations:
            if a.begin > last_time:
                it=b.get_iter_at_mark(b.get_insert())
                mark=self.create_timestamp_mark(a.begin, it)
            # FIXME: use self.controller.get_title ?
            b.insert_at_cursor(a.content.data)
            it=b.get_iter_at_mark(b.get_insert())
            mark=self.create_timestamp_mark(a.end, it)
            last_time = a.end
        return True
Пример #33
0
    def save_view(self, *p):
        title, ident = self.controller.package._idgenerator.new_from_title(
            self._label)
        title, ident = dialog.get_title_id(
            title=_("Saving %s" % self.view_name),
            element_title=title,
            element_id=ident,
            text=_("Enter a view name to save this parametered view"))
        if ident is not None:
            if not re.match(r'^[a-zA-Z0-9_]+$', ident):
                dialog.message_dialog(
                    _("Error: the identifier %s contains invalid characters.")
                    % ident)
                return True

            options, arguments = self.get_save_arguments()
            if options is None and arguments is None:
                # Cancel view saving
                return True

            v = helper.get_id(self.controller.package.views, ident)
            if v is None:
                create = True
                v = self.controller.package.createView(ident=ident,
                                                       clazz='package')
            else:
                # Existing view. Check that it is already an adhoc-view
                if v.content.mimetype != 'application/x-advene-adhoc-view':
                    dialog.message_dialog(
                        _("Error: the view %s is not an adhoc view.") % ident)
                    return True
                create = False
                self.controller.notify('EditSessionStart',
                                       element=v,
                                       immediate=True)
            v.title = title
            v.author = config.data.userid
            v.date = self.controller.get_timestamp()

            self.save_parameters(v.content, options, arguments)
            if create:
                self.controller.package.views.append(v)
                self.controller.notify("ViewCreate", view=v)
            else:
                self.controller.notify("ViewEditEnd", view=v)
                self.controller.notify('EditSessionEnd', element=v)
        return True
Пример #34
0
 def parse_svg(self):
     if self.element.data:
         try:
             root = ET.parse(self.element.stream).getroot()
         except xml.parsers.expat.ExpatError as e:
             root = None
             dialog.message_dialog(
                 _("Error while parsing SVG content:\n\n%s") % str(e),
                 icon=Gtk.MessageType.ERROR)
         if root is not None:
             self.view.drawer.clear_objects()
             path = ''
             if self.parent is not None and hasattr(self.parent, 'file_'):
                 # We are in a resource. Pass its path as current path.
                 path = os.path.dirname(self.parent.file_)
             self.view.drawer.parse_svg(root, current_path=path)
     return True
Пример #35
0
 def parse_svg(self):
     if self.element.data:
         try:
             root=ET.parse(self.element.stream).getroot()
         except xml.parsers.expat.ExpatError as e:
             root=None
             dialog.message_dialog(
                 _("Error while parsing SVG content:\n\n%s") % str(e),
                 icon=Gtk.MessageType.ERROR)
         if root is not None:
             self.view.drawer.clear_objects()
             path=''
             if self.parent is not None and hasattr(self.parent, 'file_'):
                 # We are in a resource. Pass its path as current path.
                 path=os.path.dirname(self.parent.file_)
             self.view.drawer.parse_svg(root, current_path=path)
     return True
Пример #36
0
 def parse_svg(self):
     if self.element.data:
         try:
             f=self.element.as_file
             root=ET.parse(f).getroot()
             f.close()
         except xml.parsers.expat.ExpatError:
             root=None
             dialog.message_dialog(
                 _("Error while parsing SVG content:\n\n%s") % unicode(e),
                 icon=gtk.MESSAGE_ERROR)
         if root:
             self.view.drawer.clear_objects()
             path=''
             if self.parent is not None and hasattr(self.parent, 'file_'):
                 # We are in a resource. Pass its path as current path.
                 path=os.path.dirname(self.parent.file_)
             self.view.drawer.parse_svg(root, current_path=path)
     return True
Пример #37
0
 def load_transcription_cb(self, button=None):
     if not self.buffer_is_empty():
         if not dialog.message_dialog(_("This will overwrite the current textual content. Are you sure?"),
                                               icon=Gtk.MessageType.QUESTION):
             return True
     fname=dialog.get_filename(title=_("Select transcription file to load"),
                                        default_dir=str(config.data.path['data']))
     if fname is not None:
         self.load_transcription(filename=fname)
     return True
Пример #38
0
        def validate(b):
            m = self.mergerview.store
            suffix = self.suffix_entry.get_text().strip()
            if not suffix:
                dialog.message_dialog(_("The suffix cannot be empty."),
                                      icon=Gtk.MessageType.ERROR)
                return True

            annotation_count = 0
            type_count = 0
            # Let's use differ methods to copy elements
            differ = Differ(source=self.sourcepackage,
                            destination=self.destpackage,
                            controller=self.controller)
            batch_id = object()
            for l in m:
                if l[self.mergerview.COLUMN_APPLY]:
                    source_at = l[self.mergerview.COLUMN_ELEMENT]
                    logger.debug("Copying %s (%d annotations)",
                                 source_at.title, len(source_at.annotations))
                    type_count += 1
                    dest_at = differ.copy_annotation_type(source_at,
                                                          generate_id=True)
                    dest_at.title = "%s %s" % (dest_at.title, suffix)
                    self.controller.notify('AnnotationTypeCreate',
                                           annotationtype=dest_at,
                                           immediate=True,
                                           batch=batch_id)
                    for a in source_at.annotations:
                        annotation_count += 1
                        # Since we copied the annotation type before, copy_annotation should use the translated name
                        new_a = differ.copy_annotation(a, generate_id=True)
                        self.controller.notify('AnnotationCreate',
                                               annotation=new_a,
                                               immediate=True,
                                               batch=batch_id)
            logger.info(
                _("Copied %(count)d annotations from %(tcount)d types") % {
                    "count": annotation_count,
                    "tcount": type_count
                })
            self.close()
            return True
Пример #39
0
 def load_transcription_cb(self, button=None):
     if not self.buffer_is_empty():
         if not dialog.message_dialog(_("This will overwrite the current textual content. Are you sure?"),
                                               icon=Gtk.MessageType.QUESTION):
             return True
     fname=dialog.get_filename(title=_("Select transcription file to load"),
                                        default_dir=str(config.data.path['data']))
     if fname is not None:
         self.load_transcription(filename=fname)
     return True
Пример #40
0
    def update_modified(self, l):
        def update(a, text):
            """Update an annotation content according to its representation.

            If the update is not possible (too complex representation), return False.
            """
            if self.options['default-representation']:
                rep=a.type.representation or ""
            else:
                rep=self.options['representation']
            m=parsed_representation.match(rep)
            if m:
                # We have a simple representation (here/content/parsed/name)
                # so we can update the name field.
                name=m.group(1)
                reg = re.compile('^' + name + '=(.+?)$', re.MULTILINE)
                a.content.data = reg.sub(name + '=' + text, a.content.data)
            else:
                m=empty_representation.match(rep)
                if m:
                    a.content.data = text
                else:
                    return False
            return True

        b=self.textview.get_buffer()
        impossible=[]
        batch_id=object()
        for a in l:
            beginiter=b.get_iter_at_mark(b.get_mark("b_%s" % a.id))
            enditer  =b.get_iter_at_mark(b.get_mark("e_%s" % a.id))
            self.controller.notify('EditSessionStart', element=a, immediate=True)
            if update(a, b.get_text(beginiter, enditer)):
                self.controller.notify("AnnotationEditEnd", annotation=a, batch=batch_id)
            else:
                impossible.append(a)
            self.controller.notify('EditSessionEnd', element=a)
        if impossible:
            dialog.message_dialog(label=_("Cannot convert the following annotations,\nthe representation pattern is too complex.\n%s") % ",".join( [ a.id for a in impossible ] ))
        return True
Пример #41
0
    def create_follow_dynamic_view(self, rt):
        """Create a dynamic view for the given relation-type.
        """
        p = self.controller.package
        ident = 'v_follow_%s' % rt.id
        if p.get_element_by_id(ident) is not None:
            dialog.message_dialog(
                _("A follow dynamic view for %s already seems to exist.") %
                self.get_title(rt))
            return True
        v = p.createView(ident=ident,
                         author=config.data.userid,
                         date=self.controller.get_timestamp(),
                         clazz='package',
                         content_mimetype='application/x-advene-ruleset')
        v.title = _("Follow %s relation-type") % self.get_title(rt)

        # Build the ruleset
        r = RuleSet()
        catalog = self.controller.event_handler.catalog

        ra = catalog.get_action("PlayerGoto")
        action = Action(registeredaction=ra, catalog=catalog)
        action.add_parameter(
            'position',
            'annotation/typedRelatedOut/%s/first/fragment/begin' % rt.id)
        rule = Rule(name=_("Follow the relation"),
                    event=Event("AnnotationEnd"),
                    condition=Condition(lhs='annotation/typedRelatedOut/%s' %
                                        rt.id,
                                        operator='value'),
                    action=action)
        r.add_rule(rule)

        v.content.data = r.xml_repr()

        p.views.append(v)
        self.controller.notify('ViewCreate', view=v)
        self.controller.activate_stbv(v)
        return True
Пример #42
0
    def import_annotations_cb(self, button=None):
        if not self.controller.gui:
            self.message(_("Cannot import annotations: no existing interface"))
            return True
        at=self.controller.gui.ask_for_annotation_type(text=_("Select the annotation type to import"),
                                                       create=False,
                                                       default=self.controller.package.get_element_by_id(self.options['annotation-type-id']))
        if at is None:
            return True

        self.options['annotation-type-id'] = at.id

        if not at.annotations:
            dialog.message_dialog(_("There are no annotations of type %s") % self.controller.get_title(at))
            return True

        if not self.buffer_is_empty():
            if not dialog.message_dialog(_("This will overwrite the current textual content. Are you sure?"),
                                                  icon=Gtk.MessageType.QUESTION):
                return True

        b=self.textview.get_buffer()
        begin,end=b.get_bounds()
        b.delete(begin, end)

        al=at.annotations
        al.sort(key=lambda a: a.fragment.begin)

        last_time=-1

        for a in al:
            if a.fragment.begin > last_time:
                it=b.get_iter_at_mark(b.get_insert())
                self.create_timestamp_mark(a.fragment.begin, it)
            b.insert_at_cursor(a.content.data)
            it=b.get_iter_at_mark(b.get_insert())
            self.create_timestamp_mark(a.fragment.end, it)
            last_time = a.fragment.end
        return True
Пример #43
0
    def create_dynamic_view(self, at):
        """Create a caption dynamic view for the given annotation-type.
        """
        p = self.controller.package
        ident = 'v_caption_%s' % at.id
        if p.get_element_by_id(ident) is not None:
            dialog.message_dialog(
                _("A caption dynamic view for %s already seems to exist.") %
                self.get_title(at))
            return True
        v = p.createView(ident=ident,
                         author=config.data.userid,
                         date=self.controller.get_timestamp(),
                         clazz='package',
                         content_mimetype='application/x-advene-ruleset')
        v.title = _("Caption %s annotations") % self.get_title(at)

        # Build the ruleset
        r = RuleSet()
        catalog = self.controller.event_handler.catalog

        ra = catalog.get_action("AnnotationCaption")
        action = Action(registeredaction=ra, catalog=catalog)
        action.add_parameter('message', 'annotation/content/data')

        rule = Rule(name=_("Caption the annotation"),
                    event=Event("AnnotationBegin"),
                    condition=Condition(lhs='annotation/type/id',
                                        operator='equals',
                                        rhs='string:%s' % at.id),
                    action=action)
        r.add_rule(rule)

        v.content.data = r.xml_repr()

        p.views.append(v)
        self.controller.notify('ViewCreate', view=v)
        self.controller.activate_stbv(v)
        return True
Пример #44
0
    def import_annotations_cb(self, button=None):
        if not self.controller.gui:
            self.message(_("Cannot import annotations: no existing interface"))
            return True
        at=self.controller.gui.ask_for_annotation_type(text=_("Select the annotation type to import"),
                                                       create=False,
                                                       default=self.controller.package.get_element_by_id(self.options['annotation-type-id']))
        if at is None:
            return True

        self.options['annotation-type-id'] = at.id

        if not at.annotations:
            dialog.message_dialog(_("There are no annotations of type %s") % self.controller.get_title(at))
            return True

        if not self.buffer_is_empty():
            if not dialog.message_dialog(_("This will overwrite the current textual content. Are you sure?"),
                                                  icon=Gtk.MessageType.QUESTION):
                return True

        b=self.textview.get_buffer()
        begin,end=b.get_bounds()
        b.delete(begin, end)

        al=at.annotations
        al.sort(key=lambda a: a.fragment.begin)

        last_time=-1

        for a in al:
            if a.fragment.begin > last_time:
                it=b.get_iter_at_mark(b.get_insert())
                self.create_timestamp_mark(a.fragment.begin, it)
            b.insert_at_cursor(a.content.data)
            it=b.get_iter_at_mark(b.get_insert())
            self.create_timestamp_mark(a.fragment.end, it)
            last_time = a.fragment.end
        return True
Пример #45
0
    def save_view(self, *p):
        title, ident=self.controller.package._idgenerator.new_from_title(self._label)
        title, ident=dialog.get_title_id(title=_("Saving %s" % self.view_name),
                                                  element_title=title,
                                                  element_id=ident,
                                                  text=_("Enter a view name to save this parametered view"))
        if ident is not None:
            if not re.match(r'^[a-zA-Z0-9_]+$', ident):
                dialog.message_dialog(_("Error: the identifier %s contains invalid characters.") % ident)
                return True

            options, arguments = self.get_save_arguments()
            if options is None and arguments is None:
                # Cancel view saving
                return True

            v=helper.get_id(self.controller.package.views, ident)
            if v is None:
                create=True
                v=self.controller.package.createView(ident=ident, clazz='package')
            else:
                # Existing view. Check that it is already an adhoc-view
                if v.content.mimetype != 'application/x-advene-adhoc-view':
                    dialog.message_dialog(_("Error: the view %s is not an adhoc view.") % ident)
                    return True
                create=False
                self.controller.notify('EditSessionStart', element=v, immediate=True)
            v.title=title
            v.author=config.data.userid
            v.date=self.controller.get_timestamp()

            self.save_parameters(v.content, options, arguments)
            if create:
                self.controller.package.views.append(v)
                self.controller.notify("ViewCreate", view=v)
            else:
                self.controller.notify("ViewEditEnd", view=v)
                self.controller.notify('EditSessionEnd', element=v)
        return True
Пример #46
0
    def close(self, *p):
        l=self.check_modified()
        if l:
            if self.options['representation'] and not parsed_representation.match(self.options['representation']):
                def close_cb():
                    AdhocView.close(self)
                    return True

                dialog.message_dialog(label=_("%d annotation(s) were modified\nbut we cannot propagate the modifications\nsince the representation parameter is used.") % len(l), callback=close_cb)
            else:
                def handle_modified():
                    self.log(_("Updating modified annotations"))
                    self.ignore_updates = True
                    self.update_modified(l)
                    AdhocView.close(self)
                    return True
                dialog.message_dialog(label=_("%d annotations were modified.\nDo you want to update their content?") % len(l),
                                      icon=gtk.MESSAGE_QUESTION,
                                      callback=handle_modified)
        else:
            AdhocView.close(self)
        return True
Пример #47
0
    def create_follow_dynamic_view(self, rt):
        """Create a dynamic view for the given relation-type.
        """
        p = self.controller.package
        ident = 'v_follow_%s' % rt.id
        if p.get_element_by_id(ident) is not None:
            dialog.message_dialog(_("A follow dynamic view for %s already seems to exist.") % self.get_title(rt))
            return True
        v = p.createView(
            ident=ident,
            author=config.data.userid,
            date=self.controller.get_timestamp(),
            clazz='package',
            content_mimetype='application/x-advene-ruleset'
            )
        v.title = _("Follow %s relation-type") % self.get_title(rt)

        # Build the ruleset
        r = RuleSet()
        catalog = self.controller.event_handler.catalog

        ra = catalog.get_action("PlayerGoto")
        action = Action(registeredaction=ra, catalog=catalog)
        action.add_parameter('position', 'annotation/typedRelatedOut/%s/first/fragment/begin' % rt.id)
        rule=Rule(name=_("Follow the relation"),
                  event=Event("AnnotationEnd"),
                  condition=Condition(lhs='annotation/typedRelatedOut/%s' % rt.id,
                                      operator='value'),
                  action=action)
        r.add_rule(rule)

        v.content.data=r.xml_repr()

        p.views.append(v)
        self.controller.notify('ViewCreate', view=v)
        self.controller.activate_stbv(v)
        return True
Пример #48
0
 def set_time(self, attr):
     """Sets the time of the current annotation to the current player time.
     """
     an, an_path = self.get_selected_node(with_path=True)
     if an is None:
         return
     current_time = self.controller.player.current_position_value
     confirm = True
     if self.options['confirm-time-update']:
         confirm = dialog.message_dialog(_("Set %(attr)s time to %(time)s") % {
             'attr': _(attr),
             'time': helper.format_time(current_time)
             }, icon=Gtk.MessageType.QUESTION)
     if confirm:
         self.last_edited_path = an_path
         self.controller.notify('EditSessionStart', element=an, immediate=True)
         setattr(an.fragment, attr, current_time)
         self.controller.notify("AnnotationEditEnd", annotation=an)
         self.controller.notify('EditSessionEnd', element=an)
Пример #49
0
    def export(self, b, *p):
        fname = self.get_filename() or self.filename
        if self.exporter is None:
            ec = self.exporters.get_current_element()

            if fname.startswith('file://'):
                fname = fname.replace('file://', '')
            if ec is None:
                return True
            e = ec(controller=self.controller,
                   source=self.source,
                   callback=self.progress_callback)
            self.exporter = e
        else:
            e = self.exporter
        e.set_options(self.optionform.options)
        e.set_source(self.source)
        e.get_preferences().update(dict(self.optionform.options))
        e.package = self.controller.package

        message = "Exporting data"
        # Standard, synchronous version
        try:
            e.export(fname)
            message = _(
                "Data exported to\n%s\nDo you want to open it?") % fname
            icon = Gtk.MessageType.QUESTION
        except Exception as e:
            message = _("Error when exporting data: %s") % "\n".join(
                str(a) for a in e.args)
            logger.exception(message)
            icon = Gtk.MessageType.ERROR
        if dialog.message_dialog(
                message, icon=icon) and icon == Gtk.MessageType.QUESTION:
            # Try to open the file
            open_in_filebrowser(fname)
            pass
        # Close view
        self.close()
        return True
Пример #50
0
 def set_time(self, attr):
     """Sets the time of the current annotation to the current player time.
     """
     an, an_path = self.get_selected_node(with_path=True)
     if an is None:
         return
     current_time = self.controller.player.current_position_value
     confirm = True
     if self.options['confirm-time-update']:
         confirm = dialog.message_dialog(
             _("Set %(attr)s time to %(time)s") % {
                 'attr': _(attr),
                 'time': helper.format_time(current_time)
             },
             icon=Gtk.MessageType.QUESTION)
     if confirm:
         self.last_edited_path = an_path
         self.controller.notify('EditSessionStart',
                                element=an,
                                immediate=True)
         setattr(an.fragment, attr, current_time)
         self.controller.notify("AnnotationEditEnd", annotation=an)
         self.controller.notify('EditSessionEnd', element=an)
Пример #51
0
    def do_create_element(self):
        """Create the element according to the widget data.

        @return: the created element, None if an error occurred
        """
        id_ = unicode(self.dialog.id_entry.get_text())
        title_ = unicode(self.dialog.title_entry.get_text())
        # Check validity of id.
        if not self.is_valid_id(id_):
            dialog.message_dialog(
                _("The identifier %s is not valid.\nIt must be composed of non-accentuated alphabetic characters\nUnderscore is allowed."
                  ) % id_)
            return None

        if self.controller.package._idgenerator.exists(id_):
            dialog.message_dialog(
                _("The identifier %s is already defined.") % id_)
            return None
        else:
            self.controller.package._idgenerator.add(id_)

        if self.dialog.type_combo:
            t = self.dialog.type_combo.get_current_element()

        if self.type_ == Annotation:
            if isinstance(self.parent, AnnotationType):
                parent = self.parent.rootPackage
            else:
                parent = self.parent
            el = parent.createAnnotation(
                ident=id_,
                type=t,
                author=config.data.userid,
                date=self.get_date(),
                fragment=MillisecondFragment(
                    begin=0, duration=self.controller.player.stream_duration))
            if el.type._fieldnames:
                el.content.data = "\n".join(sorted(el.type._fieldnames))
            parent.annotations.append(el)
            self.controller.notify('AnnotationCreate', annotation=el)
        elif self.type_ == Relation:
            # Unused code: relations can not be created without annotations
            if isinstance(self.parent, RelationType):
                parent = self.parent.rootPackage
            else:
                parent = self.parent
            el = parent.createRelation(ident=id_,
                                       type=t,
                                       author=config.data.userid,
                                       date=self.get_date(),
                                       members=())
            parent.relations.append(el)
            self.controller.notify('RelationCreate', relation=el)
        elif self.type_ == Query:
            el = self.parent.createQuery(ident=id_)
            el.author = config.data.userid
            el.date = self.get_date()
            el.title = title_
            el.content.mimetype = t.id
            if t.id == 'application/x-advene-simplequery':
                # Create a basic query
                q = advene.rules.elements.SimpleQuery(sources=["here"])
                el.content.data = q.xml_repr()
                el.content.mimetype = t.id
            self.parent.queries.append(el)
            self.controller.notify('QueryCreate', query=el)
        elif self.type_ == View:
            el = self.parent.createView(
                ident=id_,
                author=config.data.userid,
                date=self.get_date(),
                clazz=self.parent.viewableClass,
                content_mimetype=t.id,
            )
            el.title = title_
            if t.id == 'application/x-advene-ruleset':
                # Create an empty ruleset to begin with
                r = RuleSet()

                # Create a new default Rule
                rule = SubviewList(name=_("Subviews"), elements=[])
                r.add_rule(rule)

                event = Event("AnnotationBegin")
                catalog = self.controller.event_handler.catalog
                ra = catalog.get_action("Message")
                action = Action(registeredaction=ra, catalog=catalog)
                for p in ra.parameters:
                    action.add_parameter(p, ra.defaults.get(p, ''))
                rule = Rule(name=_("Rule") + '1', event=event, action=action)
                r.add_rule(rule)

                el.content.data = r.xml_repr()

            self.parent.views.append(el)
            self.controller.notify('ViewCreate', view=el)
        elif self.type_ == Schema:
            el = self.parent.createSchema(ident=id_)
            el.author = config.data.userid
            el.date = self.get_date()
            el.title = title_
            self.parent.schemas.append(el)
            self.controller.notify('SchemaCreate', schema=el)
        elif self.type_ == AnnotationType:
            if not isinstance(self.parent, Schema):
                print "Error: bad invocation of CreateElementPopup"
                el = None
            else:
                el = self.parent.createAnnotationType(ident=id_)
                el.author = config.data.userid
                el.date = self.get_date()
                el.title = title_
                el.mimetype = t.id
                el.setMetaData(config.data.namespace, 'color',
                               self.parent.rootPackage._color_palette.next())
                el.setMetaData(config.data.namespace, 'item_color',
                               'here/tag_color')
            self.parent.annotationTypes.append(el)
            self.controller.notify('AnnotationTypeCreate', annotationtype=el)
        elif self.type_ == RelationType:
            if not isinstance(self.parent, Schema):
                print "Error: bad invocation of CreateElementPopup"
                el = None
            else:
                el = self.parent.createRelationType(ident=id_)
                el.author = config.data.userid
                el.date = self.get_date()
                el.title = title_
                el.mimetype = t.id
                el.setMetaData(config.data.namespace, 'color',
                               self.parent.rootPackage._color_palette.next())
                el.setMetaData(config.data.namespace, 'item_color',
                               'here/tag_color')
                # Create a generic binary relationType
                el.hackedMemberTypes = (u'', u'')
            self.parent.relationTypes.append(el)
            self.controller.notify('RelationTypeCreate', relationtype=el)
        elif self.type_ == Resources:
            # Create a new dir.
            # Parent should be a Resources
            self.parent[id_] = Resources.DIRECTORY_TYPE
            el = self.parent[id_]
            self.controller.notify('ResourceCreate', resource=el)
        elif self.type_ == ResourceData:
            # Create a new resource file
            self.parent[id_] = _("New resource data")
            el = self.parent[id_]
            self.controller.notify('ResourceCreate', resource=el)

        else:
            el = None
            print "Not implemented yet."
        return el
Пример #52
0
    def build_widget(self, modal=False):
        i=self.generate_id()
        if modal:
            flags=gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL
        else:
            flags=gtk.DIALOG_DESTROY_WITH_PARENT

        d=dialog.title_id_dialog(title=_("%s creation")  % element_label[self.type_],
                                          text=_("To create a new element of type %s,\nyou must give the following information.") % element_label[self.type_],
                                          element_title=i,
                                          element_id=i,
                                          flags=flags)
        d.type_combo=None

        # Choose a type if possible
        if self.type_ in (Annotation, Relation, AnnotationType, RelationType,
                          View, Query, Resources, ResourceData):
            hbox = gtk.HBox()
            l = gtk.Label(_("Type"))
            hbox.pack_start(l)

            if self.type_ == Annotation:
                if isinstance(self.parent, AnnotationType):
                    type_list = [ self.parent ]
                else:
                    type_list = self.parent.annotationTypes
            elif self.type_ == Relation:
                if isinstance(self.parent, RelationType):
                    type_list = [ self.parent ]
                else:
                    type_list = self.parent.relationTypes
            elif self.type_ in (AnnotationType, RelationType):
                type_list = [ ViewType('text/plain', _("Plain text content")),
                              ViewType('application/x-advene-structured', _("Simple-structured content")),
                              ViewType('image/svg+xml', _("SVG graphics content")),
                              ]
            elif self.type_ == View:
                type_list = [ ViewType('application/x-advene-ruleset', _("Dynamic view")),
                              ViewType('text/html', _("HTML template")),
                              ViewType('application/xml', _("Plain XML")),
                              ViewType('image/svg+xml', _("SVG template")),
                              ViewType('text/plain', _("Plain text template")),
                              ]
            elif self.type_ == Query:
                type_list = [ ViewType('application/x-advene-simplequery', _("Simple query")) ]
            elif self.type_ == Resources:
                type_list = [ ViewType(Resources.DIRECTORY_TYPE, _("Directory")) ]
            elif self.type_ == ResourceData:
                type_list = [ ViewType("file", _("Resource File")) ]
            else:
                print "Error in advene.gui.edit.create.build_widget: invalid type %s" % self.type_
                return None

            if not type_list:
                dialog.message_dialog(_("No available type."))
                return None

            # Check for self.mimetype
            if self.mimetype is None:
                preselect=type_list[0]
            else:
                l=[ e for e in type_list if e.id == self.mimetype ]
                if l:
                    preselect=l[0]
                else:
                    # Insert self.mimetype in the list
                    preselect=ViewType(self.mimetype, self.mimetype)
                    type_list.insert(0, preselect)
            d.type_combo = dialog.list_selector_widget(
                members=[ (t, self.controller.get_title(t)) for t in type_list  ],
                preselect=preselect)
            hbox.pack_start(d.type_combo)

            d.vbox.add(hbox)

        d.show_all()
        return d
Пример #53
0
    def convert_transcription_cb(self, button=None):
        if not self.controller.gui:
            self.message(_("Cannot convert the data: no associated package"))
            return True

        d = Gtk.Dialog(title=_("Converting transcription"),
                       parent=self.controller.gui.gui.win,
                       flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
                       buttons=( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                 Gtk.STOCK_OK, Gtk.ResponseType.OK,
                                 ))
        l=Gtk.Label(label=_("Choose the annotation-type where to create annotations.\n"))
        l.set_line_wrap(True)
        l.show()
        d.vbox.pack_start(l, False, True, 0)

        # Anticipated declaration of some widgets, which need to be
        # updated in the handle_new_type_selection callback.
        new_type_dialog=Gtk.VBox()
        delete_existing_toggle=Gtk.CheckButton(_("Delete existing annotations in this type"))
        delete_existing_toggle.set_active(False)

        ats=list(self.controller.package.annotationTypes)
        newat=helper.TitledElement(value=None,
                                   title=_("Create a new annotation type"))
        ats.append(newat)

        def handle_new_type_selection(combo):
            el=combo.get_current_element()
            if el == newat:
                new_type_dialog.show()
                delete_existing_toggle.set_sensitive(False)
            else:
                new_type_dialog.hide()
                delete_existing_toggle.set_sensitive(True)
            return True

        type_selection=dialog.list_selector_widget(members=[ (a, self.controller.get_title(a), self.controller.get_element_color(a)) for a in ats],
                                                   callback=handle_new_type_selection,
                                                   preselect=self.controller.package.get_element_by_id(self.options['annotation-type-id']))

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Select type") + " "), False, False, 0)
        hb.pack_start(type_selection, False, True, 0)
        d.vbox.pack_start(hb, False, True, 0)

        l=Gtk.Label(label=_("You want to create a new type. Please specify its schema and title."))
        l.set_line_wrap(True)
        l.show()
        new_type_dialog.pack_start(l, False, True, 0)

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Title") + " "), False, False, 0)
        new_title=Gtk.Entry()
        hb.pack_start(new_title, True, True, 0)
        new_type_dialog.pack_start(hb, False, True, 0)

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Containing schema") + " "), False, False, 0)
        schemas=list(self.controller.package.schemas)
        schema_selection=dialog.list_selector_widget(members=[ (s, self.controller.get_title(s)) for s in schemas])
        hb.pack_start(schema_selection, False, True, 0)
        new_type_dialog.pack_start(hb, False, True, 0)

        new_type_dialog.show_all()
        new_type_dialog.set_no_show_all(True)
        new_type_dialog.hide()

        d.vbox.pack_start(new_type_dialog, True, True, 0)

        l=Gtk.Label()
        l.set_markup("<b>" + _("Export options") + "</b>")
        d.vbox.pack_start(l, False, True, 0)

        d.vbox.pack_start(delete_existing_toggle, False, True, 0)

        empty_contents_toggle=Gtk.CheckButton(_("Generate annotations for empty contents"))
        empty_contents_toggle.set_active(self.options['empty-annotations'])
        d.vbox.pack_start(empty_contents_toggle, False, True, 0)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)

        d.show_all()
        dialog.center_on_mouse(d)

        finished=None
        while not finished:
            res=d.run()
            if res == Gtk.ResponseType.OK:
                at=type_selection.get_current_element()
                if at == newat:
                    new_type_title=new_title.get_text()
                    if new_type_title == '':
                        # Empty title. Generate one.
                        id_=self.controller.package._idgenerator.get_id(AnnotationType)
                        new_type_title=id_
                    else:
                        id_=helper.title2id(new_type_title)
                        # Check that the id is available
                        if self.controller.package._idgenerator.exists(id_):
                            dialog.message_dialog(
                                _("The %s identifier already exists. Choose another one.") % id_,
                                icon=Gtk.MessageType.WARNING)
                            at=None
                            continue
                    # Creating a new type
                    s=schema_selection.get_current_element()
                    at=s.createAnnotationType(ident=id_)
                    at.author=config.data.userid
                    at.date=helper.get_timestamp()
                    at.title=new_type_title
                    at.mimetype='text/plain'
                    at.setMetaData(config.data.namespace, 'color', next(s.rootPackage._color_palette))
                    at.setMetaData(config.data.namespace, 'item_color', 'here/tag_color')
                    s.annotationTypes.append(at)
                    self.controller.notify('AnnotationTypeCreate', annotationtype=at)

                if delete_existing_toggle.get_active():
                    # Remove all annotations of at type
                    batch_id=object()
                    for a in at.annotations:
                        self.controller.delete_element(a, batch=batch_id)

                self.options['empty-annotations']=empty_contents_toggle.get_active()
                finished=True
            else:
                at=None
                finished=True
        d.destroy()

        if at is not None:
            self.options['annotation-type-id'] = at.id
            ti=TranscriptionImporter(package=self.controller.package,
                                     controller=self.controller,
                                     defaulttype=at,
                                     transcription_edit=self)
            ti.process_file('transcription')

            self.controller.package._modified=True
            self.controller.notify("PackageActivate", package=ti.package)
            self.message(_('Notes converted'))
            self.log(ti.statistics_formatted())
            # Feedback
            dialog.message_dialog(
                _("Conversion completed.\n%s annotations generated.") % ti.statistics['annotation'])

        return True
Пример #54
0
    def convert_file(self, b, *p):
        stop_label = _("Stop")
        if b.get_label() == stop_label:
            # Cancel action
            self.should_continue = False
            b.set_sensitive(False)
            return True

        if self.importer is None:
            ic = self.importers.get_current_element()
            fname = self.filename or self.fb.get_filename() or self.fb.get_uri(
            )

            if fname.startswith('file://'):
                fname = fname.replace('file://', '')
            if ic == dummy_advene_importer:
                # Invoke the package merge functionality.
                try:
                    source = Package(uri=fname)
                except Exception as e:
                    self.log("Cannot load %s file: %s" % (fname, str(e)))
                    return True
                self.controller.gui.open_adhoc_view(
                    'packageimporter',
                    sourcepackage=source,
                    destpackage=self.controller.package)
                self.close()
                return True

            if ic is None:
                return True
            i = ic(controller=self.controller, callback=self.progress_callback)
            self.importer = i
        else:
            i = self.importer
            fname = self.filename
        i.set_options(self.optionform.options)
        i.get_preferences().update(dict(self.optionform.options))
        i.package = self.controller.package

        reqs = i.check_requirements()
        if reqs:
            # Not all requirements are met. Display some information.
            dialog.message_dialog(_("The filter is not ready.\n%s") %
                                  "\n".join(reqs),
                                  modal=True)
            return True

        # Update Start button to Stop and disable GUI elements
        b.set_label(stop_label)
        self.importers.set_sensitive(False)
        self.fb.set_sensitive(False)

        if hasattr(i, 'async_process_file'):
            # Asynchronous version.
            try:
                i.async_process_file(fname, self.processing_ended)
            except Exception as e:
                dialog.message_dialog(str(e.args), modal=False)
                self.close()
        else:
            # Standard, synchronous version
            try:
                i.process_file(fname)
            except Exception as e:
                dialog.message_dialog(str(e.args), modal=False)
                logger.exception("Error in processing import data")
            finally:
                self.processing_ended()
        return True
Пример #55
0
    def convert_transcription_cb(self, button=None):
        if not self.controller.gui:
            self.message(_("Cannot convert the data: no associated package"))
            return True

        d = Gtk.Dialog(title=_("Converting transcription"),
                       parent=self.controller.gui.gui.win,
                       flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
                       buttons=( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                 Gtk.STOCK_OK, Gtk.ResponseType.OK,
                                 ))
        l=Gtk.Label(label=_("Choose the annotation-type where to create annotations.\n"))
        l.set_line_wrap(True)
        l.show()
        d.vbox.pack_start(l, False, True, 0)

        # Anticipated declaration of some widgets, which need to be
        # updated in the handle_new_type_selection callback.
        new_type_dialog=Gtk.VBox()
        delete_existing_toggle=Gtk.CheckButton(_("Delete existing annotations in this type"))
        delete_existing_toggle.set_active(False)

        ats=list(self.controller.package.annotationTypes)
        newat=helper.TitledElement(value=None,
                                   title=_("Create a new annotation type"))
        ats.append(newat)

        def handle_new_type_selection(combo):
            el=combo.get_current_element()
            if el == newat:
                new_type_dialog.show()
                delete_existing_toggle.set_sensitive(False)
            else:
                new_type_dialog.hide()
                delete_existing_toggle.set_sensitive(True)
            return True

        type_selection=dialog.list_selector_widget(members=[ (a, self.controller.get_title(a), self.controller.get_element_color(a)) for a in ats],
                                                   callback=handle_new_type_selection,
                                                   preselect=self.controller.package.get_element_by_id(self.options['annotation-type-id']))

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Select type") + " "), False, False, 0)
        hb.pack_start(type_selection, False, True, 0)
        d.vbox.pack_start(hb, False, True, 0)

        l=Gtk.Label(label=_("You want to create a new type. Please specify its schema and title."))
        l.set_line_wrap(True)
        l.show()
        new_type_dialog.pack_start(l, False, True, 0)

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Title") + " "), False, False, 0)
        new_title=Gtk.Entry()
        hb.pack_start(new_title, True, True, 0)
        new_type_dialog.pack_start(hb, False, True, 0)

        hb=Gtk.HBox()
        hb.pack_start(Gtk.Label(_("Containing schema") + " "), False, False, 0)
        schemas=list(self.controller.package.schemas)
        schema_selection=dialog.list_selector_widget(members=[ (s, self.controller.get_title(s)) for s in schemas])
        hb.pack_start(schema_selection, False, True, 0)
        new_type_dialog.pack_start(hb, False, True, 0)

        new_type_dialog.show_all()
        new_type_dialog.set_no_show_all(True)
        new_type_dialog.hide()

        d.vbox.pack_start(new_type_dialog, True, True, 0)

        l=Gtk.Label()
        l.set_markup("<b>" + _("Export options") + "</b>")
        d.vbox.pack_start(l, False, True, 0)

        d.vbox.pack_start(delete_existing_toggle, False, True, 0)

        empty_contents_toggle=Gtk.CheckButton(_("Generate annotations for empty contents"))
        empty_contents_toggle.set_active(self.options['empty-annotations'])
        d.vbox.pack_start(empty_contents_toggle, False, True, 0)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)

        d.show_all()
        dialog.center_on_mouse(d)

        finished=None
        while not finished:
            res=d.run()
            if res == Gtk.ResponseType.OK:
                at=type_selection.get_current_element()
                if at == newat:
                    new_type_title=new_title.get_text()
                    if new_type_title == '':
                        # Empty title. Generate one.
                        id_=self.controller.package._idgenerator.get_id(AnnotationType)
                        new_type_title=id_
                    else:
                        id_=helper.title2id(new_type_title)
                        # Check that the id is available
                        if self.controller.package._idgenerator.exists(id_):
                            dialog.message_dialog(
                                _("The %s identifier already exists. Choose another one.") % id_,
                                icon=Gtk.MessageType.WARNING)
                            at=None
                            continue
                    # Creating a new type
                    s=schema_selection.get_current_element()
                    at=s.createAnnotationType(ident=id_)
                    at.author=config.data.userid
                    at.date=helper.get_timestamp()
                    at.title=new_type_title
                    at.mimetype='text/plain'
                    at.setMetaData(config.data.namespace, 'color', next(s.rootPackage._color_palette))
                    at.setMetaData(config.data.namespace, 'item_color', 'here/tag_color')
                    s.annotationTypes.append(at)
                    self.controller.notify('AnnotationTypeCreate', annotationtype=at)

                if delete_existing_toggle.get_active():
                    # Remove all annotations of at type
                    batch_id=object()
                    for a in at.annotations:
                        self.controller.delete_element(a, batch=batch_id)

                self.options['empty-annotations']=empty_contents_toggle.get_active()
                finished=True
            else:
                at=None
                finished=True
        d.destroy()

        if at is not None:
            self.options['annotation-type-id'] = at.id
            ti=TranscriptionImporter(package=self.controller.package,
                                     controller=self.controller,
                                     defaulttype=at,
                                     transcription_edit=self)
            ti.process_file('transcription')

            self.controller.package._modified=True
            self.controller.notify("PackageActivate", package=ti.package)
            self.message(_('Notes converted'))
            self.log(ti.statistics_formatted())
            # Feedback
            dialog.message_dialog(
                _("Conversion completed.\n%s annotations generated.") % ti.statistics['annotation'])

        return True
Пример #56
0
    def build_widget(self, modal=False):
        i = self.generate_id()
        if modal:
            flags = gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL
        else:
            flags = gtk.DIALOG_DESTROY_WITH_PARENT

        d = dialog.title_id_dialog(
            title=_("%s creation") % element_label[self.type_],
            text=
            _("To create a new element of type %s,\nyou must give the following information."
              ) % element_label[self.type_],
            element_title=i,
            element_id=i,
            flags=flags)
        d.type_combo = None

        # Choose a type if possible
        if self.type_ in (Annotation, Relation, AnnotationType, RelationType,
                          View, Query, Resources, ResourceData):
            hbox = gtk.HBox()
            l = gtk.Label(_("Type"))
            hbox.pack_start(l)

            if self.type_ == Annotation:
                if isinstance(self.parent, AnnotationType):
                    type_list = [self.parent]
                else:
                    type_list = self.parent.annotationTypes
            elif self.type_ == Relation:
                if isinstance(self.parent, RelationType):
                    type_list = [self.parent]
                else:
                    type_list = self.parent.relationTypes
            elif self.type_ in (AnnotationType, RelationType):
                type_list = [
                    ViewType('text/plain', _("Plain text content")),
                    ViewType('application/x-advene-structured',
                             _("Simple-structured content")),
                    ViewType('image/svg+xml', _("SVG graphics content")),
                ]
            elif self.type_ == View:
                type_list = [
                    ViewType('application/x-advene-ruleset',
                             _("Dynamic view")),
                    ViewType('text/html', _("HTML template")),
                    ViewType('application/xml', _("Plain XML")),
                    ViewType('image/svg+xml', _("SVG template")),
                    ViewType('text/plain', _("Plain text template")),
                ]
            elif self.type_ == Query:
                type_list = [
                    ViewType('application/x-advene-simplequery',
                             _("Simple query"))
                ]
            elif self.type_ == Resources:
                type_list = [
                    ViewType(Resources.DIRECTORY_TYPE, _("Directory"))
                ]
            elif self.type_ == ResourceData:
                type_list = [ViewType("file", _("Resource File"))]
            else:
                print "Error in advene.gui.edit.create.build_widget: invalid type %s" % self.type_
                return None

            if not type_list:
                dialog.message_dialog(_("No available type."))
                return None

            # Check for self.mimetype
            if self.mimetype is None:
                preselect = type_list[0]
            else:
                l = [e for e in type_list if e.id == self.mimetype]
                if l:
                    preselect = l[0]
                else:
                    # Insert self.mimetype in the list
                    preselect = ViewType(self.mimetype, self.mimetype)
                    type_list.insert(0, preselect)
            d.type_combo = dialog.list_selector_widget(members=[
                (t, self.controller.get_title(t)) for t in type_list
            ],
                                                       preselect=preselect)
            hbox.pack_start(d.type_combo)

            d.vbox.add(hbox)

        d.show_all()
        return d