Example #1
0
    def add_view(self, widget):
        if len(self._view_icons) >= 5:
            for x in self.activity._alerts:
                self.activity.remove_alert(x)
            alert = NotifyAlert(10)
            alert.props.title = _('Limit reached')
            alert.props.msg = _('You have reached the maximum limit of '
                                'favorites views, please delete some before '
                                'continuing.')
            self.activity.add_alert(alert)
            alert.connect('response',
                          lambda x, y: self.activity.remove_alert(x))
            return

        current = len(self._view_buttons) + 1
        label = _('Favorites view %d') % current
        button = ToolbarButton(label=label, icon_name='view-radial')
        page = FavoritePage(button, self, 'view-radial', 'emblem-favorite',
                            label)
        button.set_page(page)

        self._view_icons[button] = 'view-radial'
        self._favorite_icons[button] = 'emblem-favorite'
        self._view_buttons[button] = button
        if self.favorite_names_enabled:
            self._favorite_names[button] = label

        self.insert(button, -1)
        self.save_to_gconf()
        self.show_all()
Example #2
0
    def add_view(self, widget):
        if len(self._view_icons) >= 5:
            for x in self.activity._alerts:
                self.activity.remove_alert(x)
            alert = NotifyAlert(10)
            alert.props.title = _('Limit reached')
            alert.props.msg = _('You have reached the maximum limit of '
                                'favorites views, please delete some before '
                                'continuing.')
            self.activity.add_alert(alert)
            alert.connect('response',
                          lambda x, y: self.activity.remove_alert(x))
            return

        current = len(self._view_buttons) + 1
        label = _('Favorites view %d') % current
        button = ToolbarButton(label=label, icon_name='view-radial')
        page = FavoritePage(button, self, 'view-radial', 'emblem-favorite',
                            label)
        button.set_page(page)

        self._view_icons[button] = 'view-radial'
        self._favorite_icons[button] = 'emblem-favorite'
        self._view_buttons[button] = button
        self._favorite_names[button] = label

        self.insert(button, -1)
        self.save_to_gsettings()
        self.show_all()
Example #3
0
    def __init__(self, handle):

        if not hasattr(self, 'confvars'):
            self.confvars = read_conf_from_info(get_bundle_path())

        logging.error("Starting server database: %s port: %s" %
                      (self.confvars['path'], self.confvars['port']))

        os.chdir(os.environ['SUGAR_BUNDLE_PATH'])

        self.confvars['ip'] = '0.0.0.0'

        server.run_server(self.confvars)

        handle.uri = 'http://%s:%s%s' % (
            self.confvars['ip'], self.confvars['port'],
            self.confvars['home_page'])

        webactivity.WebActivity.__init__(self, handle)

        if USE_GTK2:
            # Use xpcom to set a RAM cache limit.  (Trac #7081.)
            from xpcom import components
            from xpcom.components import interfaces
            cls = components.classes['@mozilla.org/preferences-service;1']
            pref_service = cls.getService(interfaces.nsIPrefService)
            branch = pref_service.getBranch("browser.cache.memory.")
            branch.setIntPref("capacity", "5000")

            # Use xpcom to turn off "offline mode" detection, which disables
            # access to localhost for no good reason.  (Trac #6250.)
            ios_class = components.classes["@mozilla.org/network/io-service;1"]
            io_service = ios_class.getService(interfaces.nsIIOService2)
            io_service.manageOfflineStatus = False

        self.searchtoolbar = SearchToolbar(self)
        search_toolbar_button = ToolbarButton()
        search_toolbar_button.set_page(self.searchtoolbar)
        search_toolbar_button.props.icon_name = 'search-wiki'
        search_toolbar_button.props.label = _('Search')
        self.get_toolbar_box().toolbar.insert(search_toolbar_button, 1)
        search_toolbar_button.show()
        # Hide add-tabs button
        if hasattr(self._primary_toolbar, '_add_tab'):
            self._primary_toolbar._add_tab.hide()

        self.searchtoolbar.show()
Example #4
0
    def load_views(self):
        client = GConf.Client.get_default()
        options = client.get(_FAVORITE_KEY)
        options2 = client.get(_VIEW_KEY)
        options3 = client.get(_FAVORITE_NAME_KEY)

        view_icons = []
        favorites_icons = []
        favorite_names = []

        if options is not None and options2 is not None and \
                options3 is not None:
            for gval in options.get_list():
                favorites_icons.append(gval.get_string())

            for gval in options2.get_list():
                view_icons.append(gval.get_string())

            for gval in options3.get_list():
                favorite_names.append(gval.get_string())

        current = 0
        for view_icon in view_icons:
            if self.favorite_names_enabled:
                try:
                    label = favorite_names[current]
                except IndexError:
                    label = _('Favorites view %d') % (current + 1)
            else:
                label = _('Favorites view %d') % (current + 1)

            button = ToolbarButton(label=label, icon_name=view_icon)
            page = FavoritePage(button, self, view_icon,
                                favorites_icons[current], label)
            button.set_page(page)
            self.insert(button, -1)
            self._view_icons[button] = view_icon
            self._favorite_icons[button] = favorites_icons[current]
            self._view_buttons[button] = button
            self._favorite_names[button] = label
            current += 1
Example #5
0
    def load_views(self):
        settings = Gio.Settings(_DESKTOP_CONF_DIR)
        data = settings.get_value('homeviews').unpack()

        current = 0
        for view in data:
            label = _('Favorites view %d') % (current + 1)

            print view, data
            view_icon = view['view-icon']
            favorite_icon = view['favorite-icon']

            button = ToolbarButton(label=label, icon_name=view_icon)
            page = FavoritePage(button, self, view_icon, favorite_icon, label)
            button.set_page(page)
            self.insert(button, -1)
            self._view_icons[button] = view_icon
            self._favorite_icons[button] = favorite_icon
            self._view_buttons[button] = button
            self._favorite_names[button] = label
            current += 1
Example #6
0
    def load_views(self):
        settings = Gio.Settings(_DESKTOP_CONF_DIR)
        data = settings.get_value('homeviews').unpack()

        current = 0
        for view in data:
            if 'view-label' in view:
                label = view['view-label']
            else:
                label = _('Favorites view %d') % (current + 1)

            view_icon = view['view-icon']
            favorite_icon = view['favorite-icon']

            button = ToolbarButton(label=label, icon_name=view_icon)
            page = FavoritePage(button, self, view_icon, favorite_icon, label)
            button.set_page(page)
            self.insert(button, -1)
            self._view_icons[button] = view_icon
            self._favorite_icons[button] = favorite_icon
            self._view_buttons[button] = button
            self._favorite_names[button] = label
            current += 1
