Exemplo n.º 1
0
    def available_emoticons_treeview_selection_changed(self,
                                                       treeview_selection):
        model, iter = treeview_selection.get_selected()
        button = self.xml.get_object('legend_button')
        button.set_label(_('Legend'))
        if iter:
            set_name = model.get_value(iter, C_NAME)
            if os.path.isdir(self.tmp_dir):
                rmtree(self.tmp_dir, True)
            self.tmp_dir = tempfile.mkdtemp()
            # unzip new files
            zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
            with zipfile.ZipFile(zip_file, 'r') as myzip:
                namelist = myzip.namelist()
                for n in namelist:
                    if not n.startswith(set_name):
                        continue
                    myzip.extract(n, path=self.tmp_dir)

            self.set_name.set_text(set_name)
            self.authors_label.set_text(model.get_value(iter, C_AUTHORS))
            self.converter_label.set_text(model.get_value(iter, C_CONVERTER))
            self.homepage_linkbutton.set_uri(model.get_value(iter, C_HOMEPAGE))
            self.homepage_linkbutton.set_label(
                model.get_value(iter, C_HOMEPAGE))
            label = self.homepage_linkbutton.get_children()[0]
            label.set_ellipsize(pango.ELLIPSIZE_END)
            self.homepage_linkbutton.set_property('sensitive', True)

            self.xml.get_object('scrolledwindow1').get_children()[0].destroy()
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            else:
                desc = desc.replace(
                    'preview.image',
                    ('file:' +
                     os.path.join(self.tmp_dir, set_name, 'preview.png')))

            self.emoticons_description_textview.tv.display_html(
                desc, self.emoticons_description_textview.tv,
                self.emoticons_description_textview)

            self.emoticons_description_textview.tv.set_property(
                'sensitive', True)
        else:
            self.set_name.set_text('')
            self.authors_label.set_text('')
            self.homepage_linkbutton.set_uri('')
            self.homepage_linkbutton.set_label('')
            self.homepage_linkbutton.set_property('sensitive', False)
Exemplo n.º 2
0
    def on_legend_button_clicked(self, widget):
        self.xml.get_object('scrolledwindow1').get_children()[0].destroy()

        treeview_selection = self.available_treeview.get_selection()
        model, iter = treeview_selection.get_selected()
        name = model.get_value(iter, C_NAME)

        button = self.xml.get_object('legend_button')
        if button.get_label() == _('Legend'):
            button.set_label(_('Description'))
            sys.path.append(os.path.join(self.tmp_dir, name))

            import emoticons
            imp.reload(emoticons)

            self.emoticons_description_textview = gtk.TextView()
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview)
            sw.show_all()

            buff = self.emoticons_description_textview.get_buffer()
            for icon in emoticons.emoticons:
                icon_file = os.path.join(self.tmp_dir, name, icon)
                with open(icon_file, 'rb') as _file:
                    data = _file.read()
                pbl = gtk.gdk.PixbufLoader()
                pbl.write(data)
                pbl.close()
                if icon.endswith('.gif'):
                    img = gtk.Image()
                    img.set_from_animation(pbl.get_animation())
                    img.show()
                    anchor = buff.create_child_anchor(buff.get_end_iter())
                    self.emoticons_description_textview.add_child_at_anchor(
                        img, anchor)
                else:
                    buff.insert_pixbuf(buff.get_end_iter(), pbl.get_pixbuf())
                text = ' , '.join(emoticons.emoticons[icon])
                buff.insert(buff.get_end_iter(), text + '\n', -1)

            self.emoticons_description_textview.set_property('sensitive', True)
            sys.path.remove(os.path.join(self.tmp_dir, name))

        else:
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            button.set_label(_('Legend'))
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body  '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            desc = desc.replace('preview.image', ('file:' + os.path.join(
                    self.tmp_dir, name, 'preview.png'))).replace('\n', '<br/>')
            self.emoticons_description_textview.tv.display_html(
                desc, self.emoticons_description_textview.tv,
                self.emoticons_description_textview)
            self.emoticons_description_textview.tv.set_property('sensitive', True)
Exemplo n.º 3
0
    def available_emoticons_treeview_selection_changed(self, treeview_selection):
        model, iter = treeview_selection.get_selected()
        button = self.xml.get_object('legend_button')
        button.set_label(_('Legend'))
        if iter:
            set_name = model.get_value(iter, C_NAME)
            if os.path.isdir(self.tmp_dir):
                rmtree(self.tmp_dir, True)
            self.tmp_dir = tempfile.mkdtemp()
             # unzip new files
            zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
            with zipfile.ZipFile(zip_file, 'r') as myzip:
                namelist = myzip.namelist()
                for n in namelist:
                    if not n.startswith(set_name):
                        continue
                    myzip.extract(n, path=self.tmp_dir)

            self.set_name.set_text(set_name)
            self.authors_label.set_text(model.get_value(iter, C_AUTHORS))
            self.converter_label.set_text(model.get_value(iter, C_CONVERTER))
            self.homepage_linkbutton.set_uri(
                model.get_value(iter, C_HOMEPAGE))
            self.homepage_linkbutton.set_label(
                model.get_value(iter, C_HOMEPAGE))
            label = self.homepage_linkbutton.get_children()[0]
            label.set_ellipsize(pango.ELLIPSIZE_END)
            self.homepage_linkbutton.set_property('sensitive', True)

            self.xml.get_object('scrolledwindow1').get_children()[0].destroy()
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            else:
                desc = desc.replace('preview.image', ('file:' + os.path.join(
                    self.tmp_dir, set_name, 'preview.png')))

            self.emoticons_description_textview.tv.display_html(desc,
                self.emoticons_description_textview.tv,
                self.emoticons_description_textview)

            self.emoticons_description_textview.tv.set_property('sensitive', True)
        else:
            self.set_name.set_text('')
            self.authors_label.set_text('')
            self.homepage_linkbutton.set_uri('')
            self.homepage_linkbutton.set_label('')
            self.homepage_linkbutton.set_property('sensitive', False)
Exemplo n.º 4
0
    import os

    from conversation_textview import ConversationTextview
    import gajim as gaj

    log = logging.getLogger()
    gaj.Interface()

    # create fake gajim.plugin_manager.gui_extension_point method for tests
    def gui_extension_point(*args):
        pass

    gajim.plugin_manager = gaj.Interface()
    gajim.plugin_manager.gui_extension_point = gui_extension_point

    htmlview = ConversationTextview(None)

    tooltip = tooltips.BaseTooltip()

    def on_textview_motion_notify_event(widget, event):
        """
        Change the cursor to a hand when we are over a mail or an url
        """
        global change_cursor
        w = htmlview.tv.get_window(Gtk.TextWindowType.TEXT)
        device = w.get_display().get_device_manager().get_client_pointer()
        pointer = w.get_device_position(device)
        x = pointer[1]
        y = pointer[2]
        tags = htmlview.tv.get_iter_at_location(x, y).get_tags()
        if change_cursor:
Exemplo n.º 5
0
if __name__ == '__main__':
    import os

    from conversation_textview import ConversationTextview
    import gajim as gaj

    log = logging.getLogger()
    gaj.Interface()

    # create fake gajim.plugin_manager.gui_extension_point method for tests
    def gui_extension_point(*args):
        pass
    gajim.plugin_manager = gaj.Interface()
    gajim.plugin_manager.gui_extension_point = gui_extension_point

    htmlview = ConversationTextview(None)

    tooltip = tooltips.BaseTooltip()

    def on_textview_motion_notify_event(widget, event):
        """
        Change the cursor to a hand when we are over a mail or an url
        """
        global change_cursor
        pointer_x, pointer_y = htmlview.tv.window.get_pointer()[0:2]
        x, y = htmlview.tv.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT,
            pointer_x, pointer_y)
        tags = htmlview.tv.get_iter_at_location(x, y).get_tags()
        if change_cursor:
            htmlview.tv.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(
                gtk.gdk.Cursor(gtk.gdk.XTERM))
Exemplo n.º 6
0
    def __init__(self, type_id, parent_win, widget_name, contact):
        # Undo needs this variable to know if space has been pressed.
        # Initialize it to True so empty textview is saved in undo list
        self.space_pressed = True

        MessageControl.__init__(self, type_id, parent_win, widget_name, contact)

        # Create textviews and connect signals
        self.conv_textview = ConversationTextview()

        id_ = self.conv_textview.tv.connect('key_press_event',
            self._conv_textview_key_press_event)
        self.handlers[id_] = self.conv_textview.tv


        self.conv_scrolledwindow = self.xml.get_object(
            'conversation_scrolledwindow')
        self.conv_scrolledwindow.add(self.conv_textview.tv)
        widget = self.conv_scrolledwindow.get_vadjustment()
        id_ = widget.connect('value-changed',
            self.on_conversation_vadjustment_value_changed)
        self.handlers[id_] = widget
        id_ = widget.connect('changed',
            self.on_conversation_vadjustment_changed)
        self.handlers[id_] = widget
        self.scroll_to_end_id = None
        self.was_at_the_end = True
        self.correcting = False
        self.last_sent_msg = None
        self.last_sent_txt = None
        self.last_received_txt = {} # one per name
        self.last_received_id = {} # one per name

        # add MessageTextView to UI and connect signals
        self.msg_scrolledwindow = self.xml.get_object('message_scrolledwindow')
        self.msg_textview = MessageTextView()
        id_ = self.msg_textview.connect('mykeypress',
            self._on_message_textview_mykeypress_event)
        self.handlers[id_] = self.msg_textview
        self.msg_scrolledwindow.add(self.msg_textview)
        id_ = self.msg_textview.connect('key_press_event',
            self._on_message_textview_key_press_event)
        self.handlers[id_] = self.msg_textview
        #id_ = self.msg_textview.connect('configure-event',
        #    self.on_configure_event)
        #self.handlers[id_] = self.msg_textview
        #id_ = self.msg_textview.connect('populate_popup',
        #    self.on_msg_textview_populate_popup)
        #self.handlers[id_] = self.msg_textview
        # Setup DND
        #id_ = self.msg_textview.connect('drag_data_received',
        #    self._on_drag_data_received)
        #self.handlers[id_] = self.msg_textview
        #self.msg_textview.drag_dest_set(Gtk.DestDefaults.MOTION |
        #    Gtk.DestDefaults.HIGHLIGHT, self.dnd_list, Gdk.DragAction.COPY)

        #self.update_font()

        # Hook up send button
        #widget = self.xml.get_object('send_button')
        #id_ = widget.connect('clicked', self._on_send_button_clicked)
        #widget.set_sensitive(False)
        #self.handlers[id_] = widget

        #widget = self.xml.get_object('formattings_button')
        #id_ = widget.connect('clicked', self.on_formattings_button_clicked)
        #self.handlers[id_] = widget

        # the following vars are used to keep history of user's messages
        self.sent_history = []
        self.sent_history_pos = 0
        self.received_history = []
        self.received_history_pos = 0
        self.orig_msg = None

        # Attach speller
        #if gajim.config.get('use_speller') and HAS_GTK_SPELL:
        #    self.set_speller()
        #self.conv_textview.tv.show()
        #self._paint_banner()

        # For XEP-0172
        self.user_nick = None

        self.smooth = True

        self.command_hits = []
        self.last_key_tabs = False
Exemplo n.º 7
0
class ChatControlBase(MessageControl):

    def __init__(self, type_id, parent_win, widget_name, contact):
        # Undo needs this variable to know if space has been pressed.
        # Initialize it to True so empty textview is saved in undo list
        self.space_pressed = True

        MessageControl.__init__(self, type_id, parent_win, widget_name, contact)

        # Create textviews and connect signals
        self.conv_textview = ConversationTextview()

        id_ = self.conv_textview.tv.connect('key_press_event',
            self._conv_textview_key_press_event)
        self.handlers[id_] = self.conv_textview.tv


        self.conv_scrolledwindow = self.xml.get_object(
            'conversation_scrolledwindow')
        self.conv_scrolledwindow.add(self.conv_textview.tv)
        widget = self.conv_scrolledwindow.get_vadjustment()
        id_ = widget.connect('value-changed',
            self.on_conversation_vadjustment_value_changed)
        self.handlers[id_] = widget
        id_ = widget.connect('changed',
            self.on_conversation_vadjustment_changed)
        self.handlers[id_] = widget
        self.scroll_to_end_id = None
        self.was_at_the_end = True
        self.correcting = False
        self.last_sent_msg = None
        self.last_sent_txt = None
        self.last_received_txt = {} # one per name
        self.last_received_id = {} # one per name

        # add MessageTextView to UI and connect signals
        self.msg_scrolledwindow = self.xml.get_object('message_scrolledwindow')
        self.msg_textview = MessageTextView()
        id_ = self.msg_textview.connect('mykeypress',
            self._on_message_textview_mykeypress_event)
        self.handlers[id_] = self.msg_textview
        self.msg_scrolledwindow.add(self.msg_textview)
        id_ = self.msg_textview.connect('key_press_event',
            self._on_message_textview_key_press_event)
        self.handlers[id_] = self.msg_textview
        #id_ = self.msg_textview.connect('configure-event',
        #    self.on_configure_event)
        #self.handlers[id_] = self.msg_textview
        #id_ = self.msg_textview.connect('populate_popup',
        #    self.on_msg_textview_populate_popup)
        #self.handlers[id_] = self.msg_textview
        # Setup DND
        #id_ = self.msg_textview.connect('drag_data_received',
        #    self._on_drag_data_received)
        #self.handlers[id_] = self.msg_textview
        #self.msg_textview.drag_dest_set(Gtk.DestDefaults.MOTION |
        #    Gtk.DestDefaults.HIGHLIGHT, self.dnd_list, Gdk.DragAction.COPY)

        #self.update_font()

        # Hook up send button
        #widget = self.xml.get_object('send_button')
        #id_ = widget.connect('clicked', self._on_send_button_clicked)
        #widget.set_sensitive(False)
        #self.handlers[id_] = widget

        #widget = self.xml.get_object('formattings_button')
        #id_ = widget.connect('clicked', self.on_formattings_button_clicked)
        #self.handlers[id_] = widget

        # the following vars are used to keep history of user's messages
        self.sent_history = []
        self.sent_history_pos = 0
        self.received_history = []
        self.received_history_pos = 0
        self.orig_msg = None

        # Attach speller
        #if gajim.config.get('use_speller') and HAS_GTK_SPELL:
        #    self.set_speller()
        #self.conv_textview.tv.show()
        #self._paint_banner()

        # For XEP-0172
        self.user_nick = None

        self.smooth = True

        self.command_hits = []
        self.last_key_tabs = False

        # PluginSystem: adding GUI extension point for ChatControlBase
        # instance object (also subclasses, eg. ChatControl or GroupchatControl)
        #gajim.plugin_manager.gui_extension_point('chat_control_base', self)

        #gajim.ged.register_event_handler('our-show', ged.GUI1,
        #    self._nec_our_status)
        #gajim.ged.register_event_handler('ping-sent', ged.GUI1,
        #    self._nec_ping_sent)
        #gajim.ged.register_event_handler('ping-reply', ged.GUI1,
        #    self._nec_ping_reply)
        #gajim.ged.register_event_handler('ping-error', ged.GUI1,
        #    self._nec_ping_error)

        # This is bascially a very nasty hack to surpass the inability
        # to properly use the super, because of the old code.
        #CommandTools.__init__(self)

    def _conv_textview_key_press_event(self, widget, event):
        # translate any layout to latin_layout
        valid, entries = self.keymap.get_entries_for_keyval(event.keyval)
        keycode = entries[0].keycode
        if (event.get_state() & Gdk.ModifierType.CONTROL_MASK and keycode in (
        self.keycode_c, self.keycode_ins)) or (
        event.get_state() & Gdk.ModifierType.SHIFT_MASK and \
        event.keyval in (Gdk.KEY_Page_Down, Gdk.KEY_Page_Up)):
            return False
        self.parent_win.notebook.event(event)
        return True

    def _on_message_textview_key_press_event(self, widget, event):
        if event.keyval == Gdk.KEY_space:
            self.space_pressed = True

        elif (self.space_pressed or self.msg_textview.undo_pressed) and \
        event.keyval not in (Gdk.KEY_Control_L, Gdk.KEY_Control_R) and \
        not (event.keyval == Gdk.KEY_z and event.get_state() & Gdk.ModifierType.CONTROL_MASK):
            # If the space key has been pressed and now it hasnt,
            # we save the buffer into the undo list. But be carefull we're not
            # pressiong Control again (as in ctrl+z)
            _buffer = widget.get_buffer()
            start_iter, end_iter = _buffer.get_bounds()
            self.msg_textview.save_undo(_buffer.get_text(start_iter, end_iter, True))
            self.space_pressed = False

        # Ctrl [+ Shift] + Tab are not forwarded to notebook. We handle it here
        if self.widget_name == 'groupchat_control':
            if event.keyval not in (Gdk.KEY_ISO_Left_Tab, Gdk.KEY_Tab):
                self.last_key_tabs = False
        if event.get_state() & Gdk.ModifierType.SHIFT_MASK:
            # CTRL + SHIFT + TAB
            if event.get_state() & Gdk.ModifierType.CONTROL_MASK and \
                            event.keyval == Gdk.KEY_ISO_Left_Tab:
                self.parent_win.move_to_next_unread_tab(False)
                return True
            # SHIFT + PAGE_[UP|DOWN]: send to conv_textview
            elif event.keyval == Gdk.KEY_Page_Down or \
                            event.keyval == Gdk.KEY_Page_Up:
                self.conv_textview.tv.event(event)
                return True
        elif event.get_state() & Gdk.ModifierType.CONTROL_MASK:
            if event.keyval == Gdk.KEY_Tab:  # CTRL + TAB
                self.parent_win.move_to_next_unread_tab(True)
                return True
