Beispiel #1
0
    def copy_relation(self, s, generate_id=False):
        if generate_id or self.destination.get_element_by_id(s.id):
            id_=self.destination._idgenerator.get_id(Relation)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id]=id_

        rt=helper.get_id(self.destination.relationTypes, s.type.id)
        if not rt:
            # The annotation type does not exist. Create it.
            rt=self.copy_relation_type(helper.get_id(self.source.relationTypes,
                                                     s.type.id))
        # Ensure that annotations exist
        members=[]
        for sa in s.members:
            # check translated_ids
            i=sa.id
            if i in self.translated_ids:
                i=self.translated_ids[i]

            a=helper.get_id(self.destination.annotations, i)
            if not a:
                a=self.copy_annotation(sa)
            members.append(a)
        el=self.destination.createRelation(
            ident=id_,
            type=rt,
            author=s.author or self.source.author,
            members=members)
        el.date=s.date or self.controller.get_timestamp()
        el.content.data=s.content.data
        self.destination.relations.append(el)
        #el.title=s.title or ''
        return el
Beispiel #2
0
    def copy_annotation(self, s, generate_id=False):
        """Create a new annotation.

        If generate_id is True, then generate a new id. Else, use the
        source id.

        Try to keep track of the occurences of its id, to fix them later on.
        """
        if generate_id or self.destination.get_element_by_id(s.id):
            id_ = self.destination._idgenerator.get_id(Annotation)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id] = id_

        # Find parent, and create it if necessary
        at = helper.get_id(self.destination.annotationTypes, s.type.id)
        if not at:
            # The annotation type does not exist. Create it.
            at = self.copy_annotation_type(
                helper.get_id(self.source.annotationTypes, s.type.id))
        el = self.destination.createAnnotation(ident=id_,
                                               type=at,
                                               author=s.author
                                               or self.source.author,
                                               fragment=s.fragment.clone())
        el.date = s.date or self.controller.get_timestamp()
        el.content.data = s.content.data
        self.destination.annotations.append(el)
        return el
Beispiel #3
0
    def copy_relation(self, s, generate_id=False):
        if generate_id or self.destination.get_element_by_id(s.id):
            id_ = self.destination._idgenerator.get_id(Relation)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id] = id_

        rt = helper.get_id(self.destination.relationTypes, s.type.id)
        if not rt:
            # The annotation type does not exist. Create it.
            rt = self.copy_relation_type(
                helper.get_id(self.source.relationTypes, s.type.id))
        # Ensure that annotations exist
        members = []
        for sa in s.members:
            # check translated_ids
            i = sa.id
            if i in self.translated_ids:
                i = self.translated_ids[i]

            a = helper.get_id(self.destination.annotations, i)
            if not a:
                a = self.copy_annotation(sa)
            members.append(a)
        el = self.destination.createRelation(ident=id_,
                                             type=rt,
                                             author=s.author
                                             or self.source.author,
                                             members=members)
        el.date = s.date or self.controller.get_timestamp()
        el.content.data = s.content.data
        self.destination.relations.append(el)
        #el.title=s.title or ''
        return el
Beispiel #4
0
    def copy_annotation(self, s, generate_id=False):
        """Create a new annotation.

        If generate_id is True, then generate a new id. Else, use the
        source id.

        Try to keep track of the occurences of its id, to fix them later on.
        """
        if generate_id or self.destination.get_element_by_id(s.id):
            id_ = self.destination._idgenerator.get_id(Annotation)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id]=id_

        # Find parent, and create it if necessary
        at=helper.get_id(self.destination.annotationTypes, s.type.id)
        if not at:
            # The annotation type does not exist. Create it.
            at=self.copy_annotation_type(helper.get_id(self.source.annotationTypes,
                                                       s.type.id))
        el=self.destination.createAnnotation(
            ident=id_,
            type=at,
            author=s.author or self.source.author,
            fragment=s.fragment.clone())
        el.date=s.date or self.controller.get_timestamp()
        el.content.data=s.content.data
        self.destination.annotations.append(el)
        return el
Beispiel #5
0
    def get_interactive_query(self):
        l=helper.get_id(self.controller.package.queries, '_interactive')
        if l:
            q=SimpleQuery()
            q.from_xml(l.content.stream)
            q.container=l
            return l, q
        else:
            # Create the query
            el=self.controller.package.createQuery(ident='_interactive')
            el.author=config.data.userid
            el.date=helper.get_timestamp()
            el.title=_("Interactive query")

            # Create a basic query
            q=SimpleQuery(sources=self.sources,
                          rvalue="element")
            q.add_condition(Condition(lhs="element/content/data",
                                      operator="contains",
                                      rhs="string:a"))

            el.content.mimetype='application/x-advene-simplequery'
            el.content.data=q.xml_repr()

            self.controller.package.queries.append(el)

            self.controller.notify('QueryCreate', query=el)
            q.container=el
            return el, q