class AbiWordActivity(activity.Activity):

    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        # abiword uses the current directory for all its file dialogs
        os.chdir(os.path.expanduser('~'))

        # create our main abiword canvas
        self.abiword_canvas = DocumentView()
        self._new_instance = True
        toolbar_box = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(self.activity_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.show()
        self.activity_button.props.page.insert(separator, 2)
        ExportButtonFactory(self, self.abiword_canvas)
        self.activity_button.show()

        edit_toolbar = ToolbarButton()
        edit_toolbar.props.page = EditToolbar(self, toolbar_box)
        edit_toolbar.props.icon_name = 'toolbar-edit'
        edit_toolbar.props.label = _('Edit')
        toolbar_box.toolbar.insert(edit_toolbar, -1)

        view_toolbar = ToolbarButton()
        view_toolbar.props.page = ViewToolbar(self.abiword_canvas)
        view_toolbar.props.icon_name = 'toolbar-view'
        view_toolbar.props.label = _('View')
        toolbar_box.toolbar.insert(view_toolbar, -1)

        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if self.abiword_canvas.get_version() != '3.0':
            self.speech_toolbar_button = ToolbarButton(icon_name='speak')
            toolbar_box.toolbar.insert(self.speech_toolbar_button, -1)
            self._init_speech()

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        text_toolbar = ToolbarButton()
        text_toolbar.props.page = TextToolbar(self.abiword_canvas)
        text_toolbar.props.icon_name = 'format-text'
        text_toolbar.props.label = _('Text')
        toolbar_box.toolbar.insert(text_toolbar, -1)

        para_toolbar = ToolbarButton()
        para_toolbar.props.page = ParagraphToolbar(self.abiword_canvas)
        para_toolbar.props.icon_name = 'paragraph-bar'
        para_toolbar.props.label = _('Paragraph')
        toolbar_box.toolbar.insert(para_toolbar, -1)

        insert_toolbar = ToolbarButton()
        insert_toolbar.props.page = InsertToolbar(self.abiword_canvas)
        insert_toolbar.props.icon_name = 'insert-table'
        insert_toolbar.props.label = _('Table')
        toolbar_box.toolbar.insert(insert_toolbar, -1)

        image = ToolButton('insert-picture')
        image.set_tooltip(_('Insert Image'))
        self._image_id = image.connect('clicked', self._image_cb)
        toolbar_box.toolbar.insert(image, -1)

        palette = image.get_palette()
        content_box = Gtk.VBox()
        palette.set_content(content_box)
        image_floating_checkbutton = Gtk.CheckButton(_('Floating'))
        image_floating_checkbutton.connect(
            'toggled', self._image_floating_checkbutton_toggled_cb)
        content_box.pack_start(image_floating_checkbutton, True, True, 0)
        content_box.show_all()
        self.floating_image = False

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

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)

        toolbar_box.show_all()
        self.set_toolbar_box(toolbar_box)

        # add a overlay to be able to show a icon while joining a shared doc
        overlay = Gtk.Overlay()
        overlay.add(self.abiword_canvas)
        overlay.show()

        self._connecting_box = ConnectingBox()
        overlay.add_overlay(self._connecting_box)

        self.set_canvas(overlay)

        # we want a nice border so we can select paragraphs easily
        self.abiword_canvas.set_show_margin(True)

        # Read default font face and size
        client = GConf.Client.get_default()
        self._default_font_face = client.get_string(
            '/desktop/sugar/activities/write/font_face')
        if not self._default_font_face:
            self._default_font_face = 'Sans'
        self._default_font_size = client.get_int(
            '/desktop/sugar/activities/write/font_size')
        if self._default_font_size == 0:
            self._default_font_size = 12

        # activity sharing
        self.participants = {}
        self.joined = False

        self.connect('shared', self._shared_cb)

        if self.shared_activity:
            # we are joining the activity
            logger.error('We are joining an activity')
            # display a icon while joining
            self._connecting_box.show()
            # disable the abi widget
            self.abiword_canvas.set_sensitive(False)
            self._new_instance = False
            self.connect('joined', self._joined_cb)
            self.shared_activity.connect('buddy-joined',
                                         self._buddy_joined_cb)
            self.shared_activity.connect('buddy-left', self._buddy_left_cb)
            if self.get_shared():
                self._joined_cb(self)
        else:
            # we are creating the activity
            logger.error("We are creating an activity")

        self.abiword_canvas.zoom_width()
        self.abiword_canvas.show()
        self.connect_after('map-event', self.__map_activity_event_cb)

        self.abiword_canvas.connect('size-allocate', self.size_allocate_cb)

    def _init_speech(self):
        import speech
        from speechtoolbar import SpeechToolbar
        if speech.supported:
            self.speech_toolbar = SpeechToolbar(self)
            self.speech_toolbar_button.set_page(self.speech_toolbar)
            self.speech_toolbar_button.show()

    def size_allocate_cb(self, abi, alloc):
        GObject.idle_add(abi.queue_draw)

    def __map_activity_event_cb(self, event, activity):
        # set custom keybindings for Write
        # we do it later because have problems if done before - OLPC #11049
        logger.error('Loading keybindings')
        keybindings_file = os.path.join(get_bundle_path(), 'keybindings.xml')
        self.abiword_canvas.invoke_ex(
            'com.abisource.abiword.loadbindings.fromURI',
            keybindings_file, 0, 0)
        # set default font
        if self._new_instance:
            self.abiword_canvas.select_all()
            logging.error('Setting default font to %s %d in new documents',
                          self._default_font_face, self._default_font_size)
            self.abiword_canvas.set_font_name(self._default_font_face)
            self.abiword_canvas.set_font_size(str(self._default_font_size))
            self.abiword_canvas.moveto_bod()
            self.abiword_canvas.select_bod()
        if hasattr(self.abiword_canvas, 'toggle_rulers'):
            # this is not available yet on upstream abiword
            self.abiword_canvas.view_print_layout()
            self.abiword_canvas.toggle_rulers(False)

        self.abiword_canvas.grab_focus()

    def get_preview(self):
        if not hasattr(self.abiword_canvas, 'render_page_to_image'):
            return activity.Activity.get_preview(self)

        from gi.repository import GdkPixbuf

        pixbuf = self.abiword_canvas.render_page_to_image(1)
        pixbuf = pixbuf.scale_simple(style.zoom(300), style.zoom(225),
                                     GdkPixbuf.InterpType.BILINEAR)

        preview_data = []

        def save_func(buf, lenght, data):
            data.append(buf)
            return True

        pixbuf.save_to_callbackv(save_func, preview_data, 'png', [], [])
        preview_data = ''.join(preview_data)

        return preview_data

    def _shared_cb(self, activity):
        logger.error('My Write activity was shared')
        self._sharing_setup()

        self.shared_activity.connect('buddy-joined', self._buddy_joined_cb)
        self.shared_activity.connect('buddy-left', self._buddy_left_cb)

        channel = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES]
        logger.error('This is my activity: offering a tube...')
        id = channel.OfferDBusTube('com.abisource.abiword.abicollab', {})
        logger.error('Tube address: %s', channel.GetDBusTubeAddress(id))

    def _sharing_setup(self):
        logger.debug("_sharing_setup()")

        if self.shared_activity is None:
            logger.error('Failed to share or join activity')
            return

        self.conn = self.shared_activity.telepathy_conn
        self.tubes_chan = self.shared_activity.telepathy_tubes_chan
        self.text_chan = self.shared_activity.telepathy_text_chan
        self.tube_id = None
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal(
            'NewTube', self._new_tube_cb)

    def _list_tubes_reply_cb(self, tubes):
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        logger.error('ListTubes() failed: %s', e)

    def _joined_cb(self, activity):
        logger.error("_joined_cb()")
        if not self.shared_activity:
            self._enable_collaboration()
            return

        self.joined = True
        logger.error('Joined an existing Write session')
        self._sharing_setup()

        logger.error('This is not my activity: waiting for a tube...')
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes(
            reply_handler=self._list_tubes_reply_cb,
            error_handler=self._list_tubes_error_cb)
        self._enable_collaboration()

    def _enable_collaboration(self):
        """
        when communication established, hide the download icon
        and enable the abi widget
        """
        self.abiword_canvas.zoom_width()
        self.abiword_canvas.set_sensitive(True)
        self._connecting_box.hide()

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        logger.error('New tube: ID=%d initiator=%d type=%d service=%s '
                     'params=%r state=%d', id, initiator, type, service,
                     params, state)

        if self.tube_id is not None:
            # We are already using a tube
            return

        if type != telepathy.TUBE_TYPE_DBUS or \
                service != "com.abisource.abiword.abicollab":
            return

        channel = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES]

        if state == telepathy.TUBE_STATE_LOCAL_PENDING:
            channel.AcceptDBusTube(id)

        # look for the initiator's D-Bus unique name
        initiator_dbus_name = None
        dbus_names = channel.GetDBusNames(id)
        for handle, name in dbus_names:
            if handle == initiator:
                logger.error('found initiator D-Bus name: %s', name)
                initiator_dbus_name = name
                break

        if initiator_dbus_name is None:
            logger.error('Unable to get the D-Bus name of the tube initiator')
            return

        cmd_prefix = 'com.abisource.abiword.abicollab.olpc.'
        # pass this tube to abicollab
        address = channel.GetDBusTubeAddress(id)
        if self.joined:
            logger.error('Passing tube address to abicollab (join): %s',
                         address)
            self.abiword_canvas.invoke_ex(cmd_prefix + 'joinTube',
                                          address, 0, 0)
            # The intiator of the session has to be the first passed
            # to the Abicollab backend.
            logger.error('Adding the initiator to the session: %s',
                         initiator_dbus_name)
            self.abiword_canvas.invoke_ex(cmd_prefix + 'buddyJoined',
                                          initiator_dbus_name, 0, 0)
        else:
            logger.error('Passing tube address to abicollab (offer): %s',
                         address)
            self.abiword_canvas.invoke_ex(cmd_prefix + 'offerTube', address,
                                          0, 0)
        self.tube_id = id

        channel.connect_to_signal('DBusNamesChanged',
                                  self._on_dbus_names_changed)

        self._on_dbus_names_changed(id, dbus_names, [])

    def _on_dbus_names_changed(self, tube_id, added, removed):
        """
        We call com.abisource.abiword.abicollab.olpc.buddy{Joined,Left}
        according members of the D-Bus tube. That's why we don't add/remove
        buddies in _buddy_{joined,left}_cb.
        """
        logger.error('_on_dbus_names_changed')