################################################################################
        # temporary solution instead Gtk.binding_entry_add_signal
        message_buffer = self.msg_textview.get_buffer()
        event_state = event.get_state()
        if event.keyval == Gdk.KEY_Up:
            if event_state & Gdk.ModifierType.CONTROL_MASK:
                if event_state & Gdk.ModifierType.SHIFT_MASK: # Ctrl+Shift+UP
                    self.scroll_messages('up', message_buffer, 'received')
                else:  # Ctrl+UP
                    self.scroll_messages('up', message_buffer, 'sent')
            return True
        elif event.keyval == Gdk.KEY_Down:
            if event_state & Gdk.ModifierType.CONTROL_MASK:
                if event_state & Gdk.ModifierType.SHIFT_MASK: # Ctrl+Shift+Down
                    self.scroll_messages('down', message_buffer, 'received')
                else:  # Ctrl+Down
                    self.scroll_messages('down', message_buffer, 'sent')
            return True

        elif event.keyval == Gdk.KEY_Return or \
        event.keyval == Gdk.KEY_KP_Enter:  # ENTER
            message_textview = widget
            message_buffer = message_textview.get_buffer()
            start_iter, end_iter = message_buffer.get_bounds()
            message = message_buffer.get_text(start_iter, end_iter, False)
            xhtml = self.msg_textview.get_xhtml()

            if event_state & Gdk.ModifierType.CONTROL_MASK:  # Ctrl + ENTER
                end_iter = message_buffer.get_end_iter()
                message_buffer.insert_at_cursor('\n')
                send_message = False
            else: # ENTER
                send_message = True

            #if gajim.connections[self.account].connected < 2 and send_message:
                # we are not connected
            #    dialogs.ErrorDialog(_('A connection is not available'),
            #            _('Your message can not be sent until you are connected.'))
            #    send_message = False

            if send_message:
                self.send_message(message) # send the message
            return True
        elif event.keyval == Gdk.KEY_z: # CTRL+z
            if event_state & Gdk.ModifierType.CONTROL_MASK:
                self.msg_textview.undo()
                return True