Beispiel #6
0
    def get_interactive_query(self):
        l=helper.get_id(self.controller.package.queries, '_interactive')
        if l:
            q=SimpleQuery()
            q.from_xml(l.content.stream)
            q.container=l
            return l, q
        else:
            # Create the query
            el=self.controller.package.createQuery(ident='_interactive')
            el.author=config.data.userid
            el.date=helper.get_timestamp()
            el.title=_("Interactive query")

            # Create a basic query
            q=SimpleQuery(sources=self.sources,
                          rvalue="element")
            q.add_condition(Condition(lhs="element/content/data",
                                      operator="contains",
                                      rhs="string:a"))

            el.content.mimetype='application/x-advene-simplequery'
            el.content.data=q.xml_repr()

            self.controller.package.queries.append(el)

            self.controller.notify('QueryCreate', query=el)
            q.container=el
            return el, q
Beispiel #7
0
 def create_annotation_type (self, schema, id_, author=None, date=None, title=None,
                             representation=None, description=None, mimetype=None, color=None):
     at=helper.get_id(self.package.annotationTypes, id_)
     if at is not None:
         return at
     at=schema.createAnnotationType(ident=id_)
     at.author=author or schema.author
     at.date=date or self.timestamp
     at.title=title or at.id.title()
     at.mimetype=mimetype or 'text/plain'
     if description:
         at.setMetaData(config.data.namespace_prefix['dc'], "description", description)
     if representation:
         at.setMetaData(config.data.namespace, "representation", representation)
     try:
         # Use the specified color, or pick from the palette
         tcolor = color or next(self.package._color_palette)
         logger.warning("Set color %s", tcolor)
         # Convert from basic string to TALES for # encoded colors
         if tcolor.startswith('#'):
             tcolor = f"string:{color}"
         at.setMetaData(config.data.namespace, "color", tcolor)
     except AttributeError:
         # The package does not have a _color_palette
         pass
     at.setMetaData(config.data.namespace, 'item_color', 'here/tag_color')
     schema.annotationTypes.append(at)
     self.update_statistics('annotation-type')
     return at
Beispiel #8
0
    def save_query(self, *p):
        """Saves the query in the package.
        """
        l = self.eq.invalid_items()
        if l:
            self.log(
                _("Invalid query.\nThe following fields have an invalid value:\n%s"
                  ) % ", ".join(l))
            return True
        # Update the query
        self.eq.update_value()

        if hasattr(self.eq, 'container'):
            default_id = self.eq.container.id
            default_title = self.eq.container.title
        else:
            default_id = helper.title2id(self._label)
            default_title = self._label

        t, i = dialog.get_title_id(
            title=_("Saving the query..."),
            text=_("Give a title and identifier for saving the query"),
            element_title=default_title,
            element_id=default_id)
        if i is None:
            return True

        q = helper.get_id(self.controller.package.queries, i)
        # Overwriting an existing query
        if q:
            create = False
            self.controller.notify('EditSessionStart',
                                   element=q,
                                   immediate=True)
        else:
            create = True
            # Create the query
            q = self.controller.package.createQuery(ident=i)
            q.author = config.data.userid
            q.date = helper.get_timestamp()
            self.controller.package.queries.append(q)

        q.title = t
        q.content.mimetype = 'application/x-advene-simplequery'

        # Store the query itself in the _interactive query
        q.content.data = self.eq.model.xml_repr()
        if create:
            self.controller.notify('QueryCreate', query=q)
        else:
            self.controller.notify('QueryEditEnd', query=q)
            self.controller.notify('EditSessionEnd', element=q)
        return q
Beispiel #9
0
 def create_schema (self, id_, author=None, date=None, title=None, description=None):
     s=helper.get_id(self.package.schemas, id_)
     if s is not None:
         return s
     schema=self.package.createSchema(ident=id_)
     schema.author=author or self.author
     schema.date=date or self.timestamp
     schema.title=title or "Generated schema"
     if description:
         schema.setMetaData(config.data.namespace_prefix['dc'], "description", description)
     self.package.schemas.append(schema)
     self.update_statistics('schema')
     return schema
Beispiel #10
0
    def copy_relation_type(self, s, generate_id=False):
        if generate_id or self.destination.get_element_by_id(s.id):
            id_=self.destination._idgenerator.get_id(RelationType)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id]=id_

        # Find parent, and create it if necessary
        sch=helper.get_id(self.destination.schemas, s.schema.id)
        if not sch:
            # Create it
            sch=helper.get_id(self.source.schemas, s.schema.id)
            sch=self.copy_schema(sch)
        el=sch.createRelationType(ident=id_)
        el.author=s.author or self.source.author
        el.date=s.date or helper.get_timestamp()
        el.title=s.title or id_
        el.mimetype=s.mimetype
        sch.relationTypes.append(el)
        for (namespace, name, value) in s.listMetaData():
            el.setMetaData(namespace, name, value)
        # Handle membertypes, ensure that annotation types are defined
        for m in s.hackedMemberTypes:
            if m == '':
                # Any type, no import necessary
                continue
            if not m.startswith('#'):
                logger.error("Cannot handle non-fragment membertypes %s", m)
                continue
            at=helper.get_id(self.destination.annotationTypes, m[1:])
            if not at:
                # The annotation type does not exist. Create it.
                at=helper.get_id(self.source.annotationTypes, m[1:])
                at=self.copy_annotation_type(at)
        # Now we can set member types
        el.setHackedMemberTypes(s.getHackedMemberTypes())
        return el