#        if tube_id == self.tube_id:
        cmd_prefix = 'com.abisource.abiword.abicollab.olpc'
        for handle, bus_name in added:
            logger.error('added handle: %s, with dbus_name: %s',
                         handle, bus_name)
            self.abiword_canvas.invoke_ex(cmd_prefix + '.buddyJoined',
                                          bus_name, 0, 0)
            self.participants[handle] = bus_name

    def _on_members_changed(self, message, added, removed, local_pending,
                            remote_pending, actor, reason):
        logger.error("_on_members_changed")
        for handle in removed:
            bus_name = self.participants.pop(handle, None)
            if bus_name is None:
                # FIXME: that shouldn't happen so probably hide another bug.
                # Should be investigated
                continue

            cmd_prefix = 'com.abisource.abiword.abicollab.olpc'
            logger.error('removed handle: %d, with dbus name: %s', handle,
                         bus_name)
            self.abiword_canvas.invoke_ex(cmd_prefix + '.buddyLeft',
                                          bus_name, 0, 0)

    def _buddy_joined_cb(self, activity, buddy):
        logger.error('buddy joined with object path: %s', buddy.object_path())

    def _buddy_left_cb(self, activity, buddy):
        logger.error('buddy left with object path: %s', buddy.object_path())

    def read_file(self, file_path):
        logging.debug('AbiWordActivity.read_file: %s, mimetype: %s',
                      file_path, self.metadata['mime_type'])
        if self._is_plain_text(self.metadata['mime_type']):
            self.abiword_canvas.load_file('file://' + file_path, 'text/plain')
        else:
            # we pass no mime/file type, let libabiword autodetect it,
            # so we can handle multiple file formats
            self.abiword_canvas.load_file('file://' + file_path, '')
        self.abiword_canvas.zoom_width()
        self._new_instance = False

    def write_file(self, file_path):
        logging.debug('AbiWordActivity.write_file: %s, mimetype: %s',
                      file_path, self.metadata['mime_type'])
        # if we were editing a text file save as plain text
        if self._is_plain_text(self.metadata['mime_type']):
            logger.debug('Writing file as type source (text/plain)')
            self.abiword_canvas.save('file://' + file_path, 'text/plain', '')
        else:
            #if the file is new, save in .odt format
            if self.metadata['mime_type'] == '':
                self.metadata['mime_type'] = 'application/rtf'

            # Abiword can't save in .doc format, save in .rtf instead
            if self.metadata['mime_type'] == 'application/msword':
                self.metadata['mime_type'] = 'application/rtf'

            self.abiword_canvas.save('file://' + file_path,
                                     self.metadata['mime_type'], '')

        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if self.abiword_canvas.get_version() != '3.0':
            self.metadata['fulltext'] = self.abiword_canvas.get_content(
                'text/plain', None)[:3000]

    def _is_plain_text(self, mime_type):
        # These types have 'text/plain' in their mime_parents  but we need
        # use it like rich text
        if mime_type in ['application/rtf', 'text/rtf', 'text/html']:
            return False

        from sugar3 import mime

        mime_parents = mime.get_mime_parents(self.metadata['mime_type'])
        return self.metadata['mime_type'] in ['text/plain', 'text/csv'] or \
            'text/plain' in mime_parents

    def _image_floating_checkbutton_toggled_cb(self, checkbutton):
        self.floating_image = checkbutton.get_active()

    def _image_cb(self, button):
        try:
            chooser = ObjectChooser(self, what_filter='Image',
                                    filter_type=FILTER_TYPE_GENERIC_MIME,
                                    show_preview=True)
        except:
            # for compatibility with older versions
            chooser = ObjectChooser(self, what_filter='Image')

        try:
            result = chooser.run()
            if result == Gtk.ResponseType.ACCEPT:
                logging.debug('ObjectChooser: %r',
                              chooser.get_selected_object())
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    self.abiword_canvas.insert_image(jobject.file_path,
                                                     self.floating_image)
        finally:
            chooser.destroy()
            del chooser
Example #8
0
    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