################################################################################
        return False


    def _on_message_textview_mykeypress_event(self, widget, event_keyval,
    event_keymod):
        """
        When a key is pressed: if enter is pressed without the shift key, message
        (if not empty) is sent and printed in the conversation
        """
        # NOTE: handles mykeypress which is custom signal connected to this
        # CB in new_tab(). for this singal see message_textview.py
        message_textview = widget
        message_buffer = message_textview.get_buffer()
        start_iter, end_iter = message_buffer.get_bounds()
        message = message_buffer.get_text(start_iter, end_iter, False)
        xhtml = self.msg_textview.get_xhtml()

        # construct event instance from binding
        event = Gdk.Event(Gdk.EventType.KEY_PRESS)  # it's always a key-press here
        event.keyval = event_keyval
        event.state = event_keymod
        event.time = 0  # assign current time

        if event.keyval == Gdk.KEY_Up:
            if event.get_state() == Gdk.ModifierType.CONTROL_MASK:  # Ctrl+UP
                self.scroll_messages('up', message_buffer, 'sent')
            # Ctrl+Shift+UP
            elif event.get_state() == (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK):
                self.scroll_messages('up', message_buffer, 'received')
        elif event.keyval == Gdk.KEY_Down:
            if event.get_state() == Gdk.ModifierType.CONTROL_MASK:  # Ctrl+Down
                self.scroll_messages('down', message_buffer, 'sent')
            # Ctrl+Shift+Down
            elif event.get_state() == (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK):
                self.scroll_messages('down', message_buffer, 'received')
        elif event.keyval == Gdk.KEY_Return or \
                event.keyval == Gdk.KEY_KP_Enter:  # ENTER
            # NOTE: SHIFT + ENTER is not needed to be emulated as it is not
            # binding at all (textview's default action is newline)

            if gajim.config.get('send_on_ctrl_enter'):
                # here, we emulate GTK default action on ENTER (add new line)
                # normally I would add in keypress but it gets way to complex
                # to get instant result on changing this advanced setting
                if event.get_state() == 0:  # no ctrl, no shift just ENTER add newline
                    end_iter = message_buffer.get_end_iter()
                    message_buffer.insert_at_cursor('\n')
                    send_message = False
                elif event.get_state() & Gdk.ModifierType.CONTROL_MASK:  # CTRL + ENTER
                    send_message = True
            else: # send on Enter, do newline on Ctrl Enter
                if event.get_state() & Gdk.ModifierType.CONTROL_MASK:  # Ctrl + ENTER
                    end_iter = message_buffer.get_end_iter()
                    message_buffer.insert_at_cursor('\n')
                    send_message = False
                else: # ENTER
                    send_message = True

            if gajim.connections[self.account].connected < 2 and send_message:
                # we are not connected
                dialogs.ErrorDialog(_('A connection is not available'),
                        _('Your message can not be sent until you are connected.'))
                send_message = False

            if send_message:
                self.send_message(message, xhtml=xhtml) # send the message
        elif event.keyval == Gdk.KEY_z: # CTRL+z
            if event.get_state() & Gdk.ModifierType.CONTROL_MASK:
                self.msg_textview.undo()
        else:
            # Give the control itself a chance to process
            self.handle_message_textview_mykey_press(widget, event_keyval,
                    event_keymod)


    def on_conversation_vadjustment_changed(self, adjustment):
        # used to stay at the end of the textview when we shrink conversation
        # textview.
        if self.was_at_the_end:
            if self.conv_textview.at_the_end():
                # we are at the end
                self.conv_textview.bring_scroll_to_end(-18)
            else:
                self.conv_textview.bring_scroll_to_end(-18, use_smooth=False)
        self.was_at_the_end = (adjustment.get_upper() - adjustment.get_value()\
            - adjustment.get_page_size()) < 18

    def on_conversation_vadjustment_value_changed(self, adjustment):
        # stop automatic scroll when we manually scroll
        if not self.conv_textview.auto_scrolling:
            self.conv_textview.stop_scrolling()
        self.was_at_the_end = (adjustment.get_upper() - adjustment.get_value() \
            - adjustment.get_page_size()) < 18

    def shutdown(self):
        super(ChatControlBase, self).shutdown()



    def send_message(self, message):
        """
        Send the given message to the active tab. Doesn't return None if error
        """
        if not message or message == '\n':
            return None

        #if process_commands and self.process_as_command(message):
        #    return

        #label = self.get_seclabel()

        def _cb(msg, cb, *cb_args):
            self.last_sent_msg = msg
            self.last_sent_txt = cb_args[0]
            if cb:
                cb(msg, *cb_args)

        if self.correcting and self.last_sent_msg:
            correction_msg = self.last_sent_msg
        else:
            correction_msg = None

        #gajim.nec.push_outgoing_event(MessageOutgoingEvent(None,
        #    account=self.account, jid=self.contact.jid, message=message,
        #    keyID=keyID, type_=type_, chatstate=chatstate, msg_id=msg_id,
        #    resource=resource, user_nick=self.user_nick, xhtml=xhtml,
        #    label=label, callback=_cb, callback_args=[callback] + callback_args,
        #    control=self, attention=attention, correction_msg=correction_msg))

        print('sending message...')
        import push_message
        threading.Thread(target=push_message.handleSendMms,
             args=(message, self.contact ),
              ).start()
        #self.set_chat_text(' > ' + message, widget)

        # Record the history of sent messages
        #self.save_message(message, 'sent')

        # Be sure to send user nickname only once according to JEP-0172
        #self.user_nick = None

        # Clear msg input
        message_buffer = self.msg_textview.get_buffer()
        message_buffer.set_text('') # clear message buffer (and tv of course)


    def print_conversation_line(self, text, kind, name):
        """
        Print 'chat' type messages
        correct_id = (message_id, correct_id)
        """
        jid = self.contact
        full_jid = self.get_alias()
        textview = self.conv_textview
        end = False
        if self.was_at_the_end or kind == 'outgoing':
            end = True
        old_txt = ''
        if name in self.last_received_txt:
            old_txt = self.last_received_txt[name]

        textview.print_conversation_line(text, jid, kind, name)

        if not self.parent_win:
            return

        if (not self.parent_win.get_active_control() or \
        self != self.parent_win.get_active_control() or \
        not self.parent_win.is_active() or not end) and \
        kind in ('incoming', 'incoming_queue', 'error'):
            self.parent_win.redraw_tab(self)
Exemplo n.º 8
0
    def on_activate(self, widget):
        if 'plugins' not in gajim.interface.instances:
            return
        if hasattr(self, 'page_num'):
            # 'Available' tab exists
            return
        self.installed_plugins_model = gajim.interface.instances[
            'plugins'].installed_plugins_model
        self.notebook = gajim.interface.instances['plugins'].plugins_notebook
        id_ = self.notebook.connect(
            'switch-page', self.on_notebook_switch_page)
        self.connected_ids[id_] = self.notebook
        self.window = gajim.interface.instances['plugins'].window
        id_ = self.window.connect('destroy', self.on_win_destroy)
        self.connected_ids[id_] = self.window
        self.Gtk_BUILDER_FILE_PATH = self.local_file_path('config_dialog.ui')
        self.xml = gtk.Builder()
        self.xml.set_translation_domain('gajim_plugins')
        self.xml.add_objects_from_file(self.Gtk_BUILDER_FILE_PATH,
            ['hpaned2', 'image1', 'image2'])
        self.hpaned = self.xml.get_object('hpaned2')
        self.page_num = self.notebook.append_page(self.hpaned, gtk.Label(_(
            'Emoticons')))

        widgets_to_extract = (
            'set_name', 'available_treeview', 'homepage_linkbutton',
            'inslall_upgrade_button', 'authors_label', 'converter_label',)

        for widget_name in widgets_to_extract:
            setattr(self, widget_name, self.xml.get_object(widget_name))

        self.model = gtk.ListStore(
            gtk.gdk.Pixbuf, gobject.TYPE_STRING,
            gobject.TYPE_STRING, gobject.TYPE_STRING,
            gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN)
        self.available_treeview.set_model(self.model)
        self.available_treeview.set_rules_hint(True)
        self.model.set_sort_column_id(1, gtk.SORT_ASCENDING)

        #self.progressbar.set_property('no-show-all', True)
        renderer = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_('Name'))
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, 'pixbuf', C_PIXBUF)
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_NAME)
        col.set_property('expand', True)
        col.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
        self.available_treeview.append_column(col)

        renderer = gtk.CellRendererToggle()
        renderer.set_property('activatable', True)
        renderer.connect('toggled', self.available_emoticons_toggled_cb)
        col = gtk.TreeViewColumn(
            _('Install /\nUpgrade'), renderer,  active=C_UPGRADE)
        col.set_property('expand', False)
        col.set_resizable(False)
        self.available_treeview.append_column(col)

        selection = self.available_treeview.get_selection()
        selection.connect(
            'changed', self.available_emoticons_treeview_selection_changed)
        selection.set_mode(gtk.SELECTION_SINGLE)

        self.emoticons_description_textview = ConversationTextview(None)
        sw = self.xml.get_object('scrolledwindow1')
        sw.add(self.emoticons_description_textview.tv)
        self.xml.connect_signals(self)
        self.window.show_all()