Beispiel #11
0
    def copy_relation_type(self, s, generate_id=False):
        if generate_id or self.destination.get_element_by_id(s.id):
            id_ = self.destination._idgenerator.get_id(RelationType)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id] = id_

        # Find parent, and create it if necessary
        sch = helper.get_id(self.destination.schemas, s.schema.id)
        if not sch:
            # Create it
            sch = helper.get_id(self.source.schemas, s.schema.id)
            sch = self.copy_schema(sch)
        el = sch.createRelationType(ident=id_)
        el.author = s.author or self.source.author
        el.date = s.date or helper.get_timestamp()
        el.title = s.title or id_
        el.mimetype = s.mimetype
        sch.relationTypes.append(el)
        for (namespace, name, value) in s.listMetaData():
            el.setMetaData(namespace, name, value)
        # Handle membertypes, ensure that annotation types are defined
        for m in s.hackedMemberTypes:
            if m == '':
                # Any type, no import necessary
                continue
            if not m.startswith('#'):
                logger.error("Cannot handle non-fragment membertypes %s", m)
                continue
            at = helper.get_id(self.destination.annotationTypes, m[1:])
            if not at:
                # The annotation type does not exist. Create it.
                at = helper.get_id(self.source.annotationTypes, m[1:])
                at = self.copy_annotation_type(at)
        # Now we can set member types
        el.setHackedMemberTypes(s.getHackedMemberTypes())
        return el
Beispiel #12
0
    def copy_annotation_type(self, s, generate_id=False):
        if generate_id or self.destination.get_element_by_id(s.id):
            id_=self.destination._idgenerator.get_id(AnnotationType)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id]=id_

        # Find parent, and create it if necessary
        sch=helper.get_id(self.destination.schemas, s.schema.id)
        if not sch:
            # Create it
            sch=helper.get_id(self.source.schemas, s.schema.id)
            sch=self.copy_schema(sch)
        el=sch.createAnnotationType(ident=id_)
        el.author=s.author or self.source.author
        el.date=s.date or self.controller.get_timestamp()
        el.title=s.title or id_
        el.mimetype=s.mimetype
        for n in ('color', 'item_color'):
            el.setMetaData(config.data.namespace, n, (s.getMetaData(config.data.namespace, n) or ''))
        sch.annotationTypes.append(el)
        return el
Beispiel #13
0
    def copy_annotation_type(self, s, generate_id=False):
        if generate_id or self.destination.get_element_by_id(s.id):
            id_ = self.destination._idgenerator.get_id(AnnotationType)
        else:
            id_ = s.id
        self.destination._idgenerator.add(id_)
        self.translated_ids[s.id] = id_

        # Find parent, and create it if necessary
        sch = helper.get_id(self.destination.schemas, s.schema.id)
        if not sch:
            # Create it
            sch = helper.get_id(self.source.schemas, s.schema.id)
            sch = self.copy_schema(sch)
        el = sch.createAnnotationType(ident=id_)
        el.author = s.author or self.source.author
        el.date = s.date or helper.get_timestamp()
        el.title = s.title or id_
        el.mimetype = s.mimetype
        for (namespace, name, value) in s.listMetaData():
            el.setMetaData(namespace, name, value)
        sch.annotationTypes.append(el)
        return el
Beispiel #14
0
    def save_query(self, *p):
        """Saves the query in the package.
        """
        l=self.eq.invalid_items()
        if l:
            self.log(_("Invalid query.\nThe following fields have an invalid value:\n%s")
                     % ", ".join(l))
            return True
        # Update the query
        self.eq.update_value()

        if hasattr(self.eq, 'container'):
            default_id=self.eq.container.id
            default_title=self.eq.container.title
        else:
            default_id=helper.title2id(self._label)
            default_title=self._label


        t, i = dialog.get_title_id(title=_("Saving the query..."),
                                   text=_("Give a title and identifier for saving the query"),
                                   element_title=default_title,
                                   element_id=default_id)
        if i is None:
            return True

        q=helper.get_id(self.controller.package.queries, i)
        # Overwriting an existing query
        if q:
            create=False
            self.controller.notify('EditSessionStart', element=q, immediate=True)
        else:
            create=True
            # Create the query
            q=self.controller.package.createQuery(ident=i)
            q.author=config.data.userid
            q.date=helper.get_timestamp()
            self.controller.package.queries.append(q)

        q.title=t
        q.content.mimetype='application/x-advene-simplequery'

        # Store the query itself in the _interactive query
        q.content.data = self.eq.model.xml_repr()
        if create:
            self.controller.notify('QueryCreate', query=q)
        else:
            self.controller.notify('QueryEditEnd', query=q)
            self.controller.notify('EditSessionEnd', element=q)
        return q