Example #9
0
class ReadActivity(activity.Activity):
    """The Read sugar activity."""
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.max_participants = 1
        self._document = None
        self._fileserver = None
        self._object_id = handle.object_id
        self._toc_model = None
        self.filehash = None

        self.connect('key-press-event', self._key_press_event_cb)
        self.connect('key-release-event', self._key_release_event_cb)

        _logger.debug('Starting Read...')

        self._view = None
        self.dpi = _get_screen_dpi()
        self._bookmark_view = BookmarkView()
        self._bookmark_view.connect('bookmark-changed',
                                    self._update_bookmark_cb)

        tray = HTray()
        self.set_tray(tray, Gtk.PositionType.BOTTOM)

        toolbar_box = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(self.activity_button, 0)
        self.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()

        self._highlight = self._edit_toolbar.highlight
        self._highlight_id = self._highlight.connect('clicked',
                                                     self.__highlight_cb)

        self._view_toolbar = ViewToolbar()
        self._view_toolbar.connect('go-fullscreen',
                                   self.__view_toolbar_go_fullscreen_cb)
        self._view_toolbar.connect('toggle-index-show',
                                   self.__toogle_navigator_cb)
        self._view_toolbar.connect('toggle-tray-show', self.__toogle_tray_cb)
        view_toolbar_button = ToolbarButton(page=self._view_toolbar,
                                            icon_name='toolbar-view')
        self._view_toolbar.show()
        toolbar_box.toolbar.insert(view_toolbar_button, -1)
        view_toolbar_button.show()

        self._back_button = self._create_back_button()
        toolbar_box.toolbar.insert(self._back_button, -1)
        self._back_button.show()

        self._forward_button = self._create_forward_button()
        toolbar_box.toolbar.insert(self._forward_button, -1)
        self._forward_button.show()

        num_page_item = Gtk.ToolItem()
        self._num_page_entry = self._create_search()
        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()
        total_page_item.add(self._total_page_label)
        self._total_page_label.show()
        self._total_page_label.set_margin_right(5)
        toolbar_box.toolbar.insert(total_page_item, -1)
        total_page_item.show()

        self._bookmarker = ToggleToolButton('emblem-favorite')
        self._bookmarker_toggle_handler_id = self._bookmarker.connect(
            'toggled', self.__bookmarker_toggled_cb)
        self._bookmarker.show()
        toolbar_box.toolbar.insert(self._bookmarker, -1)

        self.speech_toolbar_button = ToolbarButton(icon_name='speak')
        toolbar_box.toolbar.insert(self.speech_toolbar_button, -1)

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

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show()

        # This is needed to prevent the call of read_file on
        # canvas map, becuase interact in a bad way with the emptypanel
        # the program takes responsability of this task.
        self._read_file_called = True

        self._vbox = Gtk.VBox()
        self._vbox.show()

        overlay = Gtk.Overlay()

        self._hbox = Gtk.HBox()
        self._hbox.show()
        overlay.add(self._hbox)

        self._bookmark_view.props.halign = Gtk.Align.END
        self._bookmark_view.props.valign = Gtk.Align.START
        # HACK: This is to calculate the scrollbar width
        # defined in sugar-artwork gtk-widgets.css.em
        if style.zoom(1):
            scrollbar_width = 15
        else:
            scrollbar_width = 11

        self._bookmark_view.props.margin_right = scrollbar_width
        overlay.add_overlay(self._bookmark_view)
        overlay.show()
        self._vbox.pack_start(overlay, True, True, 0)
        self.set_canvas(self._vbox)

        self._navigator = self._create_navigator()

        # Set up for idle suspend
        self._idle_timer = 0
        self._service = None

        # start with sleep off
        self._sleep_inhibit = True

        self.unused_download_tubes = set()
        self._want_document = True
        self._download_content_length = 0
        self._download_content_type = None
        # Status of temp file used for write_file:
        self._tempfile = None
        self._close_requested = False

        fname = os.path.join('/etc', 'inhibit-ebook-sleep')

        if not os.path.exists(fname):
            try:
                bus = dbus.SystemBus()
                proxy = bus.get_object(_HARDWARE_MANAGER_SERVICE,
                                       _HARDWARE_MANAGER_OBJECT_PATH)
                self._service = dbus.Interface(proxy,
                                               _HARDWARE_MANAGER_INTERFACE)
                self._scrolled.props.vadjustment.connect(
                    "value-changed", self._user_action_cb)
                self._scrolled.props.hadjustment.connect(
                    "value-changed", self._user_action_cb)
                self.connect("focus-in-event", self._focus_in_event_cb)
                self.connect("focus-out-event", self._focus_out_event_cb)
                self.connect("notify::active", self._now_active_cb)

                _logger.debug('Suspend on idle enabled')
            except dbus.DBusException:
                _logger.info(
                    'Hardware manager service not found, no idle suspend.')
        else:
            _logger.debug('Suspend on idle disabled')

        self.connect("shared", self._shared_cb)

        h = hash(self._activity_id)
        self.port = 1024 + (h % 64511)

        self._progress_alert = None

        if self._jobject.file_path is not None and \
                self._jobject.file_path != '':
            self.read_file(self._jobject.file_path)
        elif handle.uri:
            self._load_document(handle.uri)
            # TODO: we need trasfer the metadata and uodate
            # bookmarks and urls

        elif self.shared_activity:
            # We're joining
            if self.get_shared():
                # Already joined for some reason, just get the document
                self._joined_cb(self)
            else:
                self._progress_alert = ProgressAlert()
                self._progress_alert.props.title = _('Please wait')
                self._progress_alert.props.msg = _('Starting connection...')
                self.add_alert(self._progress_alert)

                # Wait for a successful join before trying to get the document
                self.connect("joined", self._joined_cb)
        else:
            # Not joining, not resuming or resuming session without file
            emptypanel.show(self, 'activity-read', _('No book'),
                            _('Choose something to read'),
                            self._show_journal_object_picker_cb)

    def _create_back_button(self):
        back = ToolButton('go-previous-paired')
        back.set_tooltip(_('Back'))
        back.props.sensitive = False
        palette = back.get_palette()

        previous_page = MenuItem(text_label=_("Previous page"))
        previous_page.show()
        previous_bookmark = MenuItem(text_label=_("Previous bookmark"))
        previous_bookmark.show()
        palette.menu.append(previous_page)
        palette.menu.append(previous_bookmark)

        back.connect('clicked', self.__go_back_cb)
        previous_page.connect('activate', self.__go_back_page_cb)
        previous_bookmark.connect('activate', self.__prev_bookmark_activate_cb)
        return back

    def _create_forward_button(self):
        forward = ToolButton('go-next-paired')
        forward.set_tooltip(_('Forward'))
        forward.props.sensitive = False
        palette = forward.get_palette()

        next_page = MenuItem(text_label=_("Next page"))
        next_page.show()
        next_bookmark = MenuItem(text_label=_("Next bookmark"))
        next_bookmark.show()

        palette.menu.append(next_page)
        palette.menu.append(next_bookmark)

        forward.connect('clicked', self.__go_forward_cb)
        next_page.connect('activate', self.__go_forward_page_cb)
        next_bookmark.connect('activate', self.__next_bookmark_activate_cb)
        return forward

    def _create_search(self):
        num_page_entry = Gtk.Entry()
        num_page_entry.set_text('0')
        num_page_entry.set_alignment(1)
        num_page_entry.connect('insert-text',
                               self.__num_page_entry_insert_text_cb)
        num_page_entry.connect('activate', self.__num_page_entry_activate_cb)
        num_page_entry.set_width_chars(4)
        return num_page_entry

    def _set_total_page_label(self, value):
        self._total_page_label.set_text(' / %s' % value)

    def show_navigator_button(self):
        self._view_toolbar.show_nav_button()

    def _create_navigator(self):
        def __cursor_changed_cb(treeview):
            selection = treeview.get_selection()
            store, index_iter = selection.get_selected()
            if index_iter is None:
                # Nothing selected. This happens at startup
                return
            if store.iter_has_child(index_iter):
                path = store.get_path(index_iter)
                if treeview.row_expanded(path):
                    treeview.collapse_row(path)
                else:
                    treeview.expand_row(path, False)

        self._toc_visible = False
        self._update_toc_view = False
        toc_navigator = Gtk.TreeView()
        toc_navigator.set_enable_search(False)
        toc_navigator.connect('cursor-changed', __cursor_changed_cb)
        toc_selection = toc_navigator.get_selection()
        toc_selection.set_mode(Gtk.SelectionMode.SINGLE)

        cell = Gtk.CellRendererText()
        self.treecol_toc = Gtk.TreeViewColumn(_('Index'), cell, text=0)
        toc_navigator.append_column(self.treecol_toc)

        self._toc_scroller = Gtk.ScrolledWindow(hadjustment=None,
                                                vadjustment=None)
        self._toc_scroller.set_policy(Gtk.PolicyType.AUTOMATIC,
                                      Gtk.PolicyType.AUTOMATIC)
        self._toc_scroller.add(toc_navigator)
        self._hbox.pack_start(self._toc_scroller,
                              expand=False,
                              fill=False,
                              padding=0)
        self._toc_separator = Gtk.VSeparator()
        self._hbox.pack_start(self._toc_separator,
                              expand=False,
                              fill=False,
                              padding=1)
        return toc_navigator

    def set_navigator_model(self, model):
        self._toc_model = model
        self._navigator.set_model(model)

    def __toogle_navigator_cb(self, button, visible):
        scrollbar_pos = -1
        if hasattr(self._view, 'get_vertical_pos'):
            scrollbar_pos = self._view.get_vertical_pos()
        if visible:
            self._toc_visible = True
            self._update_toc_view = True
            self._toc_select_active_page()
            self._toc_scroller.set_size_request(int(Gdk.Screen.width() / 4),
                                                -1)
            self._toc_scroller.show_all()
            self._toc_separator.show()
        else:
            self._toc_visible = False
            self._toc_scroller.hide()
            self._toc_separator.hide()
        if scrollbar_pos > -1:
            self._view.set_vertical_pos(scrollbar_pos)

    def __toogle_tray_cb(self, button, visible):
        if visible:
            logging.debug('Show tray')
            self.tray.show()
        else:
            logging.debug('Hide tray')
            self.tray.hide()

    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):
        if entry.props.text:
            page = int(entry.props.text) - 1
        else:
            page = 0

        self._view.set_current_page(page)
        entry.props.text = str(page + 1)

    def __go_back_cb(self, button):
        self._view.scroll(Gtk.ScrollType.PAGE_BACKWARD, False)

    def __go_forward_cb(self, button):
        self._view.scroll(Gtk.ScrollType.PAGE_FORWARD, False)

    def __go_back_page_cb(self, button):
        self._view.previous_page()

    def __go_forward_page_cb(self, button):
        self._view.next_page()

    def __highlight_cb(self, button):
        self._view.toggle_highlight(button.get_active())

    def __prev_bookmark_activate_cb(self, menuitem):
        page = self._view.get_current_page()

        prev_bookmark = self._bookmarkmanager.get_prev_bookmark_for_page(page)
        if prev_bookmark is not None:
            self._view.set_current_page(prev_bookmark.page_no)

    def __next_bookmark_activate_cb(self, menuitem):
        page = self._view.get_current_page()

        next_bookmark = self._bookmarkmanager.get_next_bookmark_for_page(page)
        if next_bookmark is not None:
            self._view.set_current_page(next_bookmark.page_no)

    def __bookmarker_toggled_cb(self, button):
        page = self._view.get_current_page()
        if self._bookmarker.props.active:
            self._bookmark_view.add_bookmark(page)
        else:
            alert = ConfirmationAlert()
            alert.props.title = _('Delete bookmark')
            alert.props.msg = _('All the information related '
                                'with this bookmark will be lost')
            self.add_alert(alert)
            alert.connect('response', self.__alert_response_cb, page)
            alert.show()

    def __alert_response_cb(self, alert, response_id, page):
        self.remove_alert(alert)

        if response_id is Gtk.ResponseType.OK:
            self._bookmark_view.del_bookmark(page)
        elif response_id is Gtk.ResponseType.CANCEL:
            self._bookmarker.handler_block(self._bookmarker_toggle_handler_id)
            self._bookmarker.props.active = True
            self._bookmarker.handler_unblock(
                self._bookmarker_toggle_handler_id)

    def __page_changed_cb(self, model, page_from, page_to):
        self._update_nav_buttons(page_to)
        if self._toc_model is not None:
            self._toc_select_active_page()

        self._bookmark_view.update_for_page(page_to)
        self.update_bookmark_button()

        if self._view.can_highlight():
            self._view.show_highlights(page_to)

    def _update_bookmark_cb(self, sidebar):
        self.update_bookmark_button()

    def update_bookmark_button(self):
        self._bookmarker.handler_block(self._bookmarker_toggle_handler_id)
        self._bookmarker.props.active = \
            self._bookmark_view.is_showing_local_bookmark()
        self._bookmarker.handler_unblock(self._bookmarker_toggle_handler_id)

    def _update_nav_buttons(self, current_page):
        self._back_button.props.sensitive = current_page > 0
        self._forward_button.props.sensitive = \
            current_page < self._view.get_pagecount() - 1

        self._num_page_entry.props.text = str(current_page + 1)
        self._set_total_page_label(self._view.get_pagecount())

    def _update_toc(self):
        if self._view.update_toc(self):
            self._navigator_changed_handler_id = \
                self._navigator.connect('cursor-changed',
                                        self.__navigator_cursor_changed_cb)

    def __navigator_cursor_changed_cb(self, toc_treeview):
        if toc_treeview.get_selection() is None:
            return
        treestore, toc_selected = toc_treeview.get_selection().get_selected()

        if toc_selected is not None:
            link = self._toc_model.get(toc_selected, 1)[0]
            logging.debug('View handle link %s', link)
            self._update_toc_view = False
            self._view.handle_link(link)
            self._update_toc_view = True

    def _toc_select_active_page(self):
        if not self._toc_visible or not self._update_toc_view:
            return

        _store, toc_selected = self._navigator.get_selection().get_selected()

        if toc_selected is not None:
            selected_link = self._toc_model.get(toc_selected, 1)[0]
        else:
            selected_link = ""
        current_link = self._view.get_current_link()

        if current_link == selected_link:
            return

        link_iter = self._view.get_link_iter(current_link)

        if link_iter is not None:
            self._navigator.handler_block(self._navigator_changed_handler_id)
            toc_selection = self._navigator.get_selection()
            toc_selection.select_iter(link_iter)
            self._navigator.handler_unblock(self._navigator_changed_handler_id)
        else:
            logging.debug('link "%s" not found in the toc model', current_link)

    def _show_journal_object_picker_cb(self, button):
        """Show the journal object picker to load a document.

        This is for if Read is launched without a document.
        """
        if not self._want_document:
            return

        try:
            chooser = ObjectChooser(parent=self,
                                    what_filter=self.get_bundle_id(),
                                    filter_type=FILTER_TYPE_MIME_BY_ACTIVITY)
        except:
            chooser = ObjectChooser(parent=self,
                                    what_filter=mime.GENERIC_TYPE_TEXT)

        try:
            result = chooser.run()
            if result == Gtk.ResponseType.ACCEPT:
                logging.debug('ObjectChooser: %r' %
                              chooser.get_selected_object())
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    for key in list(jobject.metadata.keys()):
                        self.metadata[key] = jobject.metadata[key]
                    self.read_file(jobject.file_path)
                    jobject.object_id = self._object_id
        finally:
            chooser.destroy()
            del chooser

    def _now_active_cb(self, widget, pspec):
        if self.props.active:
            # Now active, start initial suspend timeout
            if self._idle_timer > 0:
                GLib.source_remove(self._idle_timer)
            self._idle_timer = GLib.timeout_add_seconds(15, self._suspend_cb)
            self._sleep_inhibit = False
        else:
            # Now inactive
            self._sleep_inhibit = True

    def _focus_in_event_cb(self, widget, event):
        """Enable ebook mode idle sleep since Read has focus."""
        self._sleep_inhibit = False
        self._user_action_cb(self)

    def _focus_out_event_cb(self, widget, event):
        """Disable ebook mode idle sleep since Read lost focus."""
        self._sleep_inhibit = True

    def _user_action_cb(self, widget):
        """Set a timer for going back to ebook mode idle sleep."""
        if self._idle_timer > 0:
            GLib.source_remove(self._idle_timer)
        self._idle_timer = GLib.timeout_add_seconds(5, self._suspend_cb)

    def _suspend_cb(self):
        """Go into ebook mode idle sleep."""
        # If the machine has been idle for 5 seconds, suspend
        self._idle_timer = 0
        if not self._sleep_inhibit and not self.get_shared():
            self._service.set_kernel_suspend()
        return False

    def read_file(self, file_path):
        """Load a file from the datastore on activity start."""
        _logger.debug('ReadActivity.read_file: %s', file_path)
        # enable collaboration
        self.activity_button.page.share.props.sensitive = True

        # we need copy the file to a new place, the file_path disappear
        extension = os.path.splitext(file_path)[1]
        tempfile = os.path.join(self.get_activity_root(), 'instance',
                                'tmp%i%s' % (time.time(), extension))
        os.link(file_path, tempfile)

        self._load_document('file://' + tempfile)

        # FIXME: This should obviously be fixed properly
        GLib.timeout_add_seconds(1, self.__view_toolbar_needs_update_size_cb,
                                 None)

    def write_file(self, file_path):
        """Write into datastore for Keep.

        The document is saved by hardlinking from the temporary file we
        keep around instead of "saving".

        The metadata is updated, including current page, view settings,
        search text.

        """
        if self._tempfile is None:
            # Workaround for closing Read with no document loaded
            raise NotImplementedError

        try:
            self.metadata['Read_current_page'] = \
                str(self._view.get_current_page())

            self._view.update_metadata(self)

            self.metadata['Read_search'] = \
                self._edit_toolbar._search_entry.props.text

        except Exception as e:
            _logger.error('write_file(): %s', e)

        self.metadata['Read_search'] = \
            self._edit_toolbar._search_entry.props.text
        self.metadata['activity'] = self.get_bundle_id()

        # the file is only saved if modified
        saved = False
        if hasattr(self._view, 'save'):
            saved = self._view.save(file_path)

        if saved:
            self.filehash = get_md5(file_path)
            self.metadata['filehash'] = self.filehash
        else:
            os.link(self._tempfile, file_path)

        if self.filehash is None:
            self.filehash = get_md5(file_path)
        self.metadata['filehash'] = self.filehash

        self._save_bookmars_in_metadata()

        if self._close_requested:
            _logger.debug("Removing temp file %s because we will close",
                          self._tempfile)
            os.unlink(self._tempfile)

            # remove file used to transmit the metadata if exits
            try:
                metadata_file_path = self._tempfile + '.json'
                os.unlink(metadata_file_path)
            except OSError:
                pass

            self._tempfile = None

    def _save_bookmars_in_metadata(self):
        # save bookmarks in the metadata
        bookmarks = []
        for bookmark in self._bookmarkmanager.get_bookmarks():
            bookmarks.append(bookmark.get_as_dict())
        self.metadata['bookmarks'] = json.dumps(bookmarks)
        self.metadata['highlights'] = json.dumps(
            self._bookmarkmanager.get_all_highlights())

    def can_close(self):
        """Prepare to cleanup on closing.

        Called from self.close()
        """
        self._close_requested = True
        return True

    def _download_result_cb(self, getter, tempfile, suggested_name, tube_id,
                            tube_ip, tube_port):
        if self._download_content_type == 'text/html':
            # got an error page instead
            self._download_error_cb(getter, 'HTTP Error', tube_id)
            return

        del self.unused_download_tubes

        # Use the suggested file, the mime is not recognized if the extension
        # is wrong in some cases (epub)
        temp_dir = os.path.dirname(tempfile)
        new_name = os.path.join(temp_dir, suggested_name)
        os.rename(tempfile, new_name)
        tempfile = new_name

        _logger.debug("Saving file %s to datastore...", tempfile)
        mimetype = Gio.content_type_guess(tempfile, None)[0]
        self._jobject.metadata['mime_type'] = mimetype
        self._jobject.file_path = tempfile
        datastore.write(self._jobject)

        _logger.debug("Got document %s (%s) from tube %u", tempfile,
                      suggested_name, tube_id)
        if self._progress_alert is not None:
            self.remove_alert(self._progress_alert)
            self._progress_alert = None

        # download the metadata
        GLib.idle_add(self._download_metadata, tube_id, tube_ip, tube_port)

    def _download_metadata_result_cb(self, getter, tempfile, suggested_name,
                                     tube_id):
        # load the shared metadata
        with open(tempfile) as json_file:
            shared_metadata = json.load(json_file)
        os.remove(tempfile)

        # load the object from the datastore to update the file path
        GLib.idle_add(self._open_downloaded_file, shared_metadata)

    def _open_downloaded_file(self, shared_metadata):
        self._jobject = datastore.get(self._jobject.object_id)
        for key in list(shared_metadata.keys()):
            self.metadata[key] = shared_metadata[key]

        self.read_file(self._jobject.file_path)

    def _download_progress_cb(self, getter, bytes_downloaded, tube_id):
        # FIXME: Draw a progress bar
        if self._download_content_length > 0:
            _logger.debug("Downloaded %u of %u bytes from tube %u...",
                          bytes_downloaded, self._download_content_length,
                          tube_id)
            fraction = float(bytes_downloaded) / \
                float(self._download_content_length)
            self._progress_alert.set_fraction(fraction)
        else:
            _logger.debug("Downloaded %u bytes from tube %u...",
                          bytes_downloaded, tube_id)

    def _download_error_cb(self, getter, err, tube_id):
        _logger.debug("Error getting document from tube %u: %s", tube_id, err)
        self._want_document = True
        self._download_content_length = 0
        self._download_content_type = None
        if self._progress_alert is not None:
            self.remove_alert(self._progress_alert)
            self._progress_alert = None
        GLib.idle_add(self._get_document)

    def _get_connection_params(self, tube_id):
        # return ip and port to download a file
        chan = self.shared_activity.telepathy_tubes_chan
        iface = chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES]
        addr = iface.AcceptStreamTube(
            tube_id,
            TelepathyGLib.SocketAddressType.IPV4,
            TelepathyGLib.SocketAccessControl.LOCALHOST,
            0,
            utf8_strings=True)
        _logger.debug('Accepted stream tube: listening address is %r', addr)
        # SOCKET_ADDRESS_TYPE_IPV4 is defined to have addresses of type '(sq)'
        assert isinstance(addr, dbus.Struct)
        assert len(addr) == 2
        assert isinstance(addr[0], str)
        assert isinstance(addr[1], int)
        assert addr[1] > 0 and addr[1] < 65536
        ip = addr[0]
        port = int(addr[1])
        return ip, port

    def _download_document(self, tube_id):
        ip, port = self._get_connection_params(tube_id)

        getter = ReadURLDownloader("http://%s:%d/document" % (ip, port))
        getter.connect("finished", self._download_result_cb, tube_id, ip, port)
        getter.connect("progress", self._download_progress_cb, tube_id)
        getter.connect("error", self._download_error_cb, tube_id)
        getter.start()
        self._download_content_length = getter.get_content_length()
        self._download_content_type = getter.get_content_type()
        return False

    def _download_metadata(self, tube_id, ip, port):
        getter = ReadURLDownloader("http://%s:%d/metadata" % (ip, port))
        getter.connect("finished", self._download_metadata_result_cb, tube_id)
        # getter.connect("progress", self._download_progress_cb, tube_id)
        getter.connect("error", self._download_error_cb, tube_id)
        getter.start()
        self._download_content_length = getter.get_content_length()
        self._download_content_type = getter.get_content_type()
        return False

    def _get_document(self):
        if not self._want_document:
            return False

        # Pick an arbitrary tube we can try to download the document from
        try:
            tube_id = self.unused_download_tubes.pop()
        except (ValueError, KeyError) as e:
            _logger.debug('No tubes to get the document from right now: %s', e)
            return False

        # Avoid trying to download the document multiple times at once
        self._want_document = False
        GLib.idle_add(self._download_document, tube_id)
        return False

    def _joined_cb(self, also_self):
        """Callback for when a shared activity is joined.

        Get the shared document from another participant.
        """
        self.watch_for_tubes()
        if self._progress_alert is not None:
            self._progress_alert.props.msg = _('Receiving book...')

        GLib.idle_add(self._get_document)

    def _load_document(self, filepath):
        """Load the specified document and set up the UI.

        filepath -- string starting with file://

        """
        if self._tempfile is not None:
            # prevent reopen
            return

        self.set_canvas(self._vbox)

        filename = filepath.replace('file://', '')
        self._tempfile = filename
        if not os.path.exists(filename) or os.path.getsize(filename) == 0:
            return
        if 'mime_type' not in self.metadata or not self.metadata['mime_type']:
            mimetype = Gio.content_type_guess(filepath, None)[0]
            self.metadata['mime_type'] = mimetype
        else:
            mimetype = self.metadata['mime_type']

        if mimetype == 'application/epub+zip':
            import epubadapter
            self._view = epubadapter.EpubViewer()
        elif mimetype == 'text/plain' or mimetype == 'application/zip':
            import textadapter
            self._view = textadapter.TextViewer()
        elif mimetype == 'application/x-cbz':
            import comicadapter
            self._view = comicadapter.ComicViewer()
        else:
            import evinceadapter
            self._view = evinceadapter.EvinceViewer()

        self._view.setup(self)
        self._view.load_document(filepath)

        self._want_document = False

        self._view_toolbar.set_view(self._view)
        self._edit_toolbar.set_view(self._view)

        self.filehash = self.metadata.get('filehash', None)
        if self.filehash is None:
            self.filehash = get_md5(filepath)

        self._bookmarkmanager = BookmarkManager(self.filehash)

        # update bookmarks and highlights with the informaiton
        # from the metadata
        if 'bookmarks' in self.metadata:
            self._bookmarkmanager.update_bookmarks(
                json.loads(self.metadata['bookmarks']))

        if 'highlights' in self.metadata:
            self._bookmarkmanager.update_highlights(
                json.loads(self.metadata['highlights']))

        self._bookmarkmanager.connect('added_bookmark',
                                      self._added_bookmark_cb)
        self._bookmarkmanager.connect('removed_bookmark',
                                      self._removed_bookmark_cb)

        # Add the bookmarks to the tray
        for bookmark in self._bookmarkmanager.get_bookmarks():
            page = bookmark.page_no
            thumb = self._bookmarkmanager.get_bookmark_preview(page)
            if thumb is None:
                logging.debug('Preview NOT FOUND')
                thumb = self._get_screenshot()
            # The database is zero based
            num_page = int(page) + 1
            title = _('%(title)s (Page %(number)d)') % \
                ({'title': bookmark.get_note_title(),
                    'number': num_page})
            self._add_link_totray(num_page, thumb, bookmark.color, title,
                                  bookmark.nick, bookmark.local)

        self._bookmark_view.set_bookmarkmanager(self._bookmarkmanager)
        self._update_toc()
        self._view.connect_page_changed_handler(self.__page_changed_cb)
        self._view.load_metadata(self)
        self._update_toolbars()

        self._edit_toolbar._search_entry.props.text = \
            self.metadata.get('Read_search', '')

        current_page = int(self.metadata.get('Read_current_page', '0'))
        _logger.debug('Setting page to: %d', current_page)
        self._view.set_current_page(current_page)
        self._update_nav_buttons(current_page)

        # README: bookmark sidebar is not showing the bookmark in the
        # first page because this is updated just if the page number changes
        if current_page == 0:
            self._bookmark_view.update_for_page(current_page)

        # We've got the document, so if we're a shared activity, offer it
        try:
            if self.get_shared():
                self.watch_for_tubes()
                self._share_document()
        except Exception as e:
            _logger.debug('Sharing failed: %s', e)

    def _update_toolbars(self):
        self._view_toolbar._update_zoom_buttons()
        if self._view.can_highlight():
            self._highlight.show()
        if self._view.can_do_text_to_speech():
            self.speech_toolbar = SpeechToolbar(self)
            self.speech_toolbar_button.set_page(self.speech_toolbar)
            self.speech_toolbar_button.show()

    def _share_document(self):
        """Share the document."""
        # FIXME: should ideally have the fileserver listen on a Unix socket
        # instead of IPv4 (might be more compatible with Rainbow)

        _logger.debug('Starting HTTP server on port %d', self.port)

        self._fileserver = ReadHTTPServer(("", self.port), self._tempfile,
                                          self.create_metadata_file)

        # Make a tube for it
        chan = self.shared_activity.telepathy_tubes_chan
        iface = chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES]
        self._fileserver_tube_id = iface.OfferStreamTube(
            READ_STREAM_SERVICE, {}, TelepathyGLib.SocketAddressType.IPV4,
            ('127.0.0.1', dbus.UInt16(self.port)),
            TelepathyGLib.SocketAccessControl.LOCALHOST, 0)

    def create_metadata_file(self):
        # store the metadata in a json file
        self._save_bookmars_in_metadata()
        metadata_file_path = self._tempfile + '.json'

        shared_metadata = {}
        for key in list(self.metadata.keys()):
            if key not in ['preview', 'cover_image']:
                shared_metadata[str(key)] = self.metadata[key]
        logging.debug('save metadata in %s', metadata_file_path)
        with open(metadata_file_path, 'w') as json_file:
            json.dump(shared_metadata, json_file)
        return metadata_file_path

    def watch_for_tubes(self):
        """Watch for new tubes."""
        tubes_chan = self.shared_activity.telepathy_tubes_chan

        tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].connect_to_signal(
            'NewTube', self._new_tube_cb)
        tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].ListTubes(
            reply_handler=self._list_tubes_reply_cb,
            error_handler=self._list_tubes_error_cb)

    def _new_tube_cb(self, tube_id, initiator, tube_type, service, params,
                     state):
        """Callback when a new tube becomes available."""
        _logger.debug(
            'New tube: ID=%d initator=%d type=%d service=%s '
            'params=%r state=%d', tube_id, initiator, tube_type, service,
            params, state)
        if self._view is None and service == READ_STREAM_SERVICE:
            _logger.debug('I could download from that tube')
            self.unused_download_tubes.add(tube_id)
            # if no download is in progress, let's fetch the document
            if self._want_document:
                GLib.idle_add(self._get_document)

    def _list_tubes_reply_cb(self, tubes):
        """Callback when new tubes are available."""
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        """Handle ListTubes error by logging."""
        _logger.error('ListTubes() failed: %s', e)

    def _shared_cb(self, activityid):
        """Callback when activity shared.

        Set up to share the document.

        """
        # We initiated this activity and have now shared it, so by
        # definition we have the file.
        _logger.debug('Activity became shared')
        self.watch_for_tubes()
        self._share_document()

    def _view_selection_changed_cb(self, view):
        self._edit_toolbar.copy.props.sensitive = view.get_has_selection()
        if self._view.can_highlight():
            in_bounds, _highlight_found = self._view.in_highlight()
            self._highlight.props.sensitive = \
                view.get_has_selection() or in_bounds

            self._highlight.handler_block(self._highlight_id)
            self._highlight.set_active(in_bounds)
            self._highlight.handler_unblock(self._highlight_id)

    def _edit_toolbar_copy_cb(self, button):
        self._view.copy()

    def _key_press_event_cb(self, widget, event):
        if self.activity_button.page.title.has_focus() or \
                self._num_page_entry.has_focus():
            return False
        keyname = Gdk.keyval_name(event.keyval)
        if keyname == 'c' and event.state & Gdk.ModifierType.CONTROL_MASK:
            self._view.copy()
            return True
        elif keyname == 'KP_Home':
            # FIXME: refactor later to self.zoom_in()
            self._view_toolbar.zoom_in()
            return True
        elif keyname == 'KP_End':
            self._view_toolbar.zoom_out()
            return True
        elif keyname == 'Home':
            self._view.scroll(Gtk.ScrollType.START, False)
            return True
        elif keyname == 'End':
            self._view.scroll(Gtk.ScrollType.END, False)
            return True
        elif keyname == 'Page_Up' or keyname == 'KP_Page_Up':
            self._view.scroll(Gtk.ScrollType.PAGE_BACKWARD, False)
            return True
        elif keyname == 'Page_Down' or keyname == 'KP_Page_Down':
            self._view.scroll(Gtk.ScrollType.PAGE_FORWARD, False)
            return True
        elif keyname == 'Up' or keyname == 'KP_Up':
            self._view.scroll(Gtk.ScrollType.STEP_BACKWARD, False)
            return True
        elif keyname == 'Down' or keyname == 'KP_Down':
            self._view.scroll(Gtk.ScrollType.STEP_FORWARD, False)
            return True
        elif keyname == 'Left' or keyname == 'KP_Left':
            self._view.scroll(Gtk.ScrollType.STEP_BACKWARD, True)
            return True
        elif keyname == 'Right' or keyname == 'KP_Right':
            self._view.scroll(Gtk.ScrollType.STEP_FORWARD, True)
            return True
        else:
            return False

    def _key_release_event_cb(self, widget, event):
        # keyname = Gdk.keyval_name(event.keyval)
        # _logger.debug("Keyname Release: %s, time: %s", keyname, event.time)
        return False

    def __view_toolbar_needs_update_size_cb(self, view_toolbar):
        if hasattr(self._view, 'update_view_size'):
            self._view.update_view_size(self._scrolled)
        else:
            return False  # No need again to run this again and

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

    def _added_bookmark_cb(self, bookmarkmanager, page, title):
        logging.debug('Bookmark added page %d', page)
        title = _('%(title)s (Page %(number)d)') % \
            ({'title': title, 'number': page})
        color = profile.get_color().to_string()
        owner = profile.get_nick_name()
        thumb = self._get_screenshot()
        self._add_link_totray(page, thumb, color, title, owner, 1)
        bookmarkmanager.add_bookmark_preview(page - 1, thumb)

    def _removed_bookmark_cb(self, bookmarkmanager, page):
        logging.debug('Bookmark removed page %d', page)
        # remove button from tray
        for button in self.tray.get_children():
            if button.page == page:
                self.tray.remove_item(button)
        if len(self.tray.get_children()) == 0:
            self.tray.hide()
            self._view_toolbar.traybutton.props.active = False

    def _add_link_totray(self, page, buf, color, title, owner, local):
        ''' add a link to the tray '''
        item = LinkButton(buf, color, title, owner, page, local)
        item.connect('clicked', self._bookmark_button_clicked_cb, page)
        item.connect('go_to_bookmark', self._bookmark_button_clicked_cb)
        item.connect('remove_link', self._bookmark_button_removed_cb)
        self.tray.show()
        self.tray.add_item(item)
        item.show()
        self._view_toolbar.traybutton.props.active = True

    def _bookmark_button_clicked_cb(self, button, page):
        num_page = int(page) - 1
        self._view.set_current_page(num_page)
        if not button.have_preview():
            # HACK: we need take the screenshot after the page changed
            # but we don't have a event yet, Evince model have a event
            # we need check the differnt backends and implement
            # in all the backends.
            GLib.timeout_add_seconds(2, self._update_preview, button, page)

    def _update_preview(self, button, page):
        thumb = self._get_screenshot()
        self._bookmarkmanager.add_bookmark_preview(page - 1, thumb)
        button.set_image(thumb)
        return False

    def _bookmark_button_removed_cb(self, button, page):
        num_page = int(page) - 1
        self._bookmark_view.del_bookmark(num_page)

    def _get_screenshot(self):
        """Copied from activity.get_preview()
        """
        if self.canvas is None or not hasattr(self.canvas, 'get_window'):
            return None

        window = self.canvas.get_window()
        if window is None:
            return None

        alloc = self.canvas.get_allocation()

        dummy_cr = Gdk.cairo_create(window)
        target = dummy_cr.get_target()
        canvas_width, canvas_height = alloc.width, alloc.height
        screenshot_surface = target.create_similar(cairo.CONTENT_COLOR,
                                                   canvas_width, canvas_height)
        del dummy_cr, target

        cr = cairo.Context(screenshot_surface)
        r, g, b, a_ = style.COLOR_PANEL_GREY.get_rgba()
        cr.set_source_rgb(r, g, b)
        cr.paint()
        self.canvas.draw(cr)
        del cr

        preview_width, preview_height = style.zoom(100), style.zoom(80)
        preview_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                             preview_width, preview_height)
        cr = cairo.Context(preview_surface)

        scale_w = preview_width * 1.0 / canvas_width
        scale_h = preview_height * 1.0 / canvas_height
        scale = min(scale_w, scale_h)

        translate_x = int((preview_width - (canvas_width * scale)) / 2)
        translate_y = int((preview_height - (canvas_height * scale)) / 2)

        cr.translate(translate_x, translate_y)
        cr.scale(scale, scale)

        cr.set_source_rgba(1, 1, 1, 0)
        cr.set_operator(cairo.OPERATOR_SOURCE)
        cr.paint()
        cr.set_source_surface(screenshot_surface)
        cr.paint()

        preview_str = io.StringIO()
        preview_surface.write_to_png(preview_str)
        return preview_str.getvalue()