Exemplo n.º 9
0
class EmoticonsPackPlugin(GajimPlugin):

    @log_calls('EmoticonsPackPlugin')
    def init(self):
        self.config_dialog = None  # EmoticonsPackPluginConfigDialog(self)
        self.window = None
        self.model = None
        self.connected_ids = {}
        self.tmp_dir = ''

    @log_calls('EmoticonsPackPlugin')
    def activate(self):
        self.pl_menuitem = gajim.interface.roster.xml.get_object(
            'plugins_menuitem')
        self.id_ = self.pl_menuitem.connect_after('activate', self.on_activate)
        if 'plugins' in gajim.interface.instances:
            self.on_activate(None)

    @log_calls('EmoticonsPackPlugin')
    def deactivate(self):
        self.pl_menuitem.disconnect(self.id_)
        if hasattr(self, 'page_num'):
            self.notebook.remove_page(self.notebook.page_num(self.hpaned))
            self.notebook.set_current_page(0)
            for id_, widget in list(self.connected_ids.items()):
                widget.disconnect(id_)
            del self.page_num

    def on_activate(self, widget):
        if 'plugins' not in gajim.interface.instances:
            return
        if hasattr(self, 'page_num'):
            # 'Available' tab exists
            return
        self.installed_plugins_model = gajim.interface.instances[
            'plugins'].installed_plugins_model
        self.notebook = gajim.interface.instances['plugins'].plugins_notebook
        id_ = self.notebook.connect(
            'switch-page', self.on_notebook_switch_page)
        self.connected_ids[id_] = self.notebook
        self.window = gajim.interface.instances['plugins'].window
        id_ = self.window.connect('destroy', self.on_win_destroy)
        self.connected_ids[id_] = self.window
        self.Gtk_BUILDER_FILE_PATH = self.local_file_path('config_dialog.ui')
        self.xml = gtk.Builder()
        self.xml.set_translation_domain('gajim_plugins')
        self.xml.add_objects_from_file(self.Gtk_BUILDER_FILE_PATH,
            ['hpaned2', 'image1', 'image2'])
        self.hpaned = self.xml.get_object('hpaned2')
        self.page_num = self.notebook.append_page(self.hpaned, gtk.Label(_(
            'Emoticons')))

        widgets_to_extract = (
            'set_name', 'available_treeview', 'homepage_linkbutton',
            'inslall_upgrade_button', 'authors_label', 'converter_label',)

        for widget_name in widgets_to_extract:
            setattr(self, widget_name, self.xml.get_object(widget_name))

        self.model = gtk.ListStore(
            gtk.gdk.Pixbuf, gobject.TYPE_STRING,
            gobject.TYPE_STRING, gobject.TYPE_STRING,
            gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN)
        self.available_treeview.set_model(self.model)
        self.available_treeview.set_rules_hint(True)
        self.model.set_sort_column_id(1, gtk.SORT_ASCENDING)

        #self.progressbar.set_property('no-show-all', True)
        renderer = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_('Name'))
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, 'pixbuf', C_PIXBUF)
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_NAME)
        col.set_property('expand', True)
        col.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
        self.available_treeview.append_column(col)

        renderer = gtk.CellRendererToggle()
        renderer.set_property('activatable', True)
        renderer.connect('toggled', self.available_emoticons_toggled_cb)
        col = gtk.TreeViewColumn(
            _('Install /\nUpgrade'), renderer,  active=C_UPGRADE)
        col.set_property('expand', False)
        col.set_resizable(False)
        self.available_treeview.append_column(col)

        selection = self.available_treeview.get_selection()
        selection.connect(
            'changed', self.available_emoticons_treeview_selection_changed)
        selection.set_mode(gtk.SELECTION_SINGLE)

        self.emoticons_description_textview = ConversationTextview(None)
        sw = self.xml.get_object('scrolledwindow1')
        sw.add(self.emoticons_description_textview.tv)
        self.xml.connect_signals(self)
        self.window.show_all()

    def on_legend_button_clicked(self, widget):
        self.xml.get_object('scrolledwindow1').get_children()[0].destroy()

        treeview_selection = self.available_treeview.get_selection()
        model, iter = treeview_selection.get_selected()
        name = model.get_value(iter, C_NAME)

        button = self.xml.get_object('legend_button')
        if button.get_label() == _('Legend'):
            button.set_label(_('Description'))
            sys.path.append(os.path.join(self.tmp_dir, name))

            import emoticons
            imp.reload(emoticons)

            self.emoticons_description_textview = gtk.TextView()
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview)
            sw.show_all()

            buff = self.emoticons_description_textview.get_buffer()
            for icon in emoticons.emoticons:
                icon_file = os.path.join(self.tmp_dir, name, icon)
                with open(icon_file, 'rb') as _file:
                    data = _file.read()
                pbl = gtk.gdk.PixbufLoader()
                pbl.write(data)
                pbl.close()
                if icon.endswith('.gif'):
                    img = gtk.Image()
                    img.set_from_animation(pbl.get_animation())
                    img.show()
                    anchor = buff.create_child_anchor(buff.get_end_iter())
                    self.emoticons_description_textview.add_child_at_anchor(
                        img, anchor)
                else:
                    buff.insert_pixbuf(buff.get_end_iter(), pbl.get_pixbuf())
                text = ' , '.join(emoticons.emoticons[icon])
                buff.insert(buff.get_end_iter(), text + '\n', -1)

            self.emoticons_description_textview.set_property('sensitive', True)
            sys.path.remove(os.path.join(self.tmp_dir, name))

        else:
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            button.set_label(_('Legend'))
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body  '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            desc = desc.replace('preview.image', ('file:' + os.path.join(
                    self.tmp_dir, name, 'preview.png'))).replace('\n', '<br/>')
            self.emoticons_description_textview.tv.display_html(
                desc, self.emoticons_description_textview.tv,
                self.emoticons_description_textview)
            self.emoticons_description_textview.tv.set_property('sensitive', True)

    def dict_to_html(self, dict_):
        desc = ''
        for icon in dict_:
            acr = ' , '.join(dict_[icon])
            desc += ' '+ icon + '  '+ acr + '\n'
        return desc

    def on_inslall_upgrade_clicked(self, widget):
        self.inslall_upgrade_button.set_property('sensitive', False)
        self.errors = ''

        def on_error(func, path, error):
            if func == os.path.islink:
            # if symlink
                os.unlink(path)
                return
            # access is denied or other
            # WarningDialog(_('Can\'t remove dir'), error[1], self.window)
            self.errors += str(error[1])

        name_list = []
        for i in range(len(self.model)):
            if self.model[i][C_UPGRADE]:
                name_list.append(self.model[i][C_NAME])
        for name in name_list:
            # remove dirs
            target_dir = os.path.join(gajim.MY_EMOTS_PATH, name)
            if os.path.isdir(target_dir):
                rmtree(target_dir, False, on_error)

            # unzip new files
            zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
            with zipfile.ZipFile(zip_file, 'r') as myzip:
                namelist = myzip.namelist()
                for n in namelist:
                    if not n.startswith(name):
                        continue
                    try:
                        icon_file = myzip.extract(n, path=gajim.MY_EMOTS_PATH)
                    except Exception as e:
                        self.errors += str(e)
        # unset all checkbattons
        for i in range(len(self.model)):
            self.model[i][C_UPGRADE] = False

        if self.errors:
            WarningDialog(
                _('Not fully installed'),
                'Access is denied or other', self.window)
        else:
            # show dialog
            dialog = HigDialog(
                None,  gtk.MESSAGE_INFO, gtk.BUTTONS_OK, '',
                _('All selected emoticons installed(upgraded)'))
            dialog.set_modal(False)
            dialog.set_transient_for(self.window)
            dialog.popup()

    def on_win_destroy(self, widget):
        if hasattr(self, 'page_num'):
            del self.page_num
        if os.path.isdir(self.tmp_dir):
            rmtree(self.tmp_dir, True)

    def available_emoticons_toggled_cb(self, cell, path):
        is_active = self.model[path][C_UPGRADE]
        self.model[path][C_UPGRADE] = not is_active
        dir_list = []
        for i in range(len(self.model)):
            if self.model[i][C_UPGRADE]:
                dir_list.append(self.model[i][C_NAME])
        if not dir_list:
            self.inslall_upgrade_button.set_property('sensitive', False)
        else:
            self.inslall_upgrade_button.set_property('sensitive', True)

    def on_notebook_switch_page(self, widget, page, page_num):
        tab_label_text = self.notebook.get_tab_label_text(self.hpaned)
        if tab_label_text != (_('Emoticons')):
            return

        self.model.clear()
        self.fill_table()
        self.select_root_iter()

    def fill_table(self):
        conf = ConfigParser.ConfigParser()
        # read metadata from contents.ini
        contents_path = os.path.join(self.__path__, 'contents.ini')
        with open(contents_path) as _file:
            conf.readfp(_file)
        for section in conf.sections():
            # get icon
            try:
                filename = conf.get(section, 'icon')
                filename = section + '/' + filename
                zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
                with zipfile.ZipFile(zip_file, 'r') as myzip:
                    icon_file = myzip.open(filename, mode='r')
                    data = icon_file.read()
                pbl = gtk.gdk.PixbufLoader()
                pbl.set_size(16, 16)
                pbl.write(data)
                pbl.close()
                icon = pbl.get_pixbuf()
            except Exception:
                continue

            authors = _('Unknown')
            converter = _('Unknown')
            if conf.has_option(section, 'authors'):
                authors = conf.get(section, 'authors')
            if conf.has_option(section, 'converter'):
                converter = conf.get(section, 'converter')

            self.model.append(
                [icon, section,
                    conf.get(section, 'description'),
                    authors, converter,
                    conf.get(section, 'homepage'), False])
            conf.remove_section(section)

    def available_emoticons_treeview_selection_changed(self, treeview_selection):
        model, iter = treeview_selection.get_selected()
        button = self.xml.get_object('legend_button')
        button.set_label(_('Legend'))
        if iter:
            set_name = model.get_value(iter, C_NAME)
            if os.path.isdir(self.tmp_dir):
                rmtree(self.tmp_dir, True)
            self.tmp_dir = tempfile.mkdtemp()
             # unzip new files
            zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
            with zipfile.ZipFile(zip_file, 'r') as myzip:
                namelist = myzip.namelist()
                for n in namelist:
                    if not n.startswith(set_name):
                        continue
                    myzip.extract(n, path=self.tmp_dir)

            self.set_name.set_text(set_name)
            self.authors_label.set_text(model.get_value(iter, C_AUTHORS))
            self.converter_label.set_text(model.get_value(iter, C_CONVERTER))
            self.homepage_linkbutton.set_uri(
                model.get_value(iter, C_HOMEPAGE))
            self.homepage_linkbutton.set_label(
                model.get_value(iter, C_HOMEPAGE))
            label = self.homepage_linkbutton.get_children()[0]
            label.set_ellipsize(pango.ELLIPSIZE_END)
            self.homepage_linkbutton.set_property('sensitive', True)

            self.xml.get_object('scrolledwindow1').get_children()[0].destroy()
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            else:
                desc = desc.replace('preview.image', ('file:' + os.path.join(
                    self.tmp_dir, set_name, 'preview.png')))

            self.emoticons_description_textview.tv.display_html(desc,
                self.emoticons_description_textview.tv,
                self.emoticons_description_textview)

            self.emoticons_description_textview.tv.set_property('sensitive', True)
        else:
            self.set_name.set_text('')
            self.authors_label.set_text('')
            self.homepage_linkbutton.set_uri('')
            self.homepage_linkbutton.set_label('')
            self.homepage_linkbutton.set_property('sensitive', False)

    def select_root_iter(self):
        if hasattr(self, 'page_num'):
            selection = self.available_treeview.get_selection()
            if selection.count_selected_rows() == 0:
                root_iter = self.model.get_iter_first()
                selection.select_iter(root_iter)
        scr_win = self.xml.get_object('scrolledwindow2')
        vadjustment = scr_win.get_vadjustment()
        if vadjustment:
            vadjustment.set_value(0)