Beispiel #15
0
 def update_members(self, s, d):
     """Update the relation members.
     """
     sm=[ a.id for a in s.members ]
     d.members.clear()
     for i in sm:
         # Handle translated ids
         if i in self.translated_ids:
             i=self.translated_ids[i]
         a=helper.get_id(self.destination.annotations, i)
         if a is None:
             raise "Error: missing annotation %s" % i
         d.members.append(a)
     return d
Beispiel #16
0
 def update_members(self, s, d):
     """Update the relation members.
     """
     sm = [a.id for a in s.members]
     d.members.clear()
     for i in sm:
         # Handle translated ids
         if i in self.translated_ids:
             i = self.translated_ids[i]
         a = helper.get_id(self.destination.annotations, i)
         if a is None:
             raise "Error: missing annotation %s" % i
         d.members.append(a)
     return d
Beispiel #17
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
Beispiel #18
0
    def save_query(self, *p):
        """Saves the query in the package.
        """
        if hasattr(self.query, 'container'):
            default_id = self.query.container.id
            default_title = self.query.container.title
        else:
            default_id = helper.title2id(self._label)
            default_title = self._label

        t, i = dialog.get_title_id(
            title=_("Saving the query..."),
            text=_("Give a title and identifier for saving the query"),
            element_title=default_title,
            element_id=default_id)
        if i is None:
            return True

        q = helper.get_id(self.controller.package.queries, i)
        # Overwriting an existing query
        if q:
            create = False
        else:
            create = True
            # Create the query
            q = self.controller.package.createQuery(ident=i)
            q.author = config.data.userid
            q.date = helper.get_timestamp()
            self.controller.package.queries.append(q)

        q.title = t
        if isinstance(self.query, SimpleQuery):
            q.content.mimetype = 'application/x-advene-simplequery'
        elif isinstance(self.query, Quicksearch):
            q.content.mimetype = 'application/x-advene-quicksearch'
        q.content.data = self.query.xml_repr()
        if create:
            self.controller.notify('QueryCreate', query=q)
        else:
            self.controller.notify('QueryEditEnd', query=q)
        return q
Beispiel #19
0
    def save_query(self, *p):
        """Saves the query in the package.
        """
        if hasattr(self.query, 'container'):
            default_id=self.query.container.id
            default_title=self.query.container.title
        else:
            default_id=helper.title2id(self._label)
            default_title=self._label

        t, i = dialog.get_title_id(title=_("Saving the query..."),
                                   text=_("Give a title and identifier for saving the query"),
                                   element_title=default_title,
                                   element_id=default_id)
        if i is None:
            return True

        q=helper.get_id(self.controller.package.queries, i)
        # Overwriting an existing query
        if q:
            create=False
        else:
            create=True
            # Create the query
            q=self.controller.package.createQuery(ident=i)
            q.author=config.data.userid
            q.date=helper.get_timestamp()
            self.controller.package.queries.append(q)

        q.title=t
        if isinstance(self.query, SimpleQuery):
            q.content.mimetype='application/x-advene-simplequery'
        elif isinstance(self.query, Quicksearch):
            q.content.mimetype='application/x-advene-quicksearch'
        q.content.data = self.query.xml_repr()
        if create:
            self.controller.notify('QueryCreate', query=q)
        else:
            self.controller.notify('QueryEditEnd', query=q)
        return q