Example #10
0
class AbiWordActivity(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        # abiword uses the current directory for all its file dialogs
        os.chdir(os.path.expanduser('~'))

        # create our main abiword canvas
        self.abiword_canvas = DocumentView()
        self._new_instance = True
        toolbar_box = ToolbarBox()

        self.activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(self.activity_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.show()
        self.activity_button.props.page.insert(separator, 2)
        ExportButtonFactory(self, self.abiword_canvas)
        self.activity_button.show()

        edit_toolbar = ToolbarButton()
        edit_toolbar.props.page = EditToolbar(self, toolbar_box)
        edit_toolbar.props.icon_name = 'toolbar-edit'
        edit_toolbar.props.label = _('Edit')
        toolbar_box.toolbar.insert(edit_toolbar, -1)

        view_toolbar = ToolbarButton()
        view_toolbar.props.page = ViewToolbar(self.abiword_canvas)
        view_toolbar.props.icon_name = 'toolbar-view'
        view_toolbar.props.label = _('View')
        toolbar_box.toolbar.insert(view_toolbar, -1)

        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if self.abiword_canvas.get_version() != '3.0':
            self.speech_toolbar_button = ToolbarButton(icon_name='speak')
            toolbar_box.toolbar.insert(self.speech_toolbar_button, -1)
            self._init_speech()

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        text_toolbar = ToolbarButton()
        text_toolbar.props.page = TextToolbar(self.abiword_canvas)
        text_toolbar.props.icon_name = 'format-text'
        text_toolbar.props.label = _('Text')
        toolbar_box.toolbar.insert(text_toolbar, -1)

        para_toolbar = ToolbarButton()
        para_toolbar.props.page = ParagraphToolbar(self.abiword_canvas)
        para_toolbar.props.icon_name = 'paragraph-bar'
        para_toolbar.props.label = _('Paragraph')
        toolbar_box.toolbar.insert(para_toolbar, -1)

        insert_toolbar = ToolbarButton()
        insert_toolbar.props.page = InsertToolbar(self.abiword_canvas)
        insert_toolbar.props.icon_name = 'insert-table'
        insert_toolbar.props.label = _('Table')
        toolbar_box.toolbar.insert(insert_toolbar, -1)

        image = ToolButton('insert-picture')
        image.set_tooltip(_('Insert Image'))
        self._image_id = image.connect('clicked', self.__image_cb)
        toolbar_box.toolbar.insert(image, -1)

        palette = image.get_palette()
        box = PaletteMenuBox()
        palette.set_content(box)
        box.show()
        menu_item = PaletteMenuItem(_('Floating'))
        menu_item.connect('activate', self.__image_cb, True)
        box.append_item(menu_item)
        menu_item.show()

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

        stop = StopButton(self)
        toolbar_box.toolbar.insert(stop, -1)

        toolbar_box.show_all()
        self.set_toolbar_box(toolbar_box)

        # add a overlay to be able to show a icon while joining a shared doc
        overlay = Gtk.Overlay()
        overlay.add(self.abiword_canvas)
        overlay.show()

        self._connecting_box = ConnectingBox()
        overlay.add_overlay(self._connecting_box)

        self.set_canvas(overlay)

        # we want a nice border so we can select paragraphs easily
        self.abiword_canvas.set_show_margin(True)

        # Set default font face and size
        self._default_font_face = 'Sans'
        self._default_font_size = 12

        # activity sharing
        self.participants = {}
        self.joined = False

        self.connect('shared', self._shared_cb)

        if self.shared_activity:
            # we are joining the activity
            logger.debug('We are joining an activity')
            # display a icon while joining
            self._connecting_box.show()
            # disable the abi widget
            self.abiword_canvas.set_sensitive(False)
            self._new_instance = False
            self.connect('joined', self._joined_cb)
            self.shared_activity.connect('buddy-joined', self._buddy_joined_cb)
            self.shared_activity.connect('buddy-left', self._buddy_left_cb)
            if self.get_shared():
                self._joined_cb(self)
        else:
            # we are creating the activity
            logger.debug("We are creating an activity")

        self.abiword_canvas.zoom_width()
        self.abiword_canvas.show()
        self.connect_after('map-event', self.__map_activity_event_cb)

        self.abiword_canvas.connect('size-allocate', self.size_allocate_cb)

    def _init_speech(self):
        import speech
        from speechtoolbar import SpeechToolbar
        if speech.supported:
            self.speech_toolbar = SpeechToolbar(self)
            self.speech_toolbar_button.set_page(self.speech_toolbar)
            self.speech_toolbar_button.show()

    def size_allocate_cb(self, abi, alloc):
        GObject.idle_add(abi.queue_draw)

    def __map_activity_event_cb(self, event, activity):
        # set custom keybindings for Write
        # we do it later because have problems if done before - OLPC #11049
        logger.debug('Loading keybindings')
        keybindings_file = os.path.join(get_bundle_path(), 'keybindings.xml')
        self.abiword_canvas.invoke_ex(
            'com.abisource.abiword.loadbindings.fromURI', keybindings_file, 0,
            0)
        # set default font
        if self._new_instance:
            self.abiword_canvas.select_all()
            logging.debug('Setting default font to %s %d in new documents',
                          self._default_font_face, self._default_font_size)
            self.abiword_canvas.set_font_name(self._default_font_face)
            self.abiword_canvas.set_font_size(str(self._default_font_size))
            self.abiword_canvas.moveto_bod()
            self.abiword_canvas.select_bod()
        if hasattr(self.abiword_canvas, 'toggle_rulers'):
            # this is not available yet on upstream abiword
            self.abiword_canvas.view_print_layout()
            self.abiword_canvas.toggle_rulers(False)

        self.abiword_canvas.grab_focus()

    def get_preview(self):
        if not hasattr(self.abiword_canvas, 'render_page_to_image'):
            return activity.Activity.get_preview(self)

        from gi.repository import GdkPixbuf

        pixbuf = self.abiword_canvas.render_page_to_image(1)
        pixbuf = pixbuf.scale_simple(style.zoom(300), style.zoom(225),
                                     GdkPixbuf.InterpType.BILINEAR)

        preview_data = []

        def save_func(buf, lenght, data):
            data.append(buf)
            return True

        pixbuf.save_to_callbackv(save_func, preview_data, 'png', [], [])
        preview_data = ''.join(preview_data)

        return preview_data

    def _shared_cb(self, activity):
        logger.debug('My Write activity was shared')
        self._sharing_setup()

        self.shared_activity.connect('buddy-joined', self._buddy_joined_cb)
        self.shared_activity.connect('buddy-left', self._buddy_left_cb)

        channel = self.tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES]
        logger.debug('This is my activity: offering a tube...')
        id = channel.OfferDBusTube('com.abisource.abiword.abicollab', {})
        logger.debug('Tube address: %s', channel.GetDBusTubeAddress(id))

    def _sharing_setup(self):
        logger.debug("_sharing_setup()")

        if self.shared_activity is None:
            logger.error('Failed to share or join activity')
            return

        self.conn = self.shared_activity.telepathy_conn
        self.tubes_chan = self.shared_activity.telepathy_tubes_chan
        self.text_chan = self.shared_activity.telepathy_text_chan
        self.tube_id = None
        self.tubes_chan[
            TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].connect_to_signal(
                'NewTube', self._new_tube_cb)

    def _list_tubes_reply_cb(self, tubes):
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        logger.error('ListTubes() failed: %s', e)

    def _joined_cb(self, activity):
        logger.debug("_joined_cb()")
        if not self.shared_activity:
            self._enable_collaboration()
            return

        self.joined = True
        logger.debug('Joined an existing Write session')
        self._sharing_setup()

        logger.debug('This is not my activity: waiting for a tube...')
        self.tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].ListTubes(
            reply_handler=self._list_tubes_reply_cb,
            error_handler=self._list_tubes_error_cb)
        self._enable_collaboration()

    def _enable_collaboration(self):
        """
        when communication established, hide the download icon
        and enable the abi widget
        """
        self.abiword_canvas.zoom_width()
        self.abiword_canvas.set_sensitive(True)
        self._connecting_box.hide()

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        logger.debug(
            'New tube: ID=%d initiator=%d type=%d service=%s '
            'params=%r state=%d', id, initiator, type, service, params, state)

        if self.tube_id is not None:
            # We are already using a tube
            return

        if type != TelepathyGLib.TubeType.DBUS or \
                service != "com.abisource.abiword.abicollab":
            return

        channel = self.tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES]

        if state == TelepathyGLib.TubeState.LOCAL_PENDING:
            channel.AcceptDBusTube(id)

        # look for the initiator's D-Bus unique name
        initiator_dbus_name = None
        dbus_names = channel.GetDBusNames(id)
        for handle, name in dbus_names:
            if handle == initiator:
                logger.debug('found initiator D-Bus name: %s', name)
                initiator_dbus_name = name
                break

        if initiator_dbus_name is None:
            logger.error('Unable to get the D-Bus name of the tube initiator')
            return

        cmd_prefix = 'com.abisource.abiword.abicollab.olpc.'
        # pass this tube to abicollab
        address = channel.GetDBusTubeAddress(id)
        if self.joined:
            logger.debug('Passing tube address to abicollab (join): %s',
                         address)
            self.abiword_canvas.invoke_ex(cmd_prefix + 'joinTube', address, 0,
                                          0)
            # The intiator of the session has to be the first passed
            # to the Abicollab backend.
            logger.debug('Adding the initiator to the session: %s',
                         initiator_dbus_name)
            self.abiword_canvas.invoke_ex(cmd_prefix + 'buddyJoined',
                                          initiator_dbus_name, 0, 0)
        else:
            logger.debug('Passing tube address to abicollab (offer): %s',
                         address)
            self.abiword_canvas.invoke_ex(cmd_prefix + 'offerTube', address, 0,
                                          0)
        self.tube_id = id

        channel.connect_to_signal('DBusNamesChanged',
                                  self._on_dbus_names_changed)

        self._on_dbus_names_changed(id, dbus_names, [])

    def _on_dbus_names_changed(self, tube_id, added, removed):
        """
        We call com.abisource.abiword.abicollab.olpc.buddy{Joined,Left}
        according members of the D-Bus tube. That's why we don't add/remove
        buddies in _buddy_{joined,left}_cb.
        """
        logger.debug('_on_dbus_names_changed')
        #        if tube_id == self.tube_id:
        cmd_prefix = 'com.abisource.abiword.abicollab.olpc'
        for handle, bus_name in added:
            logger.debug('added handle: %s, with dbus_name: %s', handle,
                         bus_name)
            self.abiword_canvas.invoke_ex(cmd_prefix + '.buddyJoined',
                                          bus_name, 0, 0)
            self.participants[handle] = bus_name

    def _on_members_changed(self, message, added, removed, local_pending,
                            remote_pending, actor, reason):
        logger.debug("_on_members_changed")
        for handle in removed:
            bus_name = self.participants.pop(handle, None)
            if bus_name is None:
                # FIXME: that shouldn't happen so probably hide another bug.
                # Should be investigated
                continue

            cmd_prefix = 'com.abisource.abiword.abicollab.olpc'
            logger.debug('removed handle: %d, with dbus name: %s', handle,
                         bus_name)
            self.abiword_canvas.invoke_ex(cmd_prefix + '.buddyLeft', bus_name,
                                          0, 0)

    def _buddy_joined_cb(self, activity, buddy):
        logger.debug('buddy joined with object path: %s', buddy.object_path())

    def _buddy_left_cb(self, activity, buddy):
        logger.debug('buddy left with object path: %s', buddy.object_path())

    def read_file(self, file_path):
        logging.debug('AbiWordActivity.read_file: %s, mimetype: %s', file_path,
                      self.metadata['mime_type'])
        if self._is_plain_text(self.metadata['mime_type']):
            self.abiword_canvas.load_file('file://' + file_path, 'text/plain')
        else:
            # we pass no mime/file type, let libabiword autodetect it,
            # so we can handle multiple file formats
            self.abiword_canvas.load_file('file://' + file_path, '')
        self.abiword_canvas.zoom_width()
        self._new_instance = False

    def write_file(self, file_path):
        logging.debug('AbiWordActivity.write_file: %s, mimetype: %s',
                      file_path, self.metadata['mime_type'])
        # if we were editing a text file save as plain text
        if self._is_plain_text(self.metadata['mime_type']):
            logger.debug('Writing file as type source (text/plain)')
            self.abiword_canvas.save('file://' + file_path, 'text/plain', '')
        else:
            #if the file is new, save in .odt format
            if self.metadata['mime_type'] == '':
                self.metadata['mime_type'] = 'application/rtf'

            # Abiword can't save in .doc format, save in .rtf instead
            if self.metadata['mime_type'] == 'application/msword':
                self.metadata['mime_type'] = 'application/rtf'

            self.abiword_canvas.save('file://' + file_path,
                                     self.metadata['mime_type'], '')

        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if self.abiword_canvas.get_version() != '3.0':
            self.metadata['fulltext'] = self.abiword_canvas.get_content(
                'text/plain', None)[:3000]

    def _is_plain_text(self, mime_type):
        # These types have 'text/plain' in their mime_parents  but we need
        # use it like rich text
        if mime_type in ['application/rtf', 'text/rtf', 'text/html']:
            return False

        from sugar3 import mime

        mime_parents = mime.get_mime_parents(self.metadata['mime_type'])
        return self.metadata['mime_type'] in ['text/plain', 'text/csv'] or \
            'text/plain' in mime_parents

    def __image_cb(self, button, floating=False):
        try:
            chooser = ObjectChooser(self,
                                    what_filter='Image',
                                    filter_type=FILTER_TYPE_GENERIC_MIME,
                                    show_preview=True)
        except:
            # for compatibility with older versions
            chooser = ObjectChooser(self, what_filter='Image')

        try:
            result = chooser.run()
            if result == Gtk.ResponseType.ACCEPT:
                logging.debug('ObjectChooser: %r',
                              chooser.get_selected_object())
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    self.abiword_canvas.insert_image(jobject.file_path,
                                                     floating)
        finally:
            chooser.destroy()
            del chooser