Exemplo n.º 10
0
    def on_activate(self, widget):
        if 'plugins' not in gajim.interface.instances:
            return
        if hasattr(self, 'page_num'):
            # 'Available' tab exists
            return
        self.installed_plugins_model = gajim.interface.instances[
            'plugins'].installed_plugins_model
        self.notebook = gajim.interface.instances['plugins'].plugins_notebook
        id_ = self.notebook.connect('switch-page',
                                    self.on_notebook_switch_page)
        self.connected_ids[id_] = self.notebook
        self.window = gajim.interface.instances['plugins'].window
        id_ = self.window.connect('destroy', self.on_win_destroy)
        self.connected_ids[id_] = self.window
        self.Gtk_BUILDER_FILE_PATH = self.local_file_path('config_dialog.ui')
        self.xml = gtk.Builder()
        self.xml.set_translation_domain('gajim_plugins')
        self.xml.add_objects_from_file(self.Gtk_BUILDER_FILE_PATH,
                                       ['hpaned2', 'image1', 'image2'])
        self.hpaned = self.xml.get_object('hpaned2')
        self.page_num = self.notebook.append_page(self.hpaned,
                                                  gtk.Label(_('Emoticons')))

        widgets_to_extract = (
            'set_name',
            'available_treeview',
            'homepage_linkbutton',
            'inslall_upgrade_button',
            'authors_label',
            'converter_label',
        )

        for widget_name in widgets_to_extract:
            setattr(self, widget_name, self.xml.get_object(widget_name))

        self.model = gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING,
                                   gobject.TYPE_STRING, gobject.TYPE_STRING,
                                   gobject.TYPE_STRING, gobject.TYPE_STRING,
                                   gobject.TYPE_BOOLEAN)
        self.available_treeview.set_model(self.model)
        self.available_treeview.set_rules_hint(True)
        self.model.set_sort_column_id(1, gtk.SORT_ASCENDING)

        #self.progressbar.set_property('no-show-all', True)
        renderer = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_('Name'))
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, 'pixbuf', C_PIXBUF)
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_NAME)
        col.set_property('expand', True)
        col.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
        self.available_treeview.append_column(col)

        renderer = gtk.CellRendererToggle()
        renderer.set_property('activatable', True)
        renderer.connect('toggled', self.available_emoticons_toggled_cb)
        col = gtk.TreeViewColumn(_('Install /\nUpgrade'),
                                 renderer,
                                 active=C_UPGRADE)
        col.set_property('expand', False)
        col.set_resizable(False)
        self.available_treeview.append_column(col)

        selection = self.available_treeview.get_selection()
        selection.connect('changed',
                          self.available_emoticons_treeview_selection_changed)
        selection.set_mode(gtk.SELECTION_SINGLE)

        self.emoticons_description_textview = ConversationTextview(None)
        sw = self.xml.get_object('scrolledwindow1')
        sw.add(self.emoticons_description_textview.tv)
        self.xml.connect_signals(self)
        self.window.show_all()