Beispiel #20
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
Beispiel #21
0
    def drag_received(self, widget, context, x, y, selection, targetType, time):
        def create_and_open_view(sources):
            v=self.controller.create_static_view(elements=sources)
            p=get_edit_popup(v, controller=self.controller)
            self.add_view(p, name=_("Edit %s") % self.controller.get_title(v, max_size=40))
            # FIXME: put focus on edit window
            return True

        def edit_annotation(a):
            p=get_edit_popup(a, controller=self.controller)
            self.add_view(p, name=_("Edit %s") % self.controller.get_title(a, max_size=40))
            return True

        def edit_selection(sources):
            """Edit the selected elements in an edit accumulator.
            """
            v=self.controller.gui.open_adhoc_view('editaccumulator',
                                                  destination=self.location)
            if v is not None:
                for a in sources:
                    v.edit(a)
            return True

        if targetType == config.data.target_type['adhoc-view']:
            data=decode_drop_parameters(selection.data)
            label=None
            view=None
            if 'id' in data:
                # Saved parametered view. Get the view itself.
                ident=data['id']
                v=helper.get_id(self.controller.package.views, ident)
                # Get the view_id
                if v is None:
                    self.log(_("Cannot find the view %s") % ident)
                    return True
                name=v
                label=v.title
                view=self.controller.gui.open_adhoc_view(name, label=label, destination=None)
                if view is not None:
                    self.add_view(view, name=view.view_name)
            elif 'name' in data:
                name=data['name']
                if name == 'comment':
                    saved=[ v
                            for v in self.controller.package.views
                            if helper.get_view_type(v) == 'static'
                            and v.matchFilter['class'] == 'package'
                            and not v.id.startswith('_') ]
                else:
                    saved=[ v
                            for v in self.controller.package.views
                            if v.content.mimetype == 'application/x-advene-adhoc-view'
                            and ET.parse(v.content.stream).getroot().attrib['id'] == name ]

                if name == 'transcription':
                    menu=gtk.Menu()
                    i=gtk.MenuItem(_("Open a new transcription for..."))
                    menu.append(i)
                    sm=gtk.Menu()
                    i.set_submenu(sm)
                    for at in self.controller.package.annotationTypes:
                        title=self.controller.get_title(at, max_size=40)
                        i=gtk.MenuItem(title, use_underline=False)
                        i.connect('activate', lambda i, s, t: self.controller.gui.open_adhoc_view(name, source=s, label=t, destination=self.location), "here/annotationTypes/%s/annotations/sorted" % at.id, title)
                        sm.append(i)
                elif saved:
                    menu=gtk.Menu()
                    if name == 'comment':
                        i=gtk.MenuItem(_("Create a new comment view"))
                    else:
                        i=gtk.MenuItem(_("Open a new view"))
                    i.connect('activate', lambda i: self.controller.gui.open_adhoc_view(name, label=label, destination=self.location))
                    menu.append(i)
                else:
                    menu=None

                if menu is not None:
                    if saved:
                        i=gtk.MenuItem(_("Open a saved view"))
                        menu.append(i)
                        sm=gtk.Menu()
                        i.set_submenu(sm)
                        for v in saved:
                            i=gtk.MenuItem(v.title, use_underline=False)
                            if name == 'comment':
                                i.connect('activate', lambda i, vv: self.controller.gui.open_adhoc_view('edit', element=vv, destination=self.location), v)
                            else:
                                i.connect('activate', lambda i, vv: self.controller.gui.open_adhoc_view(vv, label=vv.title, destination=self.location), v)
                            sm.append(i)
                    menu.show_all()
                    menu.popup(None, None, None, 0, gtk.get_current_event_time())
                else:
                    view=self.controller.gui.open_adhoc_view(name, label=label, destination=None)
                    if view is not None:
                        self.add_view(view, name=view.view_name)
            else:
                # Bug
                self.log("Cannot happen")
                return True


            if 'master' in data and view is not None:
                # A master view has been specified. Connect it to
                # the created view.
                master=self.controller.gui.get_adhoc_view_instance_from_id(data['master'])
                view.set_master_view(master)
            return True
        elif targetType == config.data.target_type['adhoc-view-instance']:
            v=self.controller.gui.get_adhoc_view_instance_from_id(selection.data)
            if v is not None:
                wid=v.widget
                self.add_view(v, name=v._label)
                if hasattr(v, 'reparent_done'):
                    v.reparent_done()
            else:
                print "Cannot find view ", selection.data
            return True
        elif targetType == config.data.target_type['view']:
            v=self.controller.package.views.get(unicode(selection.data, 'utf8'))
            if helper.get_view_type(v) in ('static', 'dynamic'):
                # Edit the view.
                self.controller.gui.open_adhoc_view('edit', element=v, destination=self.location)
            else:
                print "Unhandled case in viewbook: targetType=view"
            return True
        elif targetType == config.data.target_type['query']:
            v=self.controller.package.queries.get(unicode(selection.data, 'utf8'))
            if v is not None:
                self.controller.gui.open_adhoc_view('edit', element=v, destination=self.location)
            return True
        elif targetType == config.data.target_type['schema']:
            v=self.controller.package.schemas.get(unicode(selection.data, 'utf8'))
            if v is not None:
                self.controller.gui.open_adhoc_view('edit', element=v, destination=self.location)
            return True
        elif targetType == config.data.target_type['relation']:
            v=self.controller.package.relations.get(unicode(selection.data, 'utf8'))
            if v is not None:
                self.controller.gui.open_adhoc_view('edit', element=v, destination=self.location)
            return True
        elif targetType == config.data.target_type['annotation-type']:
            at=self.controller.package.annotationTypes.get(unicode(selection.data, 'utf8'))
            # Propose a menu to open various views for the annotation-type:
            menu=gtk.Menu()
            title=self.controller.get_title(at, max_size=40)
            i=gtk.MenuItem(_("Use annotation-type %s :") % title, use_underline=False)
            menu.append(i)
            for label, action in (
                (_("to edit it"), lambda i :self.controller.gui.open_adhoc_view('edit', element=at, destination=self.location)),
                (_("to create a new static view"), lambda i: create_and_open_view([ at ])),
                (_("as a transcription"), lambda i: self.controller.gui.open_adhoc_view('transcription', source='here/annotationTypes/%s/annotations/sorted' % at.id, destination=self.location, label=title)),
                (_("in a timeline"), lambda i: self.controller.gui.open_adhoc_view('timeline', elements=at.annotations, annotationtypes=[ at ], destination=self.location, label=title)),
                (_("as a montage"), lambda i: self.controller.gui.open_adhoc_view('montage', elements=at.annotations, destination=self.location, label=title)),
                (_("in a table"), lambda i: self.controller.gui.open_adhoc_view('table', elements=at.annotations, destination=self.location, label=title)),
                (_("in a query"), lambda i: self.controller.gui.open_adhoc_view('interactivequery', here=at, destination=self.location, label=_("Query %s") % title)),
                (_("in the TALES browser"), lambda i: self.controller.gui.open_adhoc_view('browser', element=at, destination=self.location, label=_("Browsing %s") % title)),
                ):
                i=gtk.MenuItem(u"    " + label, use_underline=False)
                i.connect('activate', action)
                menu.append(i)
            menu.show_all()
            menu.popup(None, None, None, 0, gtk.get_current_event_time())
            return True
        elif targetType == config.data.target_type['annotation']:
            sources=[ self.controller.package.annotations.get(uri) for uri in unicode(selection.data, 'utf8').split('\n') ]
            # Propose a menu to open various views for the annotation:
            menu=gtk.Menu()

            if len(sources) == 1:
                a=sources[0]
                title=self.controller.get_title(a, max_size=40)
                i=gtk.MenuItem(_("Use annotation %s :") % title, use_underline=False)
                menu.append(i)
                for label, action in (
                    (_("to edit it"), lambda i: edit_annotation(a)),
                    (_("to create a new static view"), lambda i: create_and_open_view(sources)),
                    (_("in a query"), lambda i: self.controller.gui.open_adhoc_view('interactivequery', here=a, destination=self.location, label=_("Query %s") % title)),
                    (_("in the TALES browser"), lambda i: self.controller.gui.open_adhoc_view('browser', element=a, destination=self.location, label=_("Browse %s") % title)),
                    (_("to display its contents"), lambda i: self.controller.gui.open_adhoc_view('annotationdisplay', annotation=a, destination=self.location, label=_("%s") % title)) ,
                    (_("as a bookmark"), lambda i: self.controller.gui.open_adhoc_view('activebookmarks', elements=[ a.fragment.begin ], destination=self.location)),
                    ):
                    i=gtk.MenuItem(u"    " + label, use_underline=False)
                    i.connect('activate', action)
                    menu.append(i)

                def apply_query(m, q):
                    ctx=self.controller.build_context(here=a)
                    res, qexpr=self.controller.evaluate_query(q, context=ctx)
                    self.controller.gui.open_adhoc_view('interactiveresult', query=q, result=res, destination=self.location)
                    return True

                if self.controller.package.queries:
                    sm=gtk.Menu()
                    for q in self.controller.package.queries:
                        i=gtk.MenuItem(self.controller.get_title(q, max_size=40), use_underline=False)
                        i.connect('activate', apply_query, q)
                        sm.append(i)
                    i=gtk.MenuItem(u"    " + _("as the context for the query..."), use_underline=False)
                    i.set_submenu(sm)
                    menu.append(i)
            else:
                title=_("Set of annotations")
                i=gtk.MenuItem(_("Use annotations:"), use_underline=False)
                menu.append(i)
                for label, action in (
                    (_("to edit them"), lambda i: edit_selection(sources)),
                    (_("in a table"), lambda i: self.controller.gui.open_adhoc_view('table', elements=sources)),
                    (_("to create a new static view"), lambda i: create_and_open_view(sources)),
                    (_("as bookmarks"), lambda i: self.controller.gui.open_adhoc_view('activebookmarks', elements=[ a.fragment.begin for a in sources ], destination=self.location)),
                    ):
                    i=gtk.MenuItem(u"    " + label, use_underline=False)
                    i.connect('activate', action)
                    menu.append(i)
            menu.show_all()
            menu.popup(None, None, None, 0, gtk.get_current_event_time())
            return True
        elif targetType == config.data.target_type['timestamp']:
            data=decode_drop_parameters(selection.data)
            v=self.controller.gui.open_adhoc_view('activebookmarks', destination=self.location)
            v.append(long(data['timestamp']), comment=data.get('comment', ''))
            return True
        else:
            print "Unknown drag target received ", targetType
        return False
