예제 #1
0
 def statistics_formatted(self):
     """Return a string representation of the statistics."""
     res=[]
     kl=list(self.statistics.keys())
     kl.sort()
     for k in kl:
         v=self.statistics[k]
         res.append("\t%s" % helper.format_element_name(k, v))
     return "\n".join(res)
예제 #2
0
    def build_widget(self):
        el = self.node.element
        vbox = Gtk.VBox()

        info = Gtk.TextView()
        info.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)

        def set_text(widget, t):
            b = widget.get_buffer()
            b.delete(*b.get_bounds())
            b.set_text(t)
            b.set_modified(False)
            return True

        info.set_text = set_text.__get__(info)
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        if isinstance(el, Package):
            info.set_text(
                _("""Package %(title)s:
%(schema)s
%(annotation)s in %(annotation_type)s
%(relation)s in %(relation_type)s
%(query)s
%(view)s

Description:
%(description)s

Annotation statistics:
%(statistics)s
""") % {
                    'title':
                    el.title,
                    'schema':
                    helper.format_element_name('schema', len(el.schemas)),
                    'annotation':
                    helper.format_element_name('annotation', len(
                        el.annotations)),
                    'annotation_type':
                    helper.format_element_name('annotation_type',
                                               len(el.annotationTypes)),
                    'relation':
                    helper.format_element_name('relation', len(el.relations)),
                    'relation_type':
                    helper.format_element_name('relation_type',
                                               len(el.relationTypes)),
                    'query':
                    helper.format_element_name('query', len(el.queries)),
                    'view':
                    helper.format_element_name('view', len(el.views)),
                    'description':
                    el.getMetaData(config.data.namespace_prefix['dc'],
                                   'description'),
                    'statistics':
                    helper.get_annotations_statistics(el.annotations)
                })
        elif isinstance(el, AnnotationType):
            info.set_text(
                _("""%(type)s %(title)s\n%(statistics)s""") % ({
                    "type":
                    helper.get_type(el),
                    "title":
                    self.controller.get_title(el),
                    "statistics":
                    helper.get_annotations_statistics(el.annotations)
                }))
        elif isinstance(el, Schema):
            info.set_text(
                _("""%(type)s %(title)s\n%(statistics)s""") %
                ({
                    "type": helper.get_type(el),
                    "title": self.controller.get_title(el),
                    "statistics": helper.get_schema_statistics(el)
                }))
        else:
            info.set_text(
                _("""%(type)s %(title)s""") %
                ({
                    "type": helper.get_type(el),
                    "title": self.controller.get_title(el)
                }))
        sw.add(info)

        edit_button = Gtk.Button(_("Edit"))
        edit_button.connect('clicked',
                            lambda w: self.controller.gui.edit_element(el))

        frame = Gtk.Expander.new(_("Metadata"))
        frame.set_expanded(False)
        self.view = EditWidget(self.node.set_config, self.node.get_config)
        for p in self.node.list_keys():
            self.view.add_entry(p, p, "")
        frame.add(self.view)

        vbox.add(sw)
        if not isinstance(el, (VirtualNode, AbstractBundle)):
            vbox.pack_start(edit_button, False, False, 0)
            vbox.pack_start(frame, False, False, 0)
        vbox.show_all()
        return vbox