Exemplo n.º 11
0
class EmoticonsPackPlugin(GajimPlugin):
    @log_calls('EmoticonsPackPlugin')
    def init(self):
        self.config_dialog = None  # EmoticonsPackPluginConfigDialog(self)
        self.window = None
        self.model = None
        self.connected_ids = {}
        self.tmp_dir = ''

    @log_calls('EmoticonsPackPlugin')
    def activate(self):
        self.pl_menuitem = gajim.interface.roster.xml.get_object(
            'plugins_menuitem')
        self.id_ = self.pl_menuitem.connect_after('activate', self.on_activate)
        if 'plugins' in gajim.interface.instances:
            self.on_activate(None)

    @log_calls('EmoticonsPackPlugin')
    def deactivate(self):
        self.pl_menuitem.disconnect(self.id_)
        if hasattr(self, 'page_num'):
            self.notebook.remove_page(self.notebook.page_num(self.hpaned))
            self.notebook.set_current_page(0)
            for id_, widget in list(self.connected_ids.items()):
                widget.disconnect(id_)
            del self.page_num

    def on_activate(self, widget):
        if 'plugins' not in gajim.interface.instances:
            return
        if hasattr(self, 'page_num'):
            # 'Available' tab exists
            return
        self.installed_plugins_model = gajim.interface.instances[
            'plugins'].installed_plugins_model
        self.notebook = gajim.interface.instances['plugins'].plugins_notebook
        id_ = self.notebook.connect('switch-page',
                                    self.on_notebook_switch_page)
        self.connected_ids[id_] = self.notebook
        self.window = gajim.interface.instances['plugins'].window
        id_ = self.window.connect('destroy', self.on_win_destroy)
        self.connected_ids[id_] = self.window
        self.Gtk_BUILDER_FILE_PATH = self.local_file_path('config_dialog.ui')
        self.xml = gtk.Builder()
        self.xml.set_translation_domain('gajim_plugins')
        self.xml.add_objects_from_file(self.Gtk_BUILDER_FILE_PATH,
                                       ['hpaned2', 'image1', 'image2'])
        self.hpaned = self.xml.get_object('hpaned2')
        self.page_num = self.notebook.append_page(self.hpaned,
                                                  gtk.Label(_('Emoticons')))

        widgets_to_extract = (
            'set_name',
            'available_treeview',
            'homepage_linkbutton',
            'inslall_upgrade_button',
            'authors_label',
            'converter_label',
        )

        for widget_name in widgets_to_extract:
            setattr(self, widget_name, self.xml.get_object(widget_name))

        self.model = gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING,
                                   gobject.TYPE_STRING, gobject.TYPE_STRING,
                                   gobject.TYPE_STRING, gobject.TYPE_STRING,
                                   gobject.TYPE_BOOLEAN)
        self.available_treeview.set_model(self.model)
        self.available_treeview.set_rules_hint(True)
        self.model.set_sort_column_id(1, gtk.SORT_ASCENDING)

        #self.progressbar.set_property('no-show-all', True)
        renderer = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_('Name'))
        cell = gtk.CellRendererPixbuf()
        col.pack_start(cell, False)
        col.add_attribute(cell, 'pixbuf', C_PIXBUF)
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', C_NAME)
        col.set_property('expand', True)
        col.set_sizing(gtk.TREE_VIEW_COLUMN_GROW_ONLY)
        self.available_treeview.append_column(col)

        renderer = gtk.CellRendererToggle()
        renderer.set_property('activatable', True)
        renderer.connect('toggled', self.available_emoticons_toggled_cb)
        col = gtk.TreeViewColumn(_('Install /\nUpgrade'),
                                 renderer,
                                 active=C_UPGRADE)
        col.set_property('expand', False)
        col.set_resizable(False)
        self.available_treeview.append_column(col)

        selection = self.available_treeview.get_selection()
        selection.connect('changed',
                          self.available_emoticons_treeview_selection_changed)
        selection.set_mode(gtk.SELECTION_SINGLE)

        self.emoticons_description_textview = ConversationTextview(None)
        sw = self.xml.get_object('scrolledwindow1')
        sw.add(self.emoticons_description_textview.tv)
        self.xml.connect_signals(self)
        self.window.show_all()

    def on_legend_button_clicked(self, widget):
        self.xml.get_object('scrolledwindow1').get_children()[0].destroy()

        treeview_selection = self.available_treeview.get_selection()
        model, iter = treeview_selection.get_selected()
        name = model.get_value(iter, C_NAME)

        button = self.xml.get_object('legend_button')
        if button.get_label() == _('Legend'):
            button.set_label(_('Description'))
            sys.path.append(os.path.join(self.tmp_dir, name))

            import emoticons
            imp.reload(emoticons)

            self.emoticons_description_textview = gtk.TextView()
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview)
            sw.show_all()

            buff = self.emoticons_description_textview.get_buffer()
            for icon in emoticons.emoticons:
                icon_file = os.path.join(self.tmp_dir, name, icon)
                with open(icon_file, 'rb') as _file:
                    data = _file.read()
                pbl = gtk.gdk.PixbufLoader()
                pbl.write(data)
                pbl.close()
                if icon.endswith('.gif'):
                    img = gtk.Image()
                    img.set_from_animation(pbl.get_animation())
                    img.show()
                    anchor = buff.create_child_anchor(buff.get_end_iter())
                    self.emoticons_description_textview.add_child_at_anchor(
                        img, anchor)
                else:
                    buff.insert_pixbuf(buff.get_end_iter(), pbl.get_pixbuf())
                text = ' , '.join(emoticons.emoticons[icon])
                buff.insert(buff.get_end_iter(), text + '\n', -1)

            self.emoticons_description_textview.set_property('sensitive', True)
            sys.path.remove(os.path.join(self.tmp_dir, name))

        else:
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            button.set_label(_('Legend'))
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body  '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            desc = desc.replace(
                'preview.image',
                ('file:' +
                 os.path.join(self.tmp_dir, name, 'preview.png'))).replace(
                     '\n', '<br/>')
            self.emoticons_description_textview.tv.display_html(
                desc, self.emoticons_description_textview.tv,
                self.emoticons_description_textview)
            self.emoticons_description_textview.tv.set_property(
                'sensitive', True)

    def dict_to_html(self, dict_):
        desc = ''
        for icon in dict_:
            acr = ' , '.join(dict_[icon])
            desc += ' ' + icon + '  ' + acr + '\n'
        return desc

    def on_inslall_upgrade_clicked(self, widget):
        self.inslall_upgrade_button.set_property('sensitive', False)
        self.errors = ''

        def on_error(func, path, error):
            if func == os.path.islink:
                # if symlink
                os.unlink(path)
                return
            # access is denied or other
            # WarningDialog(_('Can\'t remove dir'), error[1], self.window)
            self.errors += str(error[1])

        name_list = []
        for i in range(len(self.model)):
            if self.model[i][C_UPGRADE]:
                name_list.append(self.model[i][C_NAME])
        for name in name_list:
            # remove dirs
            target_dir = os.path.join(gajim.MY_EMOTS_PATH, name)
            if os.path.isdir(target_dir):
                rmtree(target_dir, False, on_error)

            # unzip new files
            zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
            with zipfile.ZipFile(zip_file, 'r') as myzip:
                namelist = myzip.namelist()
                for n in namelist:
                    if not n.startswith(name):
                        continue
                    try:
                        icon_file = myzip.extract(n, path=gajim.MY_EMOTS_PATH)
                    except Exception as e:
                        self.errors += str(e)
        # unset all checkbattons
        for i in range(len(self.model)):
            self.model[i][C_UPGRADE] = False

        if self.errors:
            WarningDialog(_('Not fully installed'),
                          'Access is denied or other', self.window)
        else:
            # show dialog
            dialog = HigDialog(None, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, '',
                               _('All selected emoticons installed(upgraded)'))
            dialog.set_modal(False)
            dialog.set_transient_for(self.window)
            dialog.popup()

    def on_win_destroy(self, widget):
        if hasattr(self, 'page_num'):
            del self.page_num
        if os.path.isdir(self.tmp_dir):
            rmtree(self.tmp_dir, True)

    def available_emoticons_toggled_cb(self, cell, path):
        is_active = self.model[path][C_UPGRADE]
        self.model[path][C_UPGRADE] = not is_active
        dir_list = []
        for i in range(len(self.model)):
            if self.model[i][C_UPGRADE]:
                dir_list.append(self.model[i][C_NAME])
        if not dir_list:
            self.inslall_upgrade_button.set_property('sensitive', False)
        else:
            self.inslall_upgrade_button.set_property('sensitive', True)

    def on_notebook_switch_page(self, widget, page, page_num):
        tab_label_text = self.notebook.get_tab_label_text(self.hpaned)
        if tab_label_text != (_('Emoticons')):
            return

        self.model.clear()
        self.fill_table()
        self.select_root_iter()

    def fill_table(self):
        conf = ConfigParser.ConfigParser()
        # read metadata from contents.ini
        contents_path = os.path.join(self.__path__, 'contents.ini')
        with open(contents_path) as _file:
            conf.readfp(_file)
        for section in conf.sections():
            # get icon
            try:
                filename = conf.get(section, 'icon')
                filename = section + '/' + filename
                zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
                with zipfile.ZipFile(zip_file, 'r') as myzip:
                    icon_file = myzip.open(filename, mode='r')
                    data = icon_file.read()
                pbl = gtk.gdk.PixbufLoader()
                pbl.set_size(16, 16)
                pbl.write(data)
                pbl.close()
                icon = pbl.get_pixbuf()
            except Exception:
                continue

            authors = _('Unknown')
            converter = _('Unknown')
            if conf.has_option(section, 'authors'):
                authors = conf.get(section, 'authors')
            if conf.has_option(section, 'converter'):
                converter = conf.get(section, 'converter')

            self.model.append([
                icon, section,
                conf.get(section, 'description'), authors, converter,
                conf.get(section, 'homepage'), False
            ])
            conf.remove_section(section)

    def available_emoticons_treeview_selection_changed(self,
                                                       treeview_selection):
        model, iter = treeview_selection.get_selected()
        button = self.xml.get_object('legend_button')
        button.set_label(_('Legend'))
        if iter:
            set_name = model.get_value(iter, C_NAME)
            if os.path.isdir(self.tmp_dir):
                rmtree(self.tmp_dir, True)
            self.tmp_dir = tempfile.mkdtemp()
            # unzip new files
            zip_file = os.path.join(self.__path__, 'emoticons_pack.zip')
            with zipfile.ZipFile(zip_file, 'r') as myzip:
                namelist = myzip.namelist()
                for n in namelist:
                    if not n.startswith(set_name):
                        continue
                    myzip.extract(n, path=self.tmp_dir)

            self.set_name.set_text(set_name)
            self.authors_label.set_text(model.get_value(iter, C_AUTHORS))
            self.converter_label.set_text(model.get_value(iter, C_CONVERTER))
            self.homepage_linkbutton.set_uri(model.get_value(iter, C_HOMEPAGE))
            self.homepage_linkbutton.set_label(
                model.get_value(iter, C_HOMEPAGE))
            label = self.homepage_linkbutton.get_children()[0]
            label.set_ellipsize(pango.ELLIPSIZE_END)
            self.homepage_linkbutton.set_property('sensitive', True)

            self.xml.get_object('scrolledwindow1').get_children()[0].destroy()
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            else:
                desc = desc.replace(
                    'preview.image',
                    ('file:' +
                     os.path.join(self.tmp_dir, set_name, 'preview.png')))

            self.emoticons_description_textview.tv.display_html(
                desc, self.emoticons_description_textview.tv,
                self.emoticons_description_textview)

            self.emoticons_description_textview.tv.set_property(
                'sensitive', True)
        else:
            self.set_name.set_text('')
            self.authors_label.set_text('')
            self.homepage_linkbutton.set_uri('')
            self.homepage_linkbutton.set_label('')
            self.homepage_linkbutton.set_property('sensitive', False)

    def select_root_iter(self):
        if hasattr(self, 'page_num'):
            selection = self.available_treeview.get_selection()
            if selection.count_selected_rows() == 0:
                root_iter = self.model.get_iter_first()
                selection.select_iter(root_iter)
        scr_win = self.xml.get_object('scrolledwindow2')
        vadjustment = scr_win.get_vadjustment()
        if vadjustment:
            vadjustment.set_value(0)