Beispiel #22
0
    def drag_received(self, widget, context, x, y, selection, targetType,
                      time):
        def create_and_open_view(sources):
            v = self.controller.create_static_view(elements=sources)
            p = get_edit_popup(v, controller=self.controller)
            self.add_view(p,
                          name=_("Edit %s") %
                          self.controller.get_title(v, max_size=40))
            # FIXME: put focus on edit window
            return True

        def edit_annotation(a):
            p = get_edit_popup(a, controller=self.controller)
            self.add_view(p,
                          name=_("Edit %s") %
                          self.controller.get_title(a, max_size=40))
            return True

        def edit_selection(sources):
            """Edit the selected elements in an edit accumulator.
            """
            v = self.controller.gui.open_adhoc_view('editaccumulator',
                                                    destination=self.location)
            if v is not None:
                for a in sources:
                    v.edit(a)
            return True

        if targetType == config.data.target_type['adhoc-view']:
            data = decode_drop_parameters(selection.data)
            label = None
            view = None
            if 'id' in data:
                # Saved parametered view. Get the view itself.
                ident = data['id']
                v = helper.get_id(self.controller.package.views, ident)
                # Get the view_id
                if v is None:
                    self.log(_("Cannot find the view %s") % ident)
                    return True
                name = v
                label = v.title
                view = self.controller.gui.open_adhoc_view(name,
                                                           label=label,
                                                           destination=None)
                if view is not None:
                    self.add_view(view, name=view.view_name)
            elif 'name' in data:
                name = data['name']
                if name == 'comment':
                    saved = [
                        v for v in self.controller.package.views
                        if helper.get_view_type(v) == 'static'
                        and v.matchFilter['class'] == 'package'
                        and not v.id.startswith('_')
                    ]
                else:
                    saved = [
                        v for v in self.controller.package.views
                        if v.content.mimetype ==
                        'application/x-advene-adhoc-view' and ET.parse(
                            v.content.stream).getroot().attrib['id'] == name
                    ]

                if name == 'transcription':
                    menu = gtk.Menu()
                    i = gtk.MenuItem(_("Open a new transcription for..."))
                    menu.append(i)
                    sm = gtk.Menu()
                    i.set_submenu(sm)
                    for at in self.controller.package.annotationTypes:
                        title = self.controller.get_title(at, max_size=40)
                        i = gtk.MenuItem(title, use_underline=False)
                        i.connect(
                            'activate', lambda i, s, t: self.controller.gui.
                            open_adhoc_view(name,
                                            source=s,
                                            label=t,
                                            destination=self.location),
                            "here/annotationTypes/%s/annotations/sorted" %
                            at.id, title)
                        sm.append(i)
                elif saved:
                    menu = gtk.Menu()
                    if name == 'comment':
                        i = gtk.MenuItem(_("Create a new comment view"))
                    else:
                        i = gtk.MenuItem(_("Open a new view"))
                    i.connect(
                        'activate',
                        lambda i: self.controller.gui.open_adhoc_view(
                            name, label=label, destination=self.location))
                    menu.append(i)
                else:
                    menu = None

                if menu is not None:
                    if saved:
                        i = gtk.MenuItem(_("Open a saved view"))
                        menu.append(i)
                        sm = gtk.Menu()
                        i.set_submenu(sm)
                        for v in saved:
                            i = gtk.MenuItem(v.title, use_underline=False)
                            if name == 'comment':
                                i.connect(
                                    'activate',
                                    lambda i, vv: self.controller.gui.
                                    open_adhoc_view('edit',
                                                    element=vv,
                                                    destination=self.location),
                                    v)
                            else:
                                i.connect(
                                    'activate',
                                    lambda i, vv: self.controller.gui.
                                    open_adhoc_view(vv,
                                                    label=vv.title,
                                                    destination=self.location),
                                    v)
                            sm.append(i)
                    menu.show_all()
                    menu.popup(None, None, None, 0,
                               gtk.get_current_event_time())
                else:
                    view = self.controller.gui.open_adhoc_view(
                        name, label=label, destination=None)
                    if view is not None:
                        self.add_view(view, name=view.view_name)
            else:
                # Bug
                self.log("Cannot happen")
                return True

            if 'master' in data and view is not None:
                # A master view has been specified. Connect it to
                # the created view.
                master = self.controller.gui.get_adhoc_view_instance_from_id(
                    data['master'])
                view.set_master_view(master)
            return True
        elif targetType == config.data.target_type['adhoc-view-instance']:
            v = self.controller.gui.get_adhoc_view_instance_from_id(
                selection.data)
            if v is not None:
                wid = v.widget
                self.add_view(v, name=v._label)
                if hasattr(v, 'reparent_done'):
                    v.reparent_done()
            else:
                print "Cannot find view ", selection.data
            return True
        elif targetType == config.data.target_type['view']:
            v = self.controller.package.views.get(
                unicode(selection.data, 'utf8'))
            if helper.get_view_type(v) in ('static', 'dynamic'):
                # Edit the view.
                self.controller.gui.open_adhoc_view('edit',
                                                    element=v,
                                                    destination=self.location)
            else:
                print "Unhandled case in viewbook: targetType=view"
            return True
        elif targetType == config.data.target_type['query']:
            v = self.controller.package.queries.get(
                unicode(selection.data, 'utf8'))
            if v is not None:
                self.controller.gui.open_adhoc_view('edit',
                                                    element=v,
                                                    destination=self.location)
            return True
        elif targetType == config.data.target_type['schema']:
            v = self.controller.package.schemas.get(
                unicode(selection.data, 'utf8'))
            if v is not None:
                self.controller.gui.open_adhoc_view('edit',
                                                    element=v,
                                                    destination=self.location)
            return True
        elif targetType == config.data.target_type['relation']:
            v = self.controller.package.relations.get(
                unicode(selection.data, 'utf8'))
            if v is not None:
                self.controller.gui.open_adhoc_view('edit',
                                                    element=v,
                                                    destination=self.location)
            return True
        elif targetType == config.data.target_type['annotation-type']:
            at = self.controller.package.annotationTypes.get(
                unicode(selection.data, 'utf8'))
            # Propose a menu to open various views for the annotation-type:
            menu = gtk.Menu()
            title = self.controller.get_title(at, max_size=40)
            i = gtk.MenuItem(_("Use annotation-type %s :") % title,
                             use_underline=False)
            menu.append(i)
            for label, action in (
                (_("to edit it"),
                 lambda i: self.controller.gui.open_adhoc_view(
                     'edit', element=at, destination=self.location)),
                (_("to create a new static view"),
                 lambda i: create_and_open_view([at])),
                (_("as a transcription"),
                 lambda i: self.controller.gui.open_adhoc_view(
                     'transcription',
                     source='here/annotationTypes/%s/annotations/sorted' % at.
                     id,
                     destination=self.location,
                     label=title)),
                (_("in a timeline"), lambda i: self.controller.gui.
                 open_adhoc_view('timeline',
                                 elements=at.annotations,
                                 annotationtypes=[at],
                                 destination=self.location,
                                 label=title)),
                (_("as a montage"), lambda i: self.controller.gui.
                 open_adhoc_view('montage',
                                 elements=at.annotations,
                                 destination=self.location,
                                 label=title)),
                (_("in a table"), lambda i: self.controller.gui.
                 open_adhoc_view('table',
                                 elements=at.annotations,
                                 destination=self.location,
                                 label=title)),
                (_("in a query"), lambda i: self.controller.gui.
                 open_adhoc_view('interactivequery',
                                 here=at,
                                 destination=self.location,
                                 label=_("Query %s") % title)),
                (_("in the TALES browser"), lambda i: self.controller.gui.
                 open_adhoc_view('browser',
                                 element=at,
                                 destination=self.location,
                                 label=_("Browsing %s") % title)),
            ):
                i = gtk.MenuItem(u"    " + label, use_underline=False)
                i.connect('activate', action)
                menu.append(i)
            menu.show_all()
            menu.popup(None, None, None, 0, gtk.get_current_event_time())
            return True
        elif targetType == config.data.target_type['annotation']:
            sources = [
                self.controller.package.annotations.get(uri)
                for uri in unicode(selection.data, 'utf8').split('\n')
            ]
            # Propose a menu to open various views for the annotation:
            menu = gtk.Menu()

            if len(sources) == 1:
                a = sources[0]
                title = self.controller.get_title(a, max_size=40)
                i = gtk.MenuItem(_("Use annotation %s :") % title,
                                 use_underline=False)
                menu.append(i)
                for label, action in (
                    (_("to edit it"), lambda i: edit_annotation(a)),
                    (_("to create a new static view"),
                     lambda i: create_and_open_view(sources)),
                    (_("in a query"), lambda i: self.controller.gui.
                     open_adhoc_view('interactivequery',
                                     here=a,
                                     destination=self.location,
                                     label=_("Query %s") % title)),
                    (_("in the TALES browser"), lambda i: self.controller.gui.
                     open_adhoc_view('browser',
                                     element=a,
                                     destination=self.location,
                                     label=_("Browse %s") % title)),
                    (_("to display its contents"), lambda i: self.controller.
                     gui.open_adhoc_view('annotationdisplay',
                                         annotation=a,
                                         destination=self.location,
                                         label=_("%s") % title)),
                    (_("as a bookmark"), lambda i: self.controller.gui.
                     open_adhoc_view('activebookmarks',
                                     elements=[a.fragment.begin],
                                     destination=self.location)),
                ):
                    i = gtk.MenuItem(u"    " + label, use_underline=False)
                    i.connect('activate', action)
                    menu.append(i)

                def apply_query(m, q):
                    ctx = self.controller.build_context(here=a)
                    res, qexpr = self.controller.evaluate_query(q, context=ctx)
                    self.controller.gui.open_adhoc_view(
                        'interactiveresult',
                        query=q,
                        result=res,
                        destination=self.location)
                    return True

                if self.controller.package.queries:
                    sm = gtk.Menu()
                    for q in self.controller.package.queries:
                        i = gtk.MenuItem(self.controller.get_title(
                            q, max_size=40),
                                         use_underline=False)
                        i.connect('activate', apply_query, q)
                        sm.append(i)
                    i = gtk.MenuItem(u"    " +
                                     _("as the context for the query..."),
                                     use_underline=False)
                    i.set_submenu(sm)
                    menu.append(i)
            else:
                title = _("Set of annotations")
                i = gtk.MenuItem(_("Use annotations:"), use_underline=False)
                menu.append(i)
                for label, action in (
                    (_("to edit them"), lambda i: edit_selection(sources)),
                    (_("in a table"), lambda i: self.controller.gui.
                     open_adhoc_view('table', elements=sources)),
                    (_("to create a new static view"),
                     lambda i: create_and_open_view(sources)),
                    (_("as bookmarks"),
                     lambda i: self.controller.gui.open_adhoc_view(
                         'activebookmarks',
                         elements=[a.fragment.begin for a in sources],
                         destination=self.location)),
                ):
                    i = gtk.MenuItem(u"    " + label, use_underline=False)
                    i.connect('activate', action)
                    menu.append(i)
            menu.show_all()
            menu.popup(None, None, None, 0, gtk.get_current_event_time())
            return True
        elif targetType == config.data.target_type['timestamp']:
            data = decode_drop_parameters(selection.data)
            v = self.controller.gui.open_adhoc_view('activebookmarks',
                                                    destination=self.location)
            v.append(long(data['timestamp']), comment=data.get('comment', ''))
            return True
        else:
            print "Unknown drag target received ", targetType
        return False