Beispiel #1
0
    def __init__(self, handle):
        super(VteActivity, self).__init__(handle)

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbar = toolbarbox.toolbar

        activitybutton = ActivityToolbarButton(self)
        toolbar.insert(activitybutton, -1)

        toolbar.insert(Gtk.SeparatorToolItem(), -1)

        # add 'copy' icon from standard toolbar.
        edittoolbar = EditToolbar()
        edittoolbar.copy.set_tooltip(_('Copy selected text to clipboard'))
        edittoolbar.copy.connect('clicked', self._on_copy_clicked_cb)
        edittoolbar.paste.connect('clicked', self._on_paste_clicked_cb)
        # as long as nothing is selected, copy needs to be insensitive.
        edittoolbar.copy.set_sensitive(False)
        edittoolbar.show()
        self._copy_button = edittoolbar.copy

        editbutton = ToolbarButton(page=edittoolbar, icon_name='toolbar-edit')
        toolbar.insert(editbutton, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.insert(separator, -1)

        stopbutton = StopButton(self)
        toolbar.insert(stopbutton, -1)

        # creates vte widget
        self._vte = Vte.Terminal()
        self._vte.set_size(30, 5)
        self._vte.set_size_request(200, 300)
        font = 'Monospace 10'
        self._vte.set_font(Pango.FontDescription(font))
        self._vte.drag_dest_set(
            Gtk.DestDefaults.ALL,
            [Gtk.TargetEntry.new("text/plain", 0, TARGET_TYPE_TEXT)],
            Gdk.DragAction.COPY)

        foreground = Gdk.Color.parse('#000000')[1]
        background = Gdk.Color.parse('#E7E7E7')[1]

        try:
            self._vte.set_colors(foreground, background, [])

        except TypeError:
            self._vte.set_colors(Gdk.RGBA.from_color(foreground),
                                 Gdk.RGBA.from_color(background), [])

        self._vte.connect('selection-changed', self._on_selection_changed_cb)
        self._vte.connect('drag_data_received', self._on_drop_cb)

        # ...and its scrollbar
        vtebox = Gtk.HBox()
        vtebox.pack_start(self._vte, True, True, 0)
        self.set_canvas(vtebox)

        vtesb = Gtk.VScrollbar.new(self._vte.get_vadjustment())
        vtebox.pack_start(vtesb, False, False, 0)

        self.show_all()
        # hide the buttons we don't use.

        edittoolbar.undo.hide()
        edittoolbar.redo.hide()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        # the 'sleep 1' works around a bug with the command dying before
        # the vte widget manages to snarf the last bits of its output

        argv = [
            "/bin/sh", "-c",
            "python %s; sleep 1" % os.path.join(bundle_path, "app.py")
        ]

        args = (Vte.PtyFlags.DEFAULT, bundle_path, argv,
                ["PYTHONPATH=%s/library" % bundle_path
                 ], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)

        if hasattr(self._vte, 'fork_command_full'):
            self._vte.fork_command_full(*args)
        else:
            self._vte.spawn_sync(*args)
Beispiel #2
0
class EditActivity(activity.Activity):
    def checkts(self):
        '''Check the timestamp
        If someone's modified our file in an external editor,
        we should reload the contents
        '''

        mtime = self.metadata[mdnames.sugartimestamp_md]
        etime = self.metadata[mdnames.cloudtimestamp_md]
        return mtime > etime

    def __init__(self, handle):
        '''We want to set up the buffer et al. early on
        sure there's early_setup, but that's not early enough
        '''
        activity.Activity.__init__(self, handle)
        self._collab = CollabWrapper(self)

        self.buffer = GtkSource.Buffer()
        TextBufferCollaberizer(self.buffer, 'main', self._collab)
        self.refresh_buffer = False

        self.text_view = GtkSource.View.new_with_buffer(self.buffer)
        self.scrollwindow = Gtk.ScrolledWindow()
        self.scrollwindow.add(self.text_view)

        self.setup_toolbar()

        self.set_canvas(self.scrollwindow)
        self.scrollwindow.show_all()
        self._collab.setup()


    def fix_mimetype(self):
        '''We must have a mimetype. Sometimes, we don't (when we get launched
        newly.) This  fixes that.'''
        if self.metadata[mdnames.mimetype_md] == '':
            self.metadata[mdnames.mimetype_md] = "text/plain"
            #we MUST have a mimetype

    def setup_toolbar(self):
        '''Setup the top toolbar. Groupthink needs some work here.'''

        toolbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.set_toolbar_box(toolbox)
        toolbox.show()
        toolbar = toolbox.toolbar

        self.edit_toolbar = EditToolbar()
        edit_toolbar_button = ToolbarButton(
            page=self.edit_toolbar,
            icon_name='toolbar-edit')
        self.edit_toolbar.show()
        toolbar.insert(edit_toolbar_button, -1)
        edit_toolbar_button.show()

        self.edit_toolbar.undo.connect('clicked', self.undobutton_cb)
        self.edit_toolbar.redo.connect('clicked', self.redobutton_cb)
        self.edit_toolbar.copy.connect('clicked', self.copybutton_cb)
        self.edit_toolbar.paste.connect('clicked', self.pastebutton_cb)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

    def initialize_display(self):
        '''Set up GTK and friends'''
        self.fix_mimetype()

        lang_manager = GtkSource.LanguageManager.get_default()
        if hasattr(lang_manager, 'list_languages'):
            langs = lang_manager.list_languages()
        else:
            lang_ids = lang_manager.get_language_ids()
            langs = [lang_manager.get_language(lang_id) \
                         for lang_id in lang_ids]
            for lang in langs:
                for mtype in lang.get_mime_types():
                    if mtype == self.metadata[mdnames.mimetype_md]:
                        self.buffer.set_language(lang)
                        break

        self.text_view.set_editable(True)
        self.text_view.set_cursor_visible(True)

        if self.metadata[mdnames.mimetype_md] == "text/plain":
            self.text_view.set_show_line_numbers(False)
            self.text_view.set_wrap_mode(Gtk.WrapMode.WORD)
            font = Pango.FontDescription("Bitstream Vera Sans " +
                                         str(style.FONT_SIZE))
        else:
            if hasattr(self.buffer, 'set_highlight'):
                self.buffer.set_highlight(True)
            else:
                self.buffer.set_highlight_syntax(True)

            self.text_view.set_show_line_numbers(True)

            self.text_view.set_wrap_mode(Gtk.WrapMode.CHAR)
            self.text_view.set_insert_spaces_instead_of_tabs(True)
            self.text_view.set_tab_width(2)
            self.text_view.set_auto_indent(True)
            font = Pango.FontDescription("Monospace " +
                                         str(style.FONT_SIZE))

        self.text_view.modify_font(font)

        if self.refresh_buffer:
            #see load_from_journal()
            self.buffer.begin_not_undoable_action()
            self.buffer.set_text(self.refresh_buffer)
            self.buffer.end_not_undoable_action()

        self.text_view.show()

        #Return the main widget. our parents take care of GTK stuff
        return self.scrollwindow

    def write_file(self, filename):
        #Also write to file:
        fhandle = open(filename, "w")

        bounds = self.buffer.get_bounds()
        text = self.buffer.get_text(bounds[0], bounds[1], True)

        fhandle.write(text)
        fhandle.close()

        self.fix_mimetype()

        #We can do full-text search on all Edit documents, yay
        self.metadata[mdnames.contents_md] = text

    def read_file(self, filename):
        '''Load the file. Duh.'''
        text = open(filename, "r").read()  # yay hackish one-line read

        self.buffer.set_text(text)
        return None

    def undobutton_cb(self, button):
        if self.buffer.can_undo():
            self.buffer.undo()

    def redobutton_cb(self, button):
        global text_buffer
        if self.buffer.can_redo():
            self.buffer.redo()

    def copybutton_cb(self, button):
        self.buffer.copy_clipboard(Gtk.Clipboard())

    def pastebutton_cb(self, button):
        self.buffer.paste_clipboard(Gtk.Clipboard(), None, True)
Beispiel #3
0
class EditActivity(activity.Activity):
    def checkts(self):
        '''Check the timestamp
        If someone's modified our file in an external editor,
        we should reload the contents
        '''

        mtime = self.metadata[mdnames.sugartimestamp_md]
        etime = self.metadata[mdnames.cloudtimestamp_md]
        return mtime > etime

    def __init__(self, handle):
        '''We want to set up the buffer et al. early on
        sure there's early_setup, but that's not early enough
        '''
        activity.Activity.__init__(self, handle)
        self._collab = CollabWrapper(self)

        self.buffer = GtkSource.Buffer()
        TextBufferCollaberizer(self.buffer, 'main', self._collab)
        self.refresh_buffer = False

        self.text_view = GtkSource.View.new_with_buffer(self.buffer)
        self.scrollwindow = Gtk.ScrolledWindow()
        self.scrollwindow.add(self.text_view)

        self.setup_toolbar()

        self.set_canvas(self.scrollwindow)
        self.scrollwindow.show_all()
        self._collab.setup()

    def fix_mimetype(self):
        '''We must have a mimetype. Sometimes, we don't (when we get launched
        newly.) This  fixes that.'''
        if self.metadata[mdnames.mimetype_md] == '':
            self.metadata[mdnames.mimetype_md] = "text/plain"
            #we MUST have a mimetype

    def setup_toolbar(self):
        '''Setup the top toolbar. Groupthink needs some work here.'''

        toolbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.set_toolbar_box(toolbox)
        toolbox.show()
        toolbar = toolbox.toolbar

        self.edit_toolbar = EditToolbar()
        edit_toolbar_button = ToolbarButton(page=self.edit_toolbar,
                                            icon_name='toolbar-edit')
        self.edit_toolbar.show()
        toolbar.insert(edit_toolbar_button, -1)
        edit_toolbar_button.show()

        self.edit_toolbar.undo.connect('clicked', self.undobutton_cb)
        self.edit_toolbar.redo.connect('clicked', self.redobutton_cb)
        self.edit_toolbar.copy.connect('clicked', self.copybutton_cb)
        self.edit_toolbar.paste.connect('clicked', self.pastebutton_cb)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

    def initialize_display(self):
        '''Set up GTK and friends'''
        self.fix_mimetype()

        lang_manager = GtkSource.LanguageManager.get_default()
        if hasattr(lang_manager, 'list_languages'):
            langs = lang_manager.list_languages()
        else:
            lang_ids = lang_manager.get_language_ids()
            langs = [lang_manager.get_language(lang_id) \
                         for lang_id in lang_ids]
            for lang in langs:
                for mtype in lang.get_mime_types():
                    if mtype == self.metadata[mdnames.mimetype_md]:
                        self.buffer.set_language(lang)
                        break

        self.text_view.set_editable(True)
        self.text_view.set_cursor_visible(True)

        if self.metadata[mdnames.mimetype_md] == "text/plain":
            self.text_view.set_show_line_numbers(False)
            self.text_view.set_wrap_mode(Gtk.WrapMode.WORD)
            font = Pango.FontDescription("Bitstream Vera Sans " +
                                         str(style.FONT_SIZE))
        else:
            if hasattr(self.buffer, 'set_highlight'):
                self.buffer.set_highlight(True)
            else:
                self.buffer.set_highlight_syntax(True)

            self.text_view.set_show_line_numbers(True)

            self.text_view.set_wrap_mode(Gtk.WrapMode.CHAR)
            self.text_view.set_insert_spaces_instead_of_tabs(True)
            self.text_view.set_tab_width(2)
            self.text_view.set_auto_indent(True)
            font = Pango.FontDescription("Monospace " + str(style.FONT_SIZE))

        self.text_view.modify_font(font)

        if self.refresh_buffer:
            #see load_from_journal()
            self.buffer.begin_not_undoable_action()
            self.buffer.set_text(self.refresh_buffer)
            self.buffer.end_not_undoable_action()

        self.text_view.show()

        #Return the main widget. our parents take care of GTK stuff
        return self.scrollwindow

    def write_file(self, filename):
        #Also write to file:
        fhandle = open(filename, "w")

        bounds = self.buffer.get_bounds()
        text = self.buffer.get_text(bounds[0], bounds[1], True)

        fhandle.write(text)
        fhandle.close()

        self.fix_mimetype()

        #We can do full-text search on all Edit documents, yay
        self.metadata[mdnames.contents_md] = text

    def read_file(self, filename):
        '''Load the file. Duh.'''
        text = open(filename, "r").read()  # yay hackish one-line read

        self.buffer.set_text(text)
        return None

    def undobutton_cb(self, button):
        if self.buffer.can_undo():
            self.buffer.undo()

    def redobutton_cb(self, button):
        global text_buffer
        if self.buffer.can_redo():
            self.buffer.redo()

    def copybutton_cb(self, button):
        self.buffer.copy_clipboard(Gtk.Clipboard())

    def pastebutton_cb(self, button):
        self.buffer.paste_clipboard(Gtk.Clipboard(), None, True)
Beispiel #4
0
class WordCloudActivity(activity.Activity):
    def __init__(self, handle):
        """Set up the HelloWorld activity."""
        activity.Activity.__init__(self, handle)

        self.connect('realize', self.__realize_cb)

        self.max_participants = 1  # No sharing

        self._font_name = None
        self._layout = LAYOUT_RANDOM
        self._xo_colors = (_rgb(profile.get_color().to_string().split(',')[0]),
                           _rgb(profile.get_color().to_string().split(',')[1]))
        self._color_scheme = self._xo_colors
        self._repeat_tags = False

        self._toolbox = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        self._toolbox.toolbar.insert(self.activity_button, 0)
        self.activity_button.show()

        self.set_toolbar_box(self._toolbox)
        self._toolbox.show()
        self.toolbar = self._toolbox.toolbar

        self._edit_toolbar = EditToolbar()
        button = ToolbarButton()
        button.set_page(self._edit_toolbar)
        button.props.icon_name = 'toolbar-edit'
        button.props.label = _('Edit')
        self._toolbox.toolbar.insert(button, -1)
        button.show()
        self._edit_toolbar.show()

        self._undo_button = self._edit_toolbar.undo
        self._undo_button.set_sensitive(False)
        self._undo_button.connect('clicked', self._undo_cb)
        self._redo_button = self._edit_toolbar.redo
        self._redo_button.set_sensitive(False)
        self._redo_button.connect('clicked', self._redo_cb)

        # used to count number of times wordcloud is clicked
        self._count_wordcloud = 0
        self._undo_clicked = False
        self._save_text = []  # used to save text for undo
        self._save_text_redo = []  # used to save text for redo

        self._copy_button = self._edit_toolbar.copy
        self._copy_button.set_sensitive(False)
        self._copy_button.connect('clicked', self._copy_cb)
        self._paste_button = self._edit_toolbar.paste
        self._paste_button.set_sensitive(False)
        self._paste_button.connect('clicked', self._paste_cb)

        go_button = ToolButton('generate-cloud')
        self._toolbox.toolbar.insert(go_button, -1)
        go_button.set_tooltip(_('Create the cloud'))
        go_button.show()
        go_button.connect('clicked', self._go_cb)

        self._text_item = TextItem(self)
        self._toolbox.toolbar.insert(self._text_item, -1)
        self._text_item.show()
        text = self._read_metadata('text')
        if text is not None:
            self._text_item.set_text(text)

        self._repeat_button = ToggleToolButton('repeat-cloud')
        self._toolbox.toolbar.insert(self._repeat_button, -1)
        self._repeat_button.set_tooltip(_('Repeat words'))
        self._repeat_button.show()
        self._repeat_button.connect('clicked', self._repeat_cb)

        self.font_palette_content, self.font_palette_dict = \
            set_palette_list(
                self._setup_font_palette(), 3, 7,
                style.SMALL_ICON_SIZE + style.DEFAULT_SPACING +
                style.DEFAULT_PADDING, return_dict=True)
        self._font_button = FontToolItem(self)
        self.font_palette_content.show()
        self._toolbox.toolbar.insert(self._font_button, -1)
        self._font_button.show()

        self.color_palette_content, self.color_palette_dict = \
            set_palette_list(
                self._setup_color_palette(), 3, 5,
                style.GRID_CELL_SIZE + style.DEFAULT_SPACING +
                style.DEFAULT_PADDING, return_dict=True)
        self._color_button = ColorToolItem(self)
        self.color_palette_content.show()
        self._toolbox.toolbar.insert(self._color_button, -1)
        self._color_button.show()

        self.layout_palette_content, self.layout_palette_dict = \
            set_palette_list(self._setup_layout_palette(), 1, 5,
                             style.GRID_CELL_SIZE + style.DEFAULT_SPACING +
                             style.DEFAULT_PADDING, return_dict=True)
        self._layout_button = LayoutToolItem(self)
        self.layout_palette_content.show()
        self._toolbox.toolbar.insert(self._layout_button, -1)
        self._layout_button.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self._toolbox.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        self._toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        self._show_image(
            os.path.join(activity.get_bundle_path(), 'WordCloud.png'))

        self._set_color('XO')
        self._set_font('Droid Sans')

        for layout in list(LAYOUT_SCHEMES.keys()):
            if LAYOUT_SCHEMES[layout] == self._layout:
                self._set_layout(layout)
                break

    def _read_metadata(self, keyword, default_value=None):
        ''' If the keyword is found, return stored value '''
        if keyword in self.metadata:
            return (self.metadata[keyword])
        else:
            return (default_value)

    def write_file(self, file_path):
        self.metadata['text'] = self._text_item.get_text_from_buffer()

    def _show_image(self, path):
        if Gdk.Screen.height() < Gdk.Screen.width():
            height = Gdk.Screen.height() - style.GRID_CELL_SIZE
            width = int(height * 4 / 3)
        else:
            width = Gdk.Screen.width()
            height = int(width * 3 / 4)

        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(path, width, height)

        image = Gtk.Image()
        image.set_from_pixbuf(pixbuf)

        align = Gtk.Alignment.new(xalign=0.5,
                                  yalign=0.5,
                                  xscale=1.0,
                                  yscale=1.0)
        align.add(image)
        image.show()
        evbox = Gtk.EventBox()
        evbox.set_size_request(Gdk.Screen.width(),
                               Gdk.Screen.height() - style.GRID_CELL_SIZE)
        evbox.modify_bg(Gtk.StateType.NORMAL,
                        style.COLOR_WHITE.get_gdk_color())
        evbox.add(align)
        align.show()
        self.set_canvas(evbox)
        evbox.show()

    def __realize_cb(self, window):
        self.window_xid = window.get_window().get_xid()

    def _repeat_cb(self, widget):
        self._repeat_tags = not self._repeat_tags

    def _go_cb(self, widget):
        self._text_item.set_expanded(False)
        text = self._text_item.get_text_from_buffer()
        # count_wordcloud is used to set if undo and redo buttons are available
        self._count_wordcloud += 1

        if self._undo_clicked:
            self._count_wordcloud = 1
            self._save_text = []
            self._undo_clicked = False

        self._save_text.append(text)

        if self._count_wordcloud > 0:
            self._copy_button.set_sensitive(True)

        if self._count_wordcloud > 1:
            self._undo_button.set_sensitive(True)

        if len(text) > 0:
            self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))

            GObject.idle_add(self._create_image, text)

    def _create_image(self, text):
        fd = open('/tmp/cloud_data.txt', 'w')
        data = json_dump({
            'repeat': self._repeat_tags,
            'layout': self._layout,
            'font': self._font_name,
            'colors': self._color_scheme
        })
        fd.write(data)
        fd.close()
        fd = open('/tmp/cloud_text.txt', 'w')
        fd.write(text)
        fd.close()
        path = os.path.join('/tmp/cloud_large.png')
        try:
            subprocess.check_call(
                [os.path.join(activity.get_bundle_path(), 'wordcloud.py')])
        except subprocess.CalledProcessError as e:
            self.get_window().set_cursor(
                Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))
            alert = NotifyAlert(5)
            alert.props.title = _('WordCloud error')
            logging.error(e)
            logging.error(e.returncode)
            if e.returncode == 255:
                logging.error('STOP WORD ERROR')
                MESSAGE = _('All of your words are "stop words."'
                            ' Please try adding more words.')
            else:
                logging.error('MEMORY ERROR')
                MESSAGE = _('Oops. There was a problem. Please try again.')
            alert.props.msg = MESSAGE
            alert.connect('response', self._remove_alert_cb)
            self.add_alert(alert)
            return

        self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))

        self._show_image(path)

        dsobject = datastore.create()
        dsobject.metadata['title'] = _('Word Cloud')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'image/png'
        dsobject.set_file_path(path)
        datastore.write(dsobject)
        dsobject.destroy()

    def _remove_alert_cb(self, alert, response_id):
        self.remove_alert(alert)

    def _undo_cb(self, button):
        ''' Undo button implementation.
        Can only go back one step'''
        text_buffer = self._save_text[self._count_wordcloud - 2]
        self._redo_button.set_sensitive(True)
        self._text_item.set_text(text_buffer)
        self._undo_button.set_sensitive(False)
        self._save_text_redo.append(self._save_text.pop())
        self._undo_clicked = True

    def _redo_cb(self, button):
        ''' Redo button implementation.
        Disabled if there is nothing to be redone'''
        text_buffer = self._save_text_redo.pop()
        self._text_item.set_text(text_buffer)
        self._redo_button.set_sensitive(False)

    def _copy_cb(self, button):
        text_buffer = self._text_item.get_text_buffer()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        text_buffer.copy_clipboard(clipboard)
        self._paste_button.set_sensitive(True)

    def _paste_cb(self, button):
        text_buffer = self._text_item.get_text_buffer()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        text_buffer.paste_clipboard(clipboard, None, True)

    def _init_font_list(self):
        self._font_list = []
        for f in FONT_CACHE:
            self._font_list.append(f['name'])
        return

    def _setup_font_palette(self):
        self._init_font_list()

        palette_list = []
        for font in sorted(self._font_list):
            palette_list.append({
                'icon':
                FontImage(font.replace(' ', '-')),
                'selected':
                FontImage(font.replace(' ', '-'), selected=True),
                'callback':
                self.__font_selected_cb,
                'label':
                font
            })
        return palette_list

    def __font_selected_cb(self, widget, event, font_name):
        self._font_name = font_name
        self._set_font(font_name)
        return

    def _set_font(self, font):
        for entry in list(self.font_palette_dict.keys()):
            if entry == font:
                self.font_palette_dict[entry]['icon'].hide()
                self.font_palette_dict[entry]['selected'].show()
            else:
                self.font_palette_dict[entry]['icon'].show()
                self.font_palette_dict[entry]['selected'].hide()

    def _setup_color_palette(self):
        palette_list = []
        palette_list.append({
            'icon': ColorImage('xo'),
            'selected': ColorImage('xo', selected=True),
            'callback': self.__color_selected_cb,
            'label': 'XO'
        })
        for color in list(COLOR_SCHEMES.keys()):
            palette_list.append({
                'icon':
                ColorIcon(COLOR_SCHEMES[color]),
                'selected':
                ColorIcon(COLOR_SCHEMES[color], selected=True),
                'callback':
                self.__color_selected_cb,
                'label':
                color
            })
        palette_list.append({
            'icon': ColorImage('random'),
            'selected': ColorImage('random', selected=True),
            'callback': self.__color_selected_cb,
            'label': _('random')
        })

        return palette_list

    def __color_selected_cb(self, widget, event, color):
        self._set_color(color)
        if color == _('random'):
            self._color_scheme = None
        elif color == 'XO':
            self._color_scheme = self._xo_colors
        else:
            self._color_scheme = COLOR_SCHEMES[color]
        return

    def _set_color(self, color):
        for entry in list(self.color_palette_dict.keys()):
            if entry == color:
                self.color_palette_dict[entry]['icon'].hide()
                self.color_palette_dict[entry]['selected'].show()
            else:
                self.color_palette_dict[entry]['icon'].show()
                self.color_palette_dict[entry]['selected'].hide()

    def _setup_layout_palette(self):
        palette_list = []
        for layout in list(LAYOUT_SCHEMES.keys()):
            palette_list.append({
                'icon': LayoutImage(layout),
                'selected': LayoutImage(layout, selected=True),
                'callback': self.__layout_selected_cb,
                'label': layout
            })
        return palette_list

    def __layout_selected_cb(self, widget, event, layout):
        self._set_layout(layout)
        self._layout = LAYOUT_SCHEMES[layout]

    def _set_layout(self, layout):
        for entry in list(self.layout_palette_dict.keys()):
            if entry == layout:
                self.layout_palette_dict[entry]['icon'].hide()
                self.layout_palette_dict[entry]['selected'].show()
            else:
                self.layout_palette_dict[entry]['icon'].show()
                self.layout_palette_dict[entry]['selected'].hide()
    def __init__(self, handle):
        super(VteActivity, self).__init__(handle)

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbar = toolbarbox.toolbar

        activitybutton = ActivityToolbarButton(self)
        toolbar.insert(activitybutton, -1)

        toolbar.insert(Gtk.SeparatorToolItem(), -1)

        # add 'copy' icon from standard toolbar.
        edittoolbar = EditToolbar()
        edittoolbar.copy.set_tooltip(_('Copy selected text to clipboard'))
        edittoolbar.copy.connect('clicked', self._on_copy_clicked_cb)
        edittoolbar.paste.connect('clicked', self._on_paste_clicked_cb)
        # as long as nothing is selected, copy needs to be insensitive.
        edittoolbar.copy.set_sensitive(False)
        edittoolbar.show()
        self._copy_button = edittoolbar.copy

        editbutton = ToolbarButton(page=edittoolbar, icon_name='toolbar-edit')
        toolbar.insert(editbutton, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.insert(separator, -1)

        stopbutton = StopButton(self)
        toolbar.insert(stopbutton, -1)

        # creates vte widget
        self._vte = Vte.Terminal()
        self._vte.set_size(30,5)
        self._vte.set_size_request(200, 300)
        font = 'Monospace 10'
        self._vte.set_font(Pango.FontDescription(font))
        self._vte.drag_dest_set(Gtk.DestDefaults.ALL,
                                [Gtk.TargetEntry.new("text/plain", 0, TARGET_TYPE_TEXT)],
                                Gdk.DragAction.COPY)

        foreground = Gdk.Color.parse('#000000')[1]
        background = Gdk.Color.parse('#E7E7E7')[1]

        try:
            self._vte.set_colors(foreground,
                                 background,
                                 [])

        except TypeError:
            self._vte.set_colors(Gdk.RGBA.from_color(foreground),
                                 Gdk.RGBA.from_color(background),
                                 [])

        self._vte.connect('selection-changed', self._on_selection_changed_cb)
        self._vte.connect('drag_data_received', self._on_drop_cb)

        # ...and its scrollbar
        vtebox = Gtk.HBox()
        vtebox.pack_start(self._vte, True, True, 0)
        self.set_canvas(vtebox)

        vtesb = Gtk.VScrollbar.new(self._vte.get_vadjustment())
        vtebox.pack_start(vtesb, False, False, 0)

        self.show_all()
        # hide the buttons we don't use.

        edittoolbar.undo.hide()
        edittoolbar.redo.hide()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        # the 'sleep 1' works around a bug with the command dying before
        # the vte widget manages to snarf the last bits of its output

        argv = [
            "/bin/sh",
            "-c",
            "python %s; sleep 1" % os.path.join(bundle_path, "app.py")
        ]

        args = (
            Vte.PtyFlags.DEFAULT,
            bundle_path,
            argv,
            ["PYTHONPATH=%s/library" % bundle_path],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None
        )

        if hasattr(self._vte, 'fork_command_full'):
            self._vte.fork_command_full(*args)
        else:
            self._vte.spawn_sync(*args)
class ReadEtextsActivity(activity.Activity):
    def __init__(self, handle):
        "The entry point to the Activity"
        global page
        activity.Activity.__init__(self, handle)

        toolbar_box = ToolbarBox()

        activity_button = CustomActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.edit_toolbar = EditToolbar()
        self.edit_toolbar.undo.props.visible = False
        self.edit_toolbar.redo.props.visible = False
        self.edit_toolbar.separator.props.visible = False
        self.edit_toolbar.copy.set_sensitive(False)
        self.edit_toolbar.copy.connect('clicked', self.edit_toolbar_copy_cb)
        self.edit_toolbar.paste.props.visible = False
        edit_toolbar_button = ToolbarButton(
            page=self.edit_toolbar,
            icon_name='toolbar-edit')
        self.edit_toolbar.show()
        toolbar_box.toolbar.insert(edit_toolbar_button, -1)
        edit_toolbar_button.show()

        view_toolbar = ViewToolbar()
        view_toolbar.connect('go-fullscreen',
                self.view_toolbar_go_fullscreen_cb)
        view_toolbar.zoom_in.connect('clicked', self.zoom_in_cb)
        view_toolbar.zoom_out.connect('clicked', self.zoom_out_cb)
        view_toolbar.show()
        view_toolbar_button = ToolbarButton(
            page=view_toolbar,
            icon_name='toolbar-view')
        toolbar_box.toolbar.insert(view_toolbar_button, -1)
        view_toolbar_button.show()

        self.back = ToolButton('go-previous')
        self.back.set_tooltip(_('Back'))
        self.back.props.sensitive = False
        self.back.connect('clicked', self.go_back_cb)
        toolbar_box.toolbar.insert(self.back, -1)
        self.back.show()

        self.forward = ToolButton('go-next')
        self.forward.set_tooltip(_('Forward'))
        self.forward.props.sensitive = False
        self.forward.connect('clicked', self.go_forward_cb)
        toolbar_box.toolbar.insert(self.forward, -1)
        self.forward.show()

        num_page_item = Gtk.ToolItem()
        self.num_page_entry = Gtk.Entry()
        self.num_page_entry.set_text('0')
        self.num_page_entry.set_alignment(1)
        self.num_page_entry.connect('insert-text',
                               self.num_page_entry_insert_text_cb)
        self.num_page_entry.connect('activate',
                               self.num_page_entry_activate_cb)
        self.num_page_entry.set_width_chars(4)
        num_page_item.add(self.num_page_entry)
        self.num_page_entry.show()
        toolbar_box.toolbar.insert(num_page_item, -1)
        num_page_item.show()

        total_page_item = Gtk.ToolItem()
        self.total_page_label = Gtk.Label()

        self.total_page_label.set_markup("<span foreground='#FFF'" \
                                         " size='14000'></span>")

        self.total_page_label.set_text(' / 0')
        total_page_item.add(self.total_page_label)
        self.total_page_label.show()
        toolbar_box.toolbar.insert(total_page_item, -1)
        total_page_item.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl><Shift>Q'
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show()

        self.scrolled_window = Gtk.ScrolledWindow()
        self.scrolled_window.set_policy(Gtk.PolicyType.NEVER, 
            Gtk.PolicyType.AUTOMATIC)

        self.textview = Gtk.TextView()
        self.textview.set_editable(False)
        self.textview.set_cursor_visible(False)
        self.textview.set_left_margin(50)
        self.textview.connect("key_press_event", self.keypress_cb)

        self.scrolled_window.add(self.textview)
        self.set_canvas(self.scrolled_window)
        self.textview.show()
        self.scrolled_window.show()
        page = 0
        self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        self.textview.grab_focus()
        self.font_desc = Pango.FontDescription("sans %d" % style.zoom(10))
        self.textview.modify_font(self.font_desc)

        buffer = self.textview.get_buffer()
        self.markset_id = buffer.connect("mark-set", 
            self.mark_set_cb)

    def num_page_entry_insert_text_cb(self, entry, text, length, position):
        if not re.match('[0-9]', text):
            entry.emit_stop_by_name('insert-text')
            return True
        return False

    def num_page_entry_activate_cb(self, entry):
        global page
        if entry.props.text:
            new_page = int(entry.props.text) - 1
        else:
            new_page = 0

        if new_page >= self.total_pages:
            new_page = self.total_pages - 1
        elif new_page < 0:
            new_page = 0

        self.current_page = new_page
        self.set_current_page(new_page)
        self.show_page(new_page)
        entry.props.text = str(new_page + 1)
        self.update_nav_buttons()
        page = new_page

    def update_nav_buttons(self):
        current_page = self.current_page
        self.back.props.sensitive = current_page > 0
        self.forward.props.sensitive = \
            current_page < self.total_pages - 1

        self.num_page_entry.props.text = str(current_page + 1)
        self.total_page_label.props.label = \
            ' / ' + str(self.total_pages)

    def set_total_pages(self, pages):
        self.total_pages = pages

    def set_current_page(self, page):
        self.current_page = page
        self.update_nav_buttons()

    def keypress_cb(self, widget, event):
        "Respond when the user presses one of the arrow keys"
        keyname = Gdk.keyval_name(event.keyval)
        print keyname
        if keyname == 'plus':
            self.font_increase()
            return True
        if keyname == 'minus':
            self.font_decrease()
            return True
        if keyname == 'Page_Up' :
            self.page_previous()
            return True
        if keyname == 'Page_Down':
            self.page_next()
            return True
        if keyname == 'Up' or keyname == 'KP_Up' \
                or keyname == 'KP_Left':
            self.scroll_up()
            return True
        if keyname == 'Down' or keyname == 'KP_Down' \
                or keyname == 'KP_Right':
            self.scroll_down()
            return True
        return False

    def go_back_cb(self, button):
        self.page_previous()

    def go_forward_cb(self, button):
        self.page_next()

    def page_previous(self):
        global page
        page=page - 1
        if page < 0: page = 0
        self.set_current_page(page)
        self.show_page(page)
        v_adjustment = self.scrolled_window.get_vadjustment()
        v_adjustment.set_value(v_adjustment.get_upper() - \
                               v_adjustment.get_page_size())

    def page_next(self):
        global page
        page = page + 1
        if page >= len(self.page_index): page = 0
        self.set_current_page(page)
        self.show_page(page)
        v_adjustment = self.scrolled_window.get_vadjustment()
        v_adjustment.set_value(v_adjustment.get_lower())

    def zoom_in_cb(self,  button):
        self.font_increase()

    def zoom_out_cb(self,  button):
        self.font_decrease()

    def font_decrease(self):
        font_size = self.font_desc.get_size() / 1024
        font_size = font_size - 1
        if font_size < 1:
            font_size = 1
        self.font_desc.set_size(font_size * 1024)
        self.textview.modify_font(self.font_desc)

    def font_increase(self):
        font_size = self.font_desc.get_size() / 1024
        font_size = font_size + 1
        self.font_desc.set_size(font_size * 1024)
        self.textview.modify_font(self.font_desc)

    def mark_set_cb(self, textbuffer, iter, textmark):

        if textbuffer.get_has_selection():
            self.edit_toolbar.copy.set_sensitive(True)
        else:
            self.edit_toolbar.copy.set_sensitive(False)

    def edit_toolbar_copy_cb(self, button):
        textbuffer = self.textview.get_buffer()
        textbuffer.copy_clipboard(self.clipboard)

    def view_toolbar_go_fullscreen_cb(self, view_toolbar):
        self.fullscreen()

    def scroll_down(self):
        v_adjustment = self.scrolled_window.get_vadjustment()
        if v_adjustment.get_value() == v_adjustment.get_upper() - \
                v_adjustment.get_page_size():
            self.page_next()
            return
        if v_adjustment.get_value() < v_adjustment.get_upper() - \
                v_adjustment.get_page_size():
            new_value = v_adjustment.get_value() + \
                v_adjustment.step_increment
            if new_value > v_adjustment.get_upper() \
                - v_adjustment.get_page_size():
                new_value = v_adjustment.get_upper() \
                    - v_adjustment.get_page_size()
            v_adjustment.set_value(new_value)

    def scroll_up(self):
        v_adjustment = self.scrolled_window.get_vadjustment()
        if v_adjustment.get_value() == v_adjustment.get_lower():
            self.page_previous()
            return
        if v_adjustment.get_value() > v_adjustment.get_lower():
            new_value = v_adjustment.get_value() - \
                v_adjustment.step_increment
            if new_value < v_adjustment.get_lower():
                new_value = v_adjustment.get_lower()
            v_adjustment.set_value(new_value)

    def show_page(self, page_number):
        global PAGE_SIZE, current_word
        position = self.page_index[page_number]
        self.etext_file.seek(position)
        linecount = 0
        label_text = '\n\n\n'
        textbuffer = self.textview.get_buffer()
        while linecount < PAGE_SIZE:
            line = self.etext_file.readline()
            label_text = label_text + unicode(line, 'iso-8859-1')
            linecount = linecount + 1
        label_text = label_text + '\n\n\n'
        textbuffer.set_text(label_text)
        self.textview.set_buffer(textbuffer)

    def save_extracted_file(self, zipfile, filename):
        "Extract the file to a temp directory for viewing"
        filebytes = zipfile.read(filename)
        outfn = self.make_new_filename(filename)
        if (outfn == ''):
            return False
        f = open(os.path.join(self.get_activity_root(), 'tmp',  outfn),  'w')
        try:
            f.write(filebytes)
        finally:
            f.close()

    def get_saved_page_number(self):
        global page
        title = self.metadata.get('title', '')
        if title == ''  or not title[len(title)- 1].isdigit():
            page = 0
        else:
            i = len(title) - 1
            newPage = ''
            while (title[i].isdigit() and i > 0):
                newPage = title[i] + newPage
                i = i - 1
            if title[i] == 'P':
                page = int(newPage) - 1
            else:
                # not a page number; maybe a volume number.
                page = 0

    def save_page_number(self):
        global page
        title = self.metadata.get('title', '')
        if title == ''  or not title[len(title)- 1].isdigit():
            title = title + ' P' +  str(page + 1)
        else:
            i = len(title) - 1
            while (title[i].isdigit() and i > 0):
                i = i - 1
            if title[i] == 'P':
                title = title[0:i] + 'P' + str(page + 1)
            else:
                title = title + ' P' + str(page + 1)
        self.metadata['title'] = title

    def read_file(self, filename):
        "Read the Etext file"
        global PAGE_SIZE,  page

        if zipfile.is_zipfile(filename):
            self.zf = zipfile.ZipFile(filename, 'r')
            self.book_files = self.zf.namelist()
            self.save_extracted_file(self.zf, self.book_files[0])
            currentFileName = os.path.join(self.get_activity_root(), \
                    'tmp',  self.book_files[0])
        else:
            currentFileName = filename

        self.etext_file = open(currentFileName,"r")
        self.page_index = [ 0 ]
        pagecount = 0
        linecount = 0
        while self.etext_file:
            line = self.etext_file.readline()
            if not line:
                break
            linecount = linecount + 1
            if linecount >= PAGE_SIZE:
                position = self.etext_file.tell()
                self.page_index.append(position)
                linecount = 0
                pagecount = pagecount + 1
        if filename.endswith(".zip"):
            os.remove(currentFileName)
        self.get_saved_page_number()
        self.show_page(page)
        self.set_total_pages(pagecount + 1)
        self.set_current_page(page)

    def make_new_filename(self, filename):
        partition_tuple = filename.rpartition('/')
        return partition_tuple[2]

    def write_file(self, filename):
        "Save meta data for the file."
        self.metadata['activity'] = self.get_bundle_id()
        self.save_page_number()
Beispiel #7
0
class ConvertActivity(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle, True)

        self.max_participants = 1
        self.dic = {}

        # Canvas
        self._canvas = Gtk.VBox()

        hbox = Gtk.HBox()
        self._liststore = Gtk.ListStore(str)
        self.combo1 = Gtk.ComboBox.new_with_model_and_entry(self._liststore)
        cell = Gtk.CellRendererText()
        self.combo1.pack_start(cell, True)
        self.combo1.set_entry_text_column(0)
        self.combo1.connect('changed', self._call)

        flip_btn = Gtk.Button()
        flip_btn.connect('clicked', self._flip)
        flip_btn.add(Gtk.Image.new_from_file('icons/flip.svg'))

        self.combo2 = Gtk.ComboBox.new_with_model_and_entry(self._liststore)
        cell = Gtk.CellRendererText()
        self.combo2.pack_start(cell, True)
        self.combo2.set_entry_text_column(0)
        self.combo2.connect('changed', self._call)

        self.label_box = Gtk.HBox()

        self.adjustment = Gtk.Adjustment(1.0, 0, 10.00**10.00, 1.0, 1.0, 0)
        self.spin = Gtk.SpinButton()
        self.spin.set_adjustment(self.adjustment)
        self.spin.set_numeric(True)

        self.label = Gtk.Label()
        self.label._size = 12
        self.label.set_selectable(True)
        self.label.connect('draw', self.resize_label)

        self.convert_btn = Gtk.Button(_('Convert'))
        self.convert_btn.connect('clicked', self._call)

        self._canvas.pack_start(hbox, False, False, 20)
        hbox.pack_start(self.combo1, False, True, 20)
        hbox.pack_start(flip_btn, True, False, 20)
        hbox.pack_end(self.combo2, False, True, 20)
        spin_box = Gtk.HBox()
        convert_box = Gtk.HBox()
        convert_box.pack_start(spin_box, True, False, 0)
        spin_box.pack_start(self.spin, False, False, 0)
        self._canvas.pack_start(convert_box, False, False, 5)
        self._canvas.pack_start(self.label_box, True, False, 0)
        self.label_box.add(self.label)
        spin_box.pack_start(self.convert_btn, False, False, 20)

        self.set_canvas(self._canvas)

        # Toolbar
        toolbarbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)

        toolbarbox.toolbar.insert(activity_button, 0)

        separator = Gtk.SeparatorToolItem()
        separator.set_expand(False)
        separator.set_draw(True)
        toolbarbox.toolbar.insert(separator, -1)

        self._edit_toolbar = EditToolbar()
        self._edit_toolbar.undo.props.visible = False
        self._edit_toolbar.redo.props.visible = False
        self._edit_toolbar.separator.props.visible = False
        self._edit_toolbar.copy.set_sensitive = False
        self._edit_toolbar.copy.connect('clicked', self._edit_copy_cb)

        edit_toolbar_button = ToolbarButton(page=self._edit_toolbar,
                                            icon_name='toolbar-edit')
        edit_toolbar_button.props.label = _('Edit')

        self._edit_toolbar.show()
        edit_toolbar_button.show()
        toolbarbox.toolbar.insert(edit_toolbar_button, -1)

        # RadioToolButton
        self._length_btn = RadioToolButton()
        self._length_btn.connect('clicked',
                                 lambda w: self._update_combo(convert.length))
        # TRANS: https://en.wikipedia.org/wiki/Length
        self._length_btn.set_tooltip(_('Length'))
        self._length_btn.props.icon_name = 'length'

        self._volume_btn = RadioToolButton()
        self._volume_btn.connect('clicked',
                                 lambda w: self._update_combo(convert.volume))
        # TRANS: https://en.wikipedia.org/wiki/Volume
        self._volume_btn.set_tooltip(_('Volume'))
        self._volume_btn.props.icon_name = 'volume'
        self._volume_btn.props.group = self._length_btn

        self._area_btn = RadioToolButton()
        self._area_btn.connect('clicked',
                               lambda w: self._update_combo(convert.area))
        # TRANS: https://en.wikipedia.org/wiki/Area
        self._area_btn.set_tooltip(_('Area'))
        self._area_btn.props.icon_name = 'area'
        self._area_btn.props.group = self._length_btn

        self._weight_btn = RadioToolButton()
        self._weight_btn.connect('clicked',
                                 lambda w: self._update_combo(convert.weight))
        # TRANS: https://en.wikipedia.org/wiki/Weight
        self._weight_btn.set_tooltip(_('Weight'))
        self._weight_btn.props.icon_name = 'weight'
        self._weight_btn.props.group = self._length_btn

        self._speed_btn = RadioToolButton()
        self._speed_btn.connect('clicked',
                                lambda w: self._update_combo(convert.speed))
        # TRANS: https://en.wikipedia.org/wiki/Speed
        self._speed_btn.set_tooltip(_('Speed'))
        self._speed_btn.props.icon_name = 'speed'
        self._speed_btn.props.group = self._length_btn

        self._time_btn = RadioToolButton()
        self._time_btn.connect('clicked',
                               lambda w: self._update_combo(convert.time))
        # TRANS: https://en.wikipedia.org/wiki/Time
        self._time_btn.set_tooltip(_('Time'))
        self._time_btn.props.icon_name = 'time'
        self._time_btn.props.group = self._length_btn

        self._temp_btn = RadioToolButton()
        self._temp_btn.connect('clicked',
                               lambda w: self._update_combo(convert.temp))
        # TRANS: https://en.wikipedia.org/wiki/Temperature
        self._temp_btn.set_tooltip(_('Temperature'))
        self._temp_btn.props.icon_name = 'temp'
        self._temp_btn.props.group = self._length_btn

        toolbarbox.toolbar.insert(self._length_btn, -1)
        toolbarbox.toolbar.insert(self._volume_btn, -1)
        toolbarbox.toolbar.insert(self._area_btn, -1)
        toolbarbox.toolbar.insert(self._weight_btn, -1)
        toolbarbox.toolbar.insert(self._speed_btn, -1)
        toolbarbox.toolbar.insert(self._time_btn, -1)
        toolbarbox.toolbar.insert(self._temp_btn, -1)

        separator = Gtk.SeparatorToolItem()
        separator.set_expand(True)
        separator.set_draw(False)
        toolbarbox.toolbar.insert(separator, -1)

        stopbtn = StopButton(self)
        toolbarbox.toolbar.insert(stopbtn, -1)

        self.set_toolbar_box(toolbarbox)
        self._update_combo(convert.length)
        self.show_all()

    def _edit_copy_cb(self, button):
        self.label.get_text()

    def _update_label(self):
        try:
            spin_value = str(self.spin.get_value())
            decimals = str(len(spin_value.split('.')[-1]))
            fmt = '%.' + decimals + 'f'
            new_value = locale.format(fmt, float(spin_value))

            convert_value = str(self.convert())
            decimals = str(len(convert_value.split('.')[-1]))
            fmt = '%.' + decimals + 'f'
            new_convert = locale.format(fmt, float(convert_value))

            text = '%s ~ %s' % (new_value, new_convert)
            self.label.set_text(text)
        except KeyError:
            pass

    def _call(self, widget=None):
        self._update_label()
        self.show_all()

    def _update_combo(self, data):
        self._liststore.clear()
        self.dic = data
        keys = self.dic.keys()
        keys.sort()
        for x in keys:
            symbol = ''
            if len(self.dic[x]) == 3:
                symbol = self.dic[x][-1]
                symbol = '<sup><b>%s</b></sup>' % symbol

            self._liststore.append(['%s%s' % (x, symbol)])
        self.combo1.set_active(-1)
        self.combo2.set_active(-1)
        self._call()
        self.show_all()

    def _get_active_text(self, combobox):
        active = combobox.get_active()
        keys = self.dic.keys()
        keys.sort()
        if active < 0:
            active = 0
        text = keys[active]
        if '<sup>' in text:
            text = text.split('<b>')[1].split('</b>')[0]
        return text

    def _flip(self, widget):
        active_combo1 = self.combo1.get_active()
        active_combo2 = self.combo2.get_active()
        self.combo1.set_active(active_combo2)
        self.combo2.set_active(active_combo1)
        value = float(self.label.get_text().split(' ~ ')[1].replace(',', '.'))
        self.spin.set_value(value)
        self._call()

    def resize_label(self, widget, event):
        num_label = len(self.label.get_text())
        try:
            size = str((60 * SCREEN_WIDTH / 100) / num_label)
            if not size == self.label._size:
                self.label.modify_font(Pango.FontDescription(size))
                self.label._size = size
        except ZeroDivisionError:
            pass

    def convert(self):
        number = float(self.spin.get_text().replace(',', '.'))
        unit = self._get_active_text(self.combo1)
        to_unit = self._get_active_text(self.combo2)
        return convert.convert(number, unit, to_unit, self.dic)