Example #11
0
    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
Example #12
0
class Record(activity.Activity):
    
    def __init__(self, handle):
        
        super(Record, self).__init__(handle)

        self.toolbox = ToolbarBox()
        self.toolbar = self.toolbox.toolbar
        self.activitybutton = ActivityToolbarButton(self)
        
        self._photo = None
        self._video = None
        self._audio = None
        
        self._timer = None
        self._timer_2 = None
        
        self._preferencias = None
        
        self.view = None
        self.tray = None
        
        self._set_toolbar()
        self._set_canvas()
        
        self.show_all()
        
        #self._photo.connect("clicked", self._click, "Photo")
        #self._video.connect("clicked", self._click, "Video")
        #self._audio.connect("clicked", self._click, "Audio")

    def _set_canvas(self):
        
        basebox = Gtk.Box(orientation = Gtk.Orientation.VERTICAL)
        
        self.view = View()
        self.tray = Tray()
        
        basebox.pack_start(self.view, True, True, 0)
        basebox.pack_start(self.tray, False, False, 0)
        
        self.set_canvas(basebox)
        
    def _set_toolbar(self):
        
        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)

        stop = StopButton(self)

        # Buttons #
        self._photo = RadioToolButton()
        self._photo.props.icon_name = 'media-photo'
        self._photo.props.label = _('Photo')

        self._video = RadioToolButton()
        self._video.props.group = self._photo
        self._video.props.icon_name = 'media-video'
        self._video.props.label = _('Video')

        self._audio = RadioToolButton()
        self._audio.props.group = self._photo
        self._audio.props.icon_name = 'media-audio'
        self._audio.props.label = _('Audio')
        # End of Buttons #

        self._timer = TimerCombo()
        self._timer_2 = DurationCombo()
        #self._timer_2.combo.set_sensitive(False)

        self._preferencias = ToolbarButton()
        
        toolbar = Gtk.Toolbar()
        combo = QualityCombo()
        #combo.set_sensitive(False)
        self.calidad = ToolComboBox(combo=combo, label_text=_('Quality:'))
        self.calidad.show_all()
        toolbar.insert(self.calidad, -1)
        toolbar.show_all()
        
        self._preferencias.set_page(toolbar)
        
        self._preferencias.props.icon_name = 'preferences-system'
        self._preferencias.props.label = _('Preferences')

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

        self.toolbar.insert(self._photo, -1)
        self.toolbar.insert(self._video, -1)
        self.toolbar.insert(self._audio, -1)

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

        self.toolbar.insert(self._timer, -1)
        self.toolbar.insert(self._timer_2, -1)
        self.toolbar.insert(self._preferencias, -1)

        self.toolbar.insert(separator, -1)
        self.toolbar.insert(stop, -1)

        self.set_toolbar_box(self.toolbox)
        
    '''