예제 #3
0
파일: __init__.py 프로젝트: oaubert/advene
def contextual_drag_begin(widget, context, element, controller):
    if callable(element):
        element=element()
    context._element=element

    if hasattr(widget, '_drag_begin'):
        if widget._drag_begin(widget, context):
            return False

    w=Gtk.Window(Gtk.WindowType.POPUP)
    w.set_decorated(False)
    w.get_style_context().add_class('advene_drag_icon')

    v=Gtk.VBox()
    v.get_style_context().add_class('advene_drag_icon')

    def get_coloured_label(t, color=None):
        l=Gtk.Label()
        #l.set_ellipsize(Pango.EllipsizeMode.END)
        if color is None:
            color='white'
        l.set_markup("""<span background="%s" foreground="black">%s</span>""" % (color, t.replace('<', '&lt;')))
        return l

    if isinstance(element, int):
        begin = image_new_from_pixbuf(png_to_pixbuf(controller.get_snapshot(position=element, precision=config.data.preferences['bookmark-snapshot-precision']), width=config.data.preferences['drag-snapshot-width']))
        begin.get_style_context().add_class('advene_drag_icon')

        l=Gtk.Label()
        l.set_text(helper.format_time(element))
        l.get_style_context().add_class('advene_drag_icon')

        v.pack_start(begin, False, True, 0)
        v.pack_start(l, False, True, 0)
        w.set_size_request(int(1.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, Annotation):
        # Pictures HBox
        h=Gtk.HBox()
        h.get_style_context().add_class('advene_drag_icon')
        begin = image_new_from_pixbuf(png_to_pixbuf(controller.get_snapshot(annotation=element), width=config.data.preferences['drag-snapshot-width']))
        begin.get_style_context().add_class('advene_drag_icon')
        h.pack_start(begin, False, True, 0)
        # Padding
        h.pack_start(Gtk.HBox(), True, True, 0)
        end = image_new_from_pixbuf(png_to_pixbuf(controller.get_snapshot(annotation=element, position=element.fragment.end), width=config.data.preferences['drag-snapshot-width']))
        end.get_style_context().add_class('advene_drag_icon')
        h.pack_start(end, False, True, 0)
        v.pack_start(h, False, True, 0)

        l=get_coloured_label(controller.get_title(element), controller.get_element_color(element))
        l.get_style_context().add_class('advene_drag_icon')
        v.pack_start(l, False, True, 0)
        w.get_style_context().add_class('advene_drag_icon')
        w.set_size_request(int(2.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, AnnotationType):
        l=get_coloured_label(_("Annotation Type %(title)s:\n%(count)s") % {
                'title': controller.get_title(element),
                'count': helper.format_element_name('annotation', len(element.annotations)),
                }, controller.get_element_color(element))
        v.pack_start(l, False, True, 0)
    elif isinstance(element, RelationType):
        l=get_coloured_label(_("Relation Type %(title)s:\n%(count)s") % {
                'title': controller.get_title(element),
                'count': helper.format_element_name('relation', len(element.relations)),
                }, controller.get_element_color(element))
        v.pack_start(l, False, True, 0)
    else:
        l=get_coloured_label("%s %s" % (helper.get_type(element),
                                        controller.get_title(element)),
                             controller.get_element_color(element))
        v.pack_start(l, False, True, 0)

    w.add(v)
    w.show_all()
    widget._icon=w
    Gtk.drag_set_icon_widget(context, w, 0, 0)
    return True
예제 #4
0
파일: __init__.py 프로젝트: oaubert/advene2
def contextual_drag_begin(widget, context, element, controller):
    if callable(element):
        element=element()
    context._element=element

    if hasattr(widget, '_drag_begin'):
        if widget._drag_begin(widget, context):
            return False

    # set_icon_widget does not work on native Gtk on MacOS X
    if config.data.os == 'darwin' and not os.environ.get('DISPLAY'):
        return False
    # set_icon_widget is broken ATM in recent gtk on win32.
    elif config.data.os == 'win32':
        return False

    w=gtk.Window(gtk.WINDOW_POPUP)
    w.set_decorated(False)

    bw_style=get_color_style(w, 'black', 'white')
    w.set_style(bw_style)

    v=gtk.VBox()
    v.set_style(bw_style)

    def get_coloured_label(t, color=None):
        l=gtk.Label()
        #l.set_ellipsize(pango.ELLIPSIZE_END)
        if color is None:
            color='white'
        l.set_markup("""<span background="%s" foreground="black">%s</span>""" % (color, t.replace('<', '&lt;')))
        return l
    
    # FIXME: not multi-media compatible
    cache=controller.gui.imagecache

    if isinstance(element, (long, int)):
        begin=image_new_from_pixbuf(png_to_pixbuf (cache.get(element, epsilon=config.data.preferences['bookmark-snapshot-precision']), width=config.data.preferences['drag-snapshot-width']))
        begin.set_style(bw_style)

        l=gtk.Label()
        l.set_style(bw_style)
        l.set_text(helper.format_time(element))
        l.set_style(bw_style)

        v.pack_start(begin, expand=False)
        v.pack_start(l, expand=False)
        w.set_style(bw_style)
        w.set_size_request(long(1.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, Annotation):
        # Pictures HBox
        h=gtk.HBox()
        h.set_style(bw_style)
        begin=image_new_from_pixbuf(png_to_pixbuf (cache.get(element.begin), width=config.data.preferences['drag-snapshot-width']))
        begin.set_style(bw_style)
        h.pack_start(begin, expand=False)
        # Padding
        h.pack_start(gtk.HBox(), expand=True)
        end=image_new_from_pixbuf(png_to_pixbuf (cache.get(element.end), width=config.data.preferences['drag-snapshot-width']))
        end.set_style(bw_style)
        h.pack_start(end, expand=False)
        v.pack_start(h, expand=False)

        l=get_coloured_label(controller.get_title(element), controller.get_element_color(element))
        l.set_style(bw_style)
        v.pack_start(l, expand=False)
        w.set_style(bw_style)
        w.set_size_request(long(2.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, AnnotationType):
        l=get_coloured_label(_("Annotation Type %(title)s:\n%(count)s") % {
                'title': controller.get_title(element),
                'count': helper.format_element_name('annotation', len(element.annotations)),
                }, controller.get_element_color(element))
        v.pack_start(l, expand=False)
    elif isinstance(element, RelationType):
        l=get_coloured_label(_("Relation Type %(title)s:\n%(count)s") % {
                'title': controller.get_title(element),
                'count': helper.format_element_name('relation', len(element.relations)),
                }, controller.get_element_color(element))
        v.pack_start(l, expand=False)
    else:
        l=get_coloured_label("%s %s" % (helper.get_type(element),
                                        controller.get_title(element)),
                             controller.get_element_color(element))
        v.pack_start(l, expand=False)

    w.add(v)
    w.show_all()
    widget._icon=w
    context.set_icon_widget(w, 0, 0)
    return True
예제 #5
0
    def build_widget(self):
        v=Gtk.VBox()

        tb=Gtk.Toolbar()
        tb.set_style(Gtk.ToolbarStyle.ICONS)
        v.pack_start(tb, False, True, 0)

        top_box=Gtk.HBox()
        v.pack_start(top_box, False, True, 0)

        if hasattr(self.query, 'container') and self.query.container.id == '_interactive':
            b=Gtk.Button(_("Edit query again"))
            b.connect('clicked', self.edit_query)
            top_box.pack_start(b, False, True, 0)
        elif isinstance(self.query, SimpleQuery):
            b=Gtk.Button(_("Edit query"))
            b.connect('clicked', lambda b: self.controller.gui.edit_element(self.query))
            top_box.pack_start(b, False, True, 0)
        elif isinstance(self.query, Quicksearch):
            e=Gtk.Entry()
            e.set_text(self.query.searched)
            e.set_width_chars(12)
            e.connect('activate', self.redo_quicksearch, e)
            b=get_small_stock_button(Gtk.STOCK_FIND, self.redo_quicksearch, e)
            e.set_tooltip_text(_('String to search'))
            b.set_tooltip_text(_('Search again'))
            top_box.pack_start(e, False, True, 0)
            top_box.pack_start(b, False, True, 0)

        # Present choices to display the result
        if not self.result:
            v.add(Gtk.Label(label=_("Empty result")))
        elif (isinstance(self.result, list) or isinstance(self.result, tuple)
            or isinstance(self.result, AbstractBundle)):
            # Check if there are annotations
            l=[ a for a in self.result if isinstance(a, Annotation) ]
            cr=len(self.result)
            cl=len(l)

            if cr == cl:
                t=_("Result is a list of %d annotations.") % cr
            else:
                t=_("Result is a list of  %(number)d elements with %(elements)s.") % {
                    'elements': helper.format_element_name("annotation", len(l)),
                    'number': len(self.result)}

            label=Gtk.Label(label=t)
            label.set_ellipsize(Pango.EllipsizeMode.END)
            label.set_line_wrap(True)
            top_box.add(label)

            def toggle_highlight(b, annotation_list):
                if not hasattr(b, 'highlight') or b.highlight:
                    event="AnnotationActivate"
                    label= _("Unhighlight annotations")
                    b.highlight=False
                else:
                    event="AnnotationDeactivate"
                    label=_("Highlight annotations")
                    b.highlight=True
                b.set_tooltip_text(label)
                for a in annotation_list:
                    self.controller.notify(event, annotation=a)
                return True

            if l:
                # Instanciate a table view
                table=AnnotationTable(controller=self.controller, elements=l)

                if cr == cl:
                    # Only annotations.
                    v.add(table.widget)
                else:
                    # Mixed annotations + other elements
                    notebook=Gtk.Notebook()
                    notebook.set_tab_pos(Gtk.PositionType.TOP)
                    notebook.popup_disable()
                    v.add(notebook)

                    notebook.append_page(table.widget, Gtk.Label(label=_("Annotations")))

                    gtable=GenericTable(controller=self.controller, elements=[ e
                                                                               for e in self.result
                                                                               if not isinstance(e, Annotation) ]
                                                                               )
                    notebook.append_page(gtable.widget, Gtk.Label(label=_("Other elements")))


                for (icon, tip, action) in (
                    ('timeline.png' , _("Display annotations in timeline"), lambda b: self.open_in_timeline(l)),
                    ('transcription.png', _("Display annotations as transcription"), lambda b:
                         self.controller.gui.open_adhoc_view('transcription',
                                                             label=self._label,
                                                             destination=self._destination,
                                                             elements=l)),
                    ('highlight.png', _("Highlight annotations"), lambda b: toggle_highlight(b, l)),
                    (Gtk.STOCK_CONVERT, _("Export table"), lambda b: table.csv_export()),
                    (Gtk.STOCK_NEW, _("Create annotations from the result"), self.create_annotations),
                    ('montage.png', _("Define a montage with the result"), self.create_montage),
                    ('comment.png', _("Create a comment view with the result"), self.create_comment),
                    (Gtk.STOCK_FIND_AND_REPLACE, _("Search and replace strings in the annotations content"), self.search_replace),
                    ):
                    if icon.endswith('.png'):
                        ti=get_pixmap_toolbutton(icon)
                    else:
                        ti=Gtk.ToolButton(stock_id=icon)
                    ti.connect('clicked', action)
                    ti.set_tooltip_text(tip)
                    tb.insert(ti, -1)

                self.table=table
            else:
                # Only Instanciate a generic table view
                gtable=GenericTable(controller=self.controller, elements=self.result)
                v.add(gtable.widget)

                ti=Gtk.ToolButton(Gtk.STOCK_CONVERT)
                ti.connect('clicked', lambda b: gtable.csv_export())
                ti.set_tooltip_text(_("Export table"))
                tb.insert(ti, -1)
                self.table=gtable


            ti=get_pixmap_toolbutton('editaccumulator.png',
                                     lambda b: self.open_in_edit_accumulator(self.table.get_elements()))
            ti.set_tooltip_text(_("Edit elements"))
            tb.insert(ti, -1)

            if config.data.preferences['expert-mode']:
                ti=get_pixmap_toolbutton('python.png',
                                         lambda b: self.open_in_evaluator(self.table.get_elements()))
                ti.set_tooltip_text(_("Open in python evaluator"))
                tb.insert(ti, -1)
        else:
            v.add(Gtk.Label(label=_("Result:\n%s") % str(self.result)))
        v.show_all()
        return v
예제 #6
0
    def refresh(self, *p):
        if self.annotation is None:
            d={ 'title': _("No annotation"),
                'begin': helper.format_time(None),
                'end': helper.format_time(None),
                'contents': '',
                'imagecontents': None}
        elif isinstance(self.annotation, int) or isinstance(self.annotation, long):
            d={ 'title': _("Current time"),
                'begin': helper.format_time(self.annotation),
                'end': helper.format_time(None),
                'contents': '',
                'imagecontents': None}
        elif isinstance(self.annotation, AnnotationType):
            col=self.controller.get_element_color(self.annotation)
            if col:
                title='<span background="%s">Annotation Type <b>%s</b></span>' % (col, self.controller.get_title(self.annotation))
            else:
                title='Annotation Type <b>%s</b>' % self.controller.get_title(self.annotation)
            if len(self.annotation.annotations):
                b=min(a.fragment.begin for a in self.annotation.annotations)
                e=max(a.fragment.end for a in self.annotation.annotations)
            else:
                b=None
                e=None
            d={ 'title': title,
                'begin': helper.format_time(b),
                'end': helper.format_time(e),
                'contents': _("Schema %(schema)s\n%(description)s\n%(total)s\nId: %(id)s") % {
                    'schema': self.controller.get_title(self.annotation.schema),
                    'description': self.annotation.getMetaData(config.data.namespace_prefix['dc'], "description") or "",
                    'total': helper.format_element_name('annotation', len(self.annotation.annotations)),
                    'id': self.annotation.id
                    },
                'imagecontents': None,
                }
        else:
            # FIXME: there should be a generic content handler
            # mechanism for basic display of various contents
            d={ 'id': self.annotation.id,
                'begin': helper.format_time(self.annotation.fragment.begin),
                'end': helper.format_time(self.annotation.fragment.end),
                'duration': helper.format_time(self.annotation.fragment.duration),
                'color': self.controller.get_element_color(self.annotation),
                }
            if d['color']:
                d['title']='<span background="%(color)s">Annotation <b>%(id)s</b></span> (d: %(duration)s)' % d
            else:
                d['title']='Annotation <b>%(id)s</b> (d: %(duration)s)' % d
            svg_data=None
            if self.annotation.content.mimetype.startswith('image/svg'):
                svg_data=self.annotation.content.data
            elif self.annotation.content.mimetype == 'application/x-advene-zone':
                # Build svg
                data=self.annotation.content.parsed()
                svg_data='''<svg xmlns='http://www.w3.org/2000/svg' version='1' viewBox="0 0 320 300" x='0' y='0' width='320' height='200'><%(shape)s style="fill:none;stroke:green;stroke-width:2;" width="%(width)s%%" height="%(height)s%%" x="%(x)s%%" y="%(y)s%%"></rect></svg>''' % data
            if svg_data:
                pixbuf=overlay_svg_as_pixbuf(self.controller.package.imagecache[self.annotation.fragment.begin],
                                             self.annotation.content.data)
                d['contents']=''
                d['imagecontents']=pixbuf
            elif self.annotation.content.mimetype.startswith('image/'):
                # Image content, other than image/svg
                # Load the element content
                loader = gtk.gdk.PixbufLoader()
                try:
                    loader.write (self.annotation.content.data, len (self.annotation.content.data))
                    loader.close ()
                    pixbuf = loader.get_pixbuf ()
                except gobject.GError:
                    # The PNG data was invalid.
                    pixbuf=gtk.gdk.pixbuf_new_from_file(config.data.advenefile( ( 'pixmaps', 'notavailable.png' ) ))

                d['contents']=''
                d['imagecontents'] = pixbuf
            else:
                d['contents']=self.annotation.content.data
                d['imagecontents']=None

        for k, v in d.iteritems():
            if k == 'title':
                self.label[k].set_markup(v)
            elif k == 'imagecontents':
                if v is None:
                    self.sw['imagecontents'].hide()
                    self.sw['contents'].show()
                else:
                    self.sw['imagecontents'].show_all()
                    self.sw['contents'].hide()

                    pixbuf=d['imagecontents']
                    w=self.widget.get_allocation().width - 6
                    width=pixbuf.get_width()
                    height=pixbuf.get_height()
                    if width > w and w > 0:
                        height = 1.0 * w * height / width
                        pixbuf=pixbuf.scale_simple(int(w), int(height), gtk.gdk.INTERP_BILINEAR)
                    self.label['imagecontents'].set_from_pixbuf(pixbuf)
            else:
                widget = self.label.get(k)
                if widget is not None:
                    widget.set_text(v)
        if self.annotation is None or isinstance(self.annotation, AnnotationType):
            self.label['image'].hide()
        else:
            if isinstance(self.annotation, int) or isinstance(self.annotation, long):
                b=self.annotation
            elif isinstance(self.annotation, Annotation):
                b=self.annotation.fragment.begin
            self.label['image'].value = b
            self.label['image'].show()
        return False
예제 #7
0
    def refresh(self, *p):
        if self.annotation is None:
            d={ 'title': _("No annotation"),
                'begin': '--:--:--:--',
                'end': '--:--:--:--',
                'contents': '',
                'imagecontents': None}
        elif isinstance(self.annotation, int) or isinstance(self.annotation, long):
            d={ 'title': _("Current time"),
                'begin': helper.format_time(self.annotation),
                'end': '--:--:--:--',
                'contents': '',
                'imagecontents': None}
        elif isinstance(self.annotation, AnnotationType):
            col=self.controller.get_element_color(self.annotation)
            if col:
                title='<span background="%s">Annotation Type <b>%s</b></span>' % (col, self.controller.get_title(self.annotation))
            else:
                title='Annotation Type <b>%s</b>' % self.controller.get_title(self.annotation)
            if len(self.annotation.annotations):
                b=min(a.begin for a in self.annotation.annotations)
                e=max(a.end for a in self.annotation.annotations)
            else:
                b=None
                e=None
            d={ 'title': title,
                'begin': helper.format_time(b),
                'end': helper.format_time(e),
                'contents': _("Schema %(schema)s\n%(description)s\n%(total)s\nId: %(id)s") % {
                    'schema': ",".join(self.controller.get_title(s) for s in self.annotation.my_schemas),
                    'description': self.annotation.description or "",
                    'total': helper.format_element_name('annotation', len(self.annotation.annotations)),
                    'id': self.annotation.id
                    },
                'imagecontents': None,
                }
        else:
            # FIXME: there should be a generic content handler
            # mechanism for basic display of various contents
            col=self.controller.get_element_color(self.annotation)
            if col:
                title='<span background="%s">Annotation <b>%s</b></span>' % (col, self.annotation.id)
            else:
                title='Annotation <b>%s</b>' % self.annotation.id
            d={ 'title': title,
                'begin': helper.format_time(self.annotation.begin),
                'end': helper.format_time(self.annotation.end) }
            svg_data=None
            if self.annotation.content.mimetype.startswith('image/'):
                svg_data=self.annotation.content.data
            elif self.annotation.content.mimetype == 'application/x-advene-zone':
                # Build svg
                data=self.annotation.content.parsed()
                svg_data='''<svg xmlns='http://www.w3.org/2000/svg' version='1' viewBox="0 0 320 300" x='0' y='0' width='320' height='200'><%(shape)s style="fill:none;stroke:green;stroke-width:2;" width="%(width)s%%" height="%(height)s%%" x="%(x)s%%" y="%(y)s%%"></rect></svg>''' % data
            if svg_data:
                pixbuf=overlay_svg_as_pixbuf(self.controller.imagecache[self.annotation.media.url][self.annotation.begin],
                                             self.annotation.content.data)
                d['contents']=''
                d['imagecontents']=pixbuf
            else:
                d['contents']=self.annotation.content.data
                d['imagecontents']=None

        for k, v in d.iteritems():
            if k == 'title':
                self.label[k].set_markup(v)
            elif k == 'imagecontents':
                if v is None:
                    self.sw['imagecontents'].hide()
                    self.sw['contents'].show()
                else:
                    self.sw['imagecontents'].show_all()
                    self.sw['contents'].hide()

                    pixbuf=d['imagecontents']
                    w=self.widget.get_allocation().width - 6
                    width=pixbuf.get_width()
                    height=pixbuf.get_height()
                    if width > w and w > 0:
                        height = 1.0 * w * height / width
                        pixbuf=pixbuf.scale_simple(int(w), int(height), gtk.gdk.INTERP_BILINEAR)
                    self.label['imagecontents'].set_from_pixbuf(pixbuf)
            else:
                self.label[k].set_text(v)
        if self.annotation is None or isinstance(self.annotation, AnnotationType):
            self.label['image'].hide()
        else:
            if isinstance(self.annotation, int) or isinstance(self.annotation, long):
                b=self.annotation
            elif isinstance(self.annotation, Annotation):
                b=self.annotation.begin
            self.label['image'].value = b
            self.label['image'].show()
        return False
예제 #8
0
def contextual_drag_begin(widget, context, element, controller):
    if callable(element):
        element=element()
    context._element=element

    if hasattr(widget, '_drag_begin'):
        if widget._drag_begin(widget, context):
            return False

    w=Gtk.Window(Gtk.WindowType.POPUP)
    w.set_decorated(False)
    w.get_style_context().add_class('advene_drag_icon')

    v=Gtk.VBox()
    v.get_style_context().add_class('advene_drag_icon')

    def get_coloured_label(t, color=None):
        l=Gtk.Label()
        #l.set_ellipsize(Pango.EllipsizeMode.END)
        if color is None:
            color='white'
        l.set_markup("""<span background="%s" foreground="black">%s</span>""" % (color, t.replace('<', '&lt;')))
        return l

    if isinstance(element, int):
        begin = image_new_from_pixbuf(png_to_pixbuf(controller.get_snapshot(position=element, precision=config.data.preferences['bookmark-snapshot-precision']), width=config.data.preferences['drag-snapshot-width']))
        begin.get_style_context().add_class('advene_drag_icon')

        l=Gtk.Label()
        l.set_text(helper.format_time(element))
        l.get_style_context().add_class('advene_drag_icon')

        v.pack_start(begin, False, True, 0)
        v.pack_start(l, False, True, 0)
        w.set_size_request(int(1.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, Annotation):
        # Pictures HBox
        h=Gtk.HBox()
        h.get_style_context().add_class('advene_drag_icon')
        begin = image_new_from_pixbuf(png_to_pixbuf(controller.get_snapshot(annotation=element), width=config.data.preferences['drag-snapshot-width']))
        begin.get_style_context().add_class('advene_drag_icon')
        h.pack_start(begin, False, True, 0)
        # Padding
        h.pack_start(Gtk.HBox(), True, True, 0)
        end = image_new_from_pixbuf(png_to_pixbuf(controller.get_snapshot(annotation=element, position=element.fragment.end), width=config.data.preferences['drag-snapshot-width']))
        end.get_style_context().add_class('advene_drag_icon')
        h.pack_start(end, False, True, 0)
        v.pack_start(h, False, True, 0)

        l=get_coloured_label(controller.get_title(element), controller.get_element_color(element))
        l.get_style_context().add_class('advene_drag_icon')
        v.pack_start(l, False, True, 0)
        w.get_style_context().add_class('advene_drag_icon')
        w.set_size_request(int(2.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, AnnotationType):
        l=get_coloured_label(_("Annotation Type %(title)s:\n%(count)s") % {
            'title': controller.get_title(element),
            'count': helper.format_element_name('annotation', len(element.annotations)),
        }, controller.get_element_color(element))
        v.pack_start(l, False, True, 0)
    elif isinstance(element, RelationType):
        l=get_coloured_label(_("Relation Type %(title)s:\n%(count)s") % {
            'title': controller.get_title(element),
            'count': helper.format_element_name('relation', len(element.relations)),
        }, controller.get_element_color(element))
        v.pack_start(l, False, True, 0)
    else:
        l=get_coloured_label("%s %s" % (helper.get_type(element),
                                        controller.get_title(element)),
                             controller.get_element_color(element))
        v.pack_start(l, False, True, 0)

    w.add(v)
    w.show_all()
    widget._icon=w
    Gtk.drag_set_icon_widget(context, w, 0, 0)
    return True
예제 #9
0
파일: __init__.py 프로젝트: pchampin/advene
def contextual_drag_begin(widget, context, element, controller):
    if callable(element):
        element = element()
    context._element = element

    if hasattr(widget, '_drag_begin'):
        if widget._drag_begin(widget, context):
            return False

    # set_icon_widget does not work on native Gtk on MacOS X
    if config.data.os == 'darwin' and not os.environ.get('DISPLAY'):
        return False
    # set_icon_widget is broken ATM in recent gtk on win32.
    elif config.data.os == 'win32':
        return False

    w = gtk.Window(gtk.WINDOW_POPUP)
    w.set_decorated(False)

    bw_style = get_color_style(w, 'black', 'white')
    w.set_style(bw_style)

    v = gtk.VBox()
    v.set_style(bw_style)

    def get_coloured_label(t, color=None):
        l = gtk.Label()
        #l.set_ellipsize(pango.ELLIPSIZE_END)
        if color is None:
            color = 'white'
        l.set_markup("""<span background="%s" foreground="black">%s</span>""" %
                     (color, t.replace('<', '&lt;')))
        return l

    cache = controller.package.imagecache

    if isinstance(element, (long, int)):
        begin = image_new_from_pixbuf(
            png_to_pixbuf(
                cache.get(element,
                          epsilon=config.data.
                          preferences['bookmark-snapshot-precision']),
                width=config.data.preferences['drag-snapshot-width']))
        begin.set_style(bw_style)

        l = gtk.Label()
        l.set_style(bw_style)
        l.set_text(helper.format_time(element))
        l.set_style(bw_style)

        v.pack_start(begin, expand=False)
        v.pack_start(l, expand=False)
        w.set_style(bw_style)
        w.set_size_request(
            long(1.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, Annotation):
        # Pictures HBox
        h = gtk.HBox()
        h.set_style(bw_style)
        begin = image_new_from_pixbuf(
            png_to_pixbuf(
                cache.get(element.fragment.begin),
                width=config.data.preferences['drag-snapshot-width']))
        begin.set_style(bw_style)
        h.pack_start(begin, expand=False)
        # Padding
        h.pack_start(gtk.HBox(), expand=True)
        end = image_new_from_pixbuf(
            png_to_pixbuf(
                cache.get(element.fragment.end),
                width=config.data.preferences['drag-snapshot-width']))
        end.set_style(bw_style)
        h.pack_start(end, expand=False)
        v.pack_start(h, expand=False)

        l = get_coloured_label(controller.get_title(element),
                               controller.get_element_color(element))
        l.set_style(bw_style)
        v.pack_start(l, expand=False)
        w.set_style(bw_style)
        w.set_size_request(
            long(2.5 * config.data.preferences['drag-snapshot-width']), -1)
    elif isinstance(element, AnnotationType):
        l = get_coloured_label(
            _("Annotation Type %(title)s:\n%(count)s") % {
                'title':
                controller.get_title(element),
                'count':
                helper.format_element_name('annotation',
                                           len(element.annotations)),
            }, controller.get_element_color(element))
        v.pack_start(l, expand=False)
    elif isinstance(element, RelationType):
        l = get_coloured_label(
            _("Relation Type %(title)s:\n%(count)s") % {
                'title':
                controller.get_title(element),
                'count':
                helper.format_element_name('relation', len(element.relations)),
            }, controller.get_element_color(element))
        v.pack_start(l, expand=False)
    else:
        l = get_coloured_label(
            "%s %s" %
            (helper.get_type(element), controller.get_title(element)),
            controller.get_element_color(element))
        v.pack_start(l, expand=False)

    w.add(v)
    w.show_all()
    widget._icon = w
    context.set_icon_widget(w, 0, 0)
    return True
예제 #10
0
    def build_widget(self):
        v=Gtk.VBox()

        tb=Gtk.Toolbar()
        tb.set_style(Gtk.ToolbarStyle.ICONS)
        v.pack_start(tb, False, True, 0)

        top_box=Gtk.HBox()
        v.pack_start(top_box, False, True, 0)

        if hasattr(self.query, 'container') and self.query.container.id == '_interactive':
            b=Gtk.Button(_("Edit query again"))
            b.connect('clicked', self.edit_query)
            top_box.pack_start(b, False, True, 0)
        elif isinstance(self.query, SimpleQuery):
            b=Gtk.Button(_("Edit query"))
            b.connect('clicked', lambda b: self.controller.gui.edit_element(self.query))
            top_box.pack_start(b, False, True, 0)
        elif isinstance(self.query, Quicksearch):
            e=Gtk.Entry()
            e.set_text(self.query.searched)
            e.set_width_chars(12)
            e.connect('activate', self.redo_quicksearch, e)
            b=get_small_stock_button(Gtk.STOCK_FIND, self.redo_quicksearch, e)
            e.set_tooltip_text(_('String to search'))
            b.set_tooltip_text(_('Search again'))
            top_box.pack_start(e, False, True, 0)
            top_box.pack_start(b, False, True, 0)

        # Present choices to display the result
        if not self.result:
            v.add(Gtk.Label(label=_("Empty result")))
        elif isinstance(self.result, (list, tuple, AbstractBundle)):
            # Check if there are annotations
            l=[ a for a in self.result if isinstance(a, Annotation) ]
            cr=len(self.result)
            cl=len(l)

            if cr == cl:
                t=_("Result is a list of %d annotations.") % cr
            else:
                t=_("Result is a list of  %(number)d elements with %(elements)s.") % {
                    'elements': helper.format_element_name("annotation", len(l)),
                    'number': len(self.result)}

            label=Gtk.Label(label=t)
            label.set_ellipsize(Pango.EllipsizeMode.END)
            label.set_line_wrap(True)
            top_box.add(label)

            def toggle_highlight(b, annotation_list):
                if not hasattr(b, 'highlight') or b.highlight:
                    event="AnnotationActivate"
                    label= _("Unhighlight annotations")
                    b.highlight=False
                else:
                    event="AnnotationDeactivate"
                    label=_("Highlight annotations")
                    b.highlight=True
                b.set_tooltip_text(label)
                for a in annotation_list:
                    self.controller.notify(event, annotation=a)
                return True

            if l:
                # Instanciate a table view
                table=AnnotationTable(controller=self.controller, elements=l)

                if cr == cl:
                    # Only annotations.
                    v.add(table.widget)
                else:
                    # Mixed annotations + other elements
                    notebook=Gtk.Notebook()
                    notebook.set_tab_pos(Gtk.PositionType.TOP)
                    notebook.popup_disable()
                    v.add(notebook)

                    notebook.append_page(table.widget, Gtk.Label(label=_("Annotations")))

                    gtable=GenericTable(controller=self.controller, elements=[ e
                                                                               for e in self.result
                                                                               if not isinstance(e, Annotation) ])
                    notebook.append_page(gtable.widget, Gtk.Label(label=_("Other elements")))


                for (icon, tip, action) in (
                        ('timeline.png' , _("Display annotations in timeline"), lambda b: self.open_in_timeline(l)),
                        ('transcription.png', _("Display annotations as transcription"), lambda b:
                         self.controller.gui.open_adhoc_view('transcription',
                                                             label=self._label,
                                                             destination=self._destination,
                                                             elements=l)),
                        ('highlight.png', _("Highlight annotations"), lambda b: toggle_highlight(b, l)),
                        (Gtk.STOCK_CONVERT, _("Export table"), lambda b: table.csv_export()),
                        (Gtk.STOCK_NEW, _("Create annotations from the result"), self.create_annotations),
                        ('montage.png', _("Define a montage with the result"), self.create_montage),
                        ('comment.png', _("Create a comment view with the result"), self.create_comment),
                        (Gtk.STOCK_FIND_AND_REPLACE, _("Search and replace strings in the annotations content"), self.search_replace),
                ):
                    if icon.endswith('.png'):
                        ti=get_pixmap_toolbutton(icon)
                    else:
                        ti=Gtk.ToolButton(stock_id=icon)
                    ti.connect('clicked', action)
                    ti.set_tooltip_text(tip)
                    tb.insert(ti, -1)

                self.table=table
            else:
                # Only Instanciate a generic table view
                gtable=GenericTable(controller=self.controller, elements=self.result)
                v.add(gtable.widget)

                ti=Gtk.ToolButton(Gtk.STOCK_CONVERT)
                ti.connect('clicked', lambda b: gtable.csv_export())
                ti.set_tooltip_text(_("Export table"))
                tb.insert(ti, -1)
                self.table=gtable


            ti=get_pixmap_toolbutton('editaccumulator.png',
                                     lambda b: self.open_in_edit_accumulator(self.table.get_elements()))
            ti.set_tooltip_text(_("Edit elements"))
            tb.insert(ti, -1)

            if config.data.preferences['expert-mode']:
                ti=get_pixmap_toolbutton('python.png',
                                         lambda b: self.open_in_evaluator(self.table.get_elements()))
                ti.set_tooltip_text(_("Open in python evaluator"))
                tb.insert(ti, -1)
        else:
            v.add(Gtk.Label(label=_("Result:\n%s") % str(self.result)))
        v.show_all()
        return v
예제 #11
0
파일: finder.py 프로젝트: oaubert/advene
    def build_widget(self):
        el = self.node.element
        vbox=Gtk.VBox()

        info = Gtk.TextView()
        info.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
        def set_text(widget, t):
            b=widget.get_buffer()
            b.delete(*b.get_bounds())
            b.set_text(t)
            b.set_modified(False)
            return True
        info.set_text = set_text.__get__(info)
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        if isinstance(el, Package):
            info.set_text(_("""Package %(title)s:
%(schema)s
%(annotation)s in %(annotation_type)s
%(relation)s in %(relation_type)s
%(query)s
%(view)s

Description:
%(description)s

Annotation statistics:
%(statistics)s
""") % {
        'title': el.title,
        'schema': helper.format_element_name('schema', len(el.schemas)),
        'annotation': helper.format_element_name('annotation', len(el.annotations)),
        'annotation_type': helper.format_element_name('annotation_type', len(el.annotationTypes)),
        'relation': helper.format_element_name('relation', len(el.relations)),
        'relation_type': helper.format_element_name('relation_type', len(el.relationTypes)),
        'query': helper.format_element_name('query', len(el.queries)),
        'view': helper.format_element_name('view', len(el.views)),
        'description': el.getMetaData(config.data.namespace_prefix['dc'], 'description'),
        'statistics': helper.get_annotations_statistics(el.annotations)
        })
        elif isinstance(el, AnnotationType):
            info.set_text(_("""%(type)s %(title)s\n%(statistics)s""") % ({
                "type": helper.get_type(el),
                "title": self.controller.get_title(el),
                "statistics": helper.get_annotations_statistics(el.annotations)
            }))
        elif isinstance(el, Schema):
            info.set_text(_("""%(type)s %(title)s\n%(statistics)s""") % ({
                "type": helper.get_type(el),
                "title": self.controller.get_title(el),
                "statistics": helper.get_schema_statistics(el)
            }))
        else:
            info.set_text(_("""%(type)s %(title)s""") % ({"type": helper.get_type(el),
                                                          "title": self.controller.get_title(el)}))
        sw.add(info)

        edit_button = Gtk.Button(_("Edit"))
        edit_button.connect('clicked', lambda w: self.controller.gui.edit_element(el))

        frame = Gtk.Expander.new(_("Metadata"))
        frame.set_expanded(False)
        self.view = EditWidget(self.node.set_config, self.node.get_config)
        for p in self.node.list_keys():
            self.view.add_entry(p, p, "")
        frame.add(self.view)

        vbox.add(sw)
        if not isinstance(el, (VirtualNode, AbstractBundle)):
            vbox.pack_start(edit_button, False, False, 0)
            vbox.pack_start(frame, False, False, 0)
        vbox.show_all()
        return vbox