Beispiel #8
0
class WordCloudActivity(activity.Activity):

    def __init__(self, handle):
        """Set up the HelloWorld activity."""
        activity.Activity.__init__(self, handle)

        self.connect('realize', self.__realize_cb)

        self.max_participants = 1  # No sharing

        self._font_name = None
        self._layout = LAYOUT_RANDOM
        self._xo_colors = (_rgb(profile.get_color().to_string().split(',')[0]),
                           _rgb(profile.get_color().to_string().split(',')[1]))
        self._color_scheme = self._xo_colors
        self._repeat_tags = False

        self._toolbox = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        self._toolbox.toolbar.insert(self.activity_button, 0)
        self.activity_button.show()

        self.set_toolbar_box(self._toolbox)
        self._toolbox.show()
        self.toolbar = self._toolbox.toolbar

        self._edit_toolbar = EditToolbar()
        button = ToolbarButton()
        button.set_page(self._edit_toolbar)
        button.props.icon_name = 'toolbar-edit'
        button.props.label = _('Edit')
        self._toolbox.toolbar.insert(button, -1)
        button.show()
        self._edit_toolbar.show()

        # self._edit_toolbar.undo.connect('clicked', self._undo_cb)
        # self._edit_toolbar.redo.connect('clicked', self._redo_cb)
        self._edit_toolbar.undo.hide()
        self._edit_toolbar.redo.hide()
        self._edit_toolbar.copy.connect('clicked', self._copy_cb)
        self._edit_toolbar.paste.connect('clicked', self._paste_cb)

        go_button = ToolButton('generate-cloud')
        self._toolbox.toolbar.insert(go_button, -1)
        go_button.set_tooltip(_('Create the cloud'))
        go_button.show()
        go_button.connect('clicked', self._go_cb)

        self._text_item = TextItem(self)
        self._toolbox.toolbar.insert(self._text_item, -1)
        self._text_item.show()
        text = self._read_metadata('text')
        if text is not None:
            self._text_item.set_text(text)

        self._repeat_button = ToggleToolButton('repeat-cloud')
        self._toolbox.toolbar.insert(self._repeat_button, -1)
        self._repeat_button.set_tooltip(_('Repeat words'))
        self._repeat_button.show()
        self._repeat_button.connect('clicked', self._repeat_cb)

        self.font_palette_content, self.font_palette_dict = \
            set_palette_list(
                self._setup_font_palette(), 3, 7,
                style.SMALL_ICON_SIZE + style.DEFAULT_SPACING +
                style.DEFAULT_PADDING, return_dict=True)
        self._font_button = FontToolItem(self)
        self.font_palette_content.show()
        self._toolbox.toolbar.insert(self._font_button, -1)
        self._font_button.show()

        self.color_palette_content, self.color_palette_dict = \
            set_palette_list(
                self._setup_color_palette(), 3, 5,
                style.GRID_CELL_SIZE + style.DEFAULT_SPACING +
                style.DEFAULT_PADDING, return_dict=True)
        self._color_button = ColorToolItem(self)
        self.color_palette_content.show()
        self._toolbox.toolbar.insert(self._color_button, -1)
        self._color_button.show()

        self.layout_palette_content, self.layout_palette_dict = \
            set_palette_list(self._setup_layout_palette(), 1, 5,
                             style.GRID_CELL_SIZE + style.DEFAULT_SPACING +
                             style.DEFAULT_PADDING, return_dict=True)
        self._layout_button = LayoutToolItem(self)
        self.layout_palette_content.show()
        self._toolbox.toolbar.insert(self._layout_button, -1)
        self._layout_button.show()

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        self._toolbox.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        self._toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        self._show_image(os.path.join(
            activity.get_bundle_path(), 'WordCloud.png'))

        self._set_color('XO')
        self._set_font('Droid Sans')

        for layout in LAYOUT_SCHEMES.keys():
            if LAYOUT_SCHEMES[layout] == self._layout:
                self._set_layout(layout)
                break

    def _read_metadata(self, keyword, default_value=None):
        ''' If the keyword is found, return stored value '''
        if keyword in self.metadata:
            return(self.metadata[keyword])
        else:
            return(default_value)

    def write_file(self, file_path):
        self.metadata['text'] = self._text_item.get_text_from_buffer()

    def _show_image(self, path):
        if Gdk.Screen.height() < Gdk.Screen.width():
            height = Gdk.Screen.height() - style.GRID_CELL_SIZE
            width = int(height * 4 / 3)
        else:
            width = Gdk.Screen.width()
            height = int(width * 3 / 4)

        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path, width, height)

        image = Gtk.Image()
        image.set_from_pixbuf(pixbuf)

        align = Gtk.Alignment.new(xalign=0.5, yalign=0.5, xscale=1.0,
                                  yscale=1.0)
        align.add(image)
        image.show()
        evbox = Gtk.EventBox()
        evbox.set_size_request(Gdk.Screen.width(),
                               Gdk.Screen.height() - style.GRID_CELL_SIZE)
        evbox.modify_bg(
            Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color())
        evbox.add(align)
        align.show()
        self.set_canvas(evbox)
        evbox.show()

    def __realize_cb(self, window):
        self.window_xid = window.get_window().get_xid()

    def _repeat_cb(self, widget):
        self._repeat_tags = not self._repeat_tags

    def _go_cb(self, widget):
        self._text_item.set_expanded(False)
        text = self._text_item.get_text_from_buffer()
        if len(text) > 0:
            self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))

            GObject.idle_add(self._create_image, text)

    def _create_image(self, text):
        fd = open('/tmp/cloud_data.txt', 'w')
        data = json_dump({'repeat': self._repeat_tags,
                          'layout': self._layout,
                          'font': self._font_name,
                          'colors': self._color_scheme})
        fd.write(data)
        fd.close()
        fd = open('/tmp/cloud_text.txt', 'w')
        fd.write(text)
        fd.close()
        path = os.path.join('/tmp/cloud_large.png')
        try:
            subprocess.check_call(
                [os.path.join(activity.get_bundle_path(), 'wordcloud.py')])
        except subprocess.CalledProcessError as e:
            self.get_window().set_cursor(
                Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))
            alert = NotifyAlert(5)
            alert.props.title = _('WordCloud error')
            logging.error(e)
            logging.error(e.returncode)
            if e.returncode == 255:
                logging.error('STOP WORD ERROR')
                MESSAGE = _('All of your words are "stop words."'
                            ' Please try adding more words.')
            else:
                logging.error('MEMORY ERROR')
                MESSAGE = _('Oops. There was a problem. Please try again.')
            alert.props.msg = MESSAGE
            alert.connect('response', self._remove_alert_cb)
            self.add_alert(alert)
            return

        self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))

        self._show_image(path)

        dsobject = datastore.create()
        dsobject.metadata['title'] = _('Word Cloud')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'image/png'
        dsobject.set_file_path(path)
        datastore.write(dsobject)
        dsobject.destroy()

    def _remove_alert_cb(self, alert, response_id):
        self.remove_alert(alert)

    def _undo_cb(self, butston):
        text_buffer = self._text_item.get_text_buffer()
        if text_buffer.can_undo():
            text_buffer.undo()

    def _redo_cb(self, button):
        text_buffer = self._text_item.get_text_buffer()
        if text_buffer.can_redo():
            text_buffer.redo()

    def _copy_cb(self, button):
        text_buffer = self._text_item.get_text_buffer()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        text_buffer.copy_clipboard(clipboard)

    def _paste_cb(self, button):
        text_buffer = self._text_item.get_text_buffer()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        text_buffer.paste_clipboard(
            clipboard, None, True)

    def _init_font_list(self):
        self._font_list = []
        for f in FONT_CACHE:
            self._font_list.append(f['name'].encode('utf-8'))
        return

    def _setup_font_palette(self):
        self._init_font_list()

        palette_list = []
        for font in sorted(self._font_list):
            palette_list.append({'icon': FontImage(font.replace(' ', '-')),
                                 'selected': FontImage(font.replace(' ', '-'),
                                                       selected=True),
                                 'callback': self.__font_selected_cb,
                                 'label': font})
        return palette_list

    def __font_selected_cb(self, widget, event, font_name):
        self._font_name = font_name
        self._set_font(font_name)
        return

    def _set_font(self, font):
        for entry in self.font_palette_dict.keys():
            if entry == font:
                self.font_palette_dict[entry]['icon'].hide()
                self.font_palette_dict[entry]['selected'].show()
            else:
                self.font_palette_dict[entry]['icon'].show()
                self.font_palette_dict[entry]['selected'].hide()

    def _setup_color_palette(self):
        palette_list = []
        palette_list.append({'icon': ColorImage('xo'),
                             'selected': ColorImage('xo', selected=True),
                             'callback': self.__color_selected_cb,
                             'label': 'XO'})
        for color in COLOR_SCHEMES.keys():
            palette_list.append({'icon': ColorIcon(COLOR_SCHEMES[color]),
                                 'selected': ColorIcon(
                                     COLOR_SCHEMES[color], selected=True),
                                 'callback': self.__color_selected_cb,
                                 'label': color})
        palette_list.append({'icon': ColorImage('random'),
                             'selected': ColorImage('random', selected=True),
                             'callback': self.__color_selected_cb,
                             'label': _('random')})

        return palette_list

    def __color_selected_cb(self, widget, event, color):
        self._set_color(color)
        if color == _('random'):
            self._color_scheme = None
        elif color == 'XO':
            self._color_scheme = self._xo_colors
        else:
            self._color_scheme = COLOR_SCHEMES[color]
        return

    def _set_color(self, color):
        for entry in self.color_palette_dict.keys():
            if entry == color:
                self.color_palette_dict[entry]['icon'].hide()
                self.color_palette_dict[entry]['selected'].show()
            else:
                self.color_palette_dict[entry]['icon'].show()
                self.color_palette_dict[entry]['selected'].hide()

    def _setup_layout_palette(self):
        palette_list = []
        for layout in LAYOUT_SCHEMES.keys():
            palette_list.append({'icon': LayoutImage(layout),
                                 'selected': LayoutImage(layout,
                                                         selected=True),
                                 'callback': self.__layout_selected_cb,
                                 'label': layout})
        return palette_list

    def __layout_selected_cb(self, widget, event, layout):
        self._set_layout(layout)
        self._layout = LAYOUT_SCHEMES[layout]

    def _set_layout(self, layout):
        for entry in self.layout_palette_dict.keys():
            if entry == layout:
                self.layout_palette_dict[entry]['icon'].hide()
                self.layout_palette_dict[entry]['selected'].show()
            else:
                self.layout_palette_dict[entry]['icon'].show()
                self.layout_palette_dict[entry]['selected'].hide()