Exemplo n.º 12
0
    def on_legend_button_clicked(self, widget):
        self.xml.get_object('scrolledwindow1').get_children()[0].destroy()

        treeview_selection = self.available_treeview.get_selection()
        model, iter = treeview_selection.get_selected()
        name = model.get_value(iter, C_NAME)

        button = self.xml.get_object('legend_button')
        if button.get_label() == _('Legend'):
            button.set_label(_('Description'))
            sys.path.append(os.path.join(self.tmp_dir, name))

            import emoticons
            imp.reload(emoticons)

            self.emoticons_description_textview = gtk.TextView()
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview)
            sw.show_all()

            buff = self.emoticons_description_textview.get_buffer()
            for icon in emoticons.emoticons:
                icon_file = os.path.join(self.tmp_dir, name, icon)
                with open(icon_file, 'rb') as _file:
                    data = _file.read()
                pbl = gtk.gdk.PixbufLoader()
                pbl.write(data)
                pbl.close()
                if icon.endswith('.gif'):
                    img = gtk.Image()
                    img.set_from_animation(pbl.get_animation())
                    img.show()
                    anchor = buff.create_child_anchor(buff.get_end_iter())
                    self.emoticons_description_textview.add_child_at_anchor(
                        img, anchor)
                else:
                    buff.insert_pixbuf(buff.get_end_iter(), pbl.get_pixbuf())
                text = ' , '.join(emoticons.emoticons[icon])
                buff.insert(buff.get_end_iter(), text + '\n', -1)

            self.emoticons_description_textview.set_property('sensitive', True)
            sys.path.remove(os.path.join(self.tmp_dir, name))

        else:
            self.emoticons_description_textview = ConversationTextview(None)
            sw = self.xml.get_object('scrolledwindow1')
            sw.add(self.emoticons_description_textview.tv)
            sw.show_all()
            button.set_label(_('Legend'))
            desc = _(model.get_value(iter, C_DESCRIPTION))
            if not desc.startswith('<body  '):
                desc = '<body  xmlns=\'http://www.w3.org/1999/xhtml\'>' + \
                    desc + ' </body>'
            desc = desc.replace(
                'preview.image',
                ('file:' +
                 os.path.join(self.tmp_dir, name, 'preview.png'))).replace(
                     '\n', '<br/>')
            self.emoticons_description_textview.tv.display_html(
                desc, self.emoticons_description_textview.tv,
                self.emoticons_description_textview)
            self.emoticons_description_textview.tv.set_property(
                'sensitive', True)