class ManView(PidaView): icon_name = 'gtk-library' label_text = 'Man' def create_ui(self): self._count = 0 self.__vbox = gtk.VBox(spacing=3) self.__vbox.set_border_width(6) self.__hbox = gtk.HBox() self.__entry = gtk.Entry() self.__entry.connect('changed', self.cb_entry_changed) self.__check = gtk.CheckButton(label='-k') self.__check.connect('toggled', self.cb_entry_changed) self.__list = ObjectList([ Column('markup', title=_('Man page'), sorted=True, use_markup=True), Column('description', title=_('Description'), use_markup=True), ]) self.__list.connect('double-click', self._on_man_double_click) self.__list.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.__hbox.pack_start(self.__entry) self.__hbox.pack_start(self.__check, expand=False) self.__vbox.pack_start(self.__hbox, expand=False) self.__vbox.pack_start(self.__list) self.add_main_widget(self.__vbox) self.__vbox.show_all() def clear_items(self): self._count = 0 self.__list.clear() def add_item(self, item): self._count += 1 self.__list.append(item) def _on_man_double_click(self, olist, item): commandargs = ['/usr/bin/env', 'man', item.number, item.pattern] directory = os.path.dirname(commandargs[0]) self.svc.boss.cmd('commander', 'execute', commandargs=commandargs, cwd=directory, icon='gnome-library', title='%(pattern)s(%(number)d)' % dict( pattern=item.pattern, number=int(item.number) )) def cb_entry_changed(self, w): options = '-f' if self.__check.get_active(): options = '-k' self.svc.cmd_find(options=options, pattern=self.__entry.get_text()) def can_be_closed(self): self.svc.get_action('show_man').set_active(False)
class PyflakeView(PidaView): icon_name = 'python-icon' label_text = _('Python Errors') def create_ui(self): self.errors_ol = ObjectList( Column('markup', use_markup=True) ) self.errors_ol.set_headers_visible(False) self.errors_ol.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.add_main_widget(self.errors_ol) self.errors_ol.connect('double-click', self._on_errors_double_clicked) self.errors_ol.show_all() self.sort_combo = AttrSortCombo( self.errors_ol, [ ('lineno', _('Line Number')), ('message_string', _('Message')), ('name', _('Type')), ], 'lineno', ) self.sort_combo.show() self.add_main_widget(self.sort_combo, expand=False) def clear_items(self): self.errors_ol.clear() def set_items(self, items): self.clear_items() for item in items: self.errors_ol.append(self.decorate_pyflake_message(item)) def decorate_pyflake_message(self, msg): args = [('<b>%s</b>' % arg) for arg in msg.message_args] msg.message_string = msg.message % tuple(args) msg.name = msg.__class__.__name__ msg.markup = ('<tt>%s </tt><i>%s</i>\n%s' % (msg.lineno, msg.name, msg.message_string)) return msg def _on_errors_double_clicked(self, ol, item): self.svc.boss.editor.cmd('goto_line', line=item.lineno) def can_be_closed(self): self.svc.get_action('show_python_errors').set_active(False)
class PropertiesAdminGtkNode(BaseAdminGtkNode): gladeFile = os.path.join('flumotion', 'component', 'base', 'properties.glade') uiStateHandlers = None _properties = {} def __init__(self, state, admin): BaseAdminGtkNode.__init__(self, state, admin, title=_("Properties")) def haveWidgetTree(self): self.widget = gtk.VBox() self.widget.set_border_width(6) self.properties = ObjectList( [Column('name'), Column('value')]) self.properties.set_size_request(-1, 200) self.widget.pack_start(self.properties, False, False) self.properties.show() self._reloadProperties(self.state.get('config')['properties']) return self.widget # IStateListener Interface def stateSet(self, object, key, value): if key == 'properties': self._reloadProperties(value) ### Private methods def _reloadProperties(self, properties): if properties is None: return self.properties.clear() propertyNames = properties.keys()[:] propertyNames.sort() for name in propertyNames: self.properties.append( Settable(name=name, value=properties[name]))
class Package(SlaveView): columns = [ Column("name", sorted=True), Column("version"), Column("installed"), Column("description") ] def __init__(self): self.list = ObjectList(self.columns) self.list.connect('selection-changed', self.info) self.to_install = "" # selecting categories f = urllib.urlopen("http://pacnet.karbownicki.com/api/category/app-accessibility/").read() packages=json.loads(f) for category in packages: got = local.check(category['name']) row = PackageItem(category['name'], category['version'], got, category['description']) self.list.append(row) SlaveView.__init__(self, self.list) def info(self, the_list, item): command = ["pacman", "-Si", item.name] pkg_info, errors = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() shell.get_widget("info").get_buffer().set_text(pkg_info) self.to_install = item.name def new_list(self, category): self.list.clear() f = urllib.urlopen("http://pacnet.karbownicki.com/api/category/%s/" % category).read() packages=json.loads(f) for category in packages: got = local.check(category['name']) row = PackageItem(category['name'], category['version'], got, category['description']) self.list.append(row)
class MethodTest(unittest.TestCase): def setUp(self): self.klist = ObjectList([Column('name', sorted=True)], [Settable(name='first')]) def testNonZero(self): self.assertEqual(self.klist.__nonzero__(), True) self.klist.remove(self.klist[0]) self.assertEqual(self.klist.__nonzero__(), True) if not self.klist: raise AssertionError def testIter(self): for item1 in self.klist: pass for item2 in iter(self.klist): self.assertEqual(item1, item2) def testGetItem(self): self.klist.append(Settable(name='second')) model = self.klist.get_model() item1 = model[0][0] item2 = model[1][0] self.assertEqual(self.klist[0], item1) self.assertEqual(self.klist[:1], [item1]) self.assertEqual(self.klist[-1:], [item2]) self.assertRaises(TypeError, self.klist.__getitem__, None) def testSetItem(self): self.klist[0] = Settable(name='second') self.assertRaises(NotImplementedError, self.klist.__setitem__, slice(0), None) self.assertRaises(TypeError, self.klist.__setitem__, None, None) def testIndex(self): self.assertRaises(NotImplementedError, self.klist.index, 0, start=0) self.assertRaises(NotImplementedError, self.klist.index, 0, stop=0) self.assertEqual(self.klist.index(self.klist[0]), 0) self.assertRaises(ValueError, self.klist.index, None) def testCount(self): item = self.klist[0] self.assertEqual(self.klist.count(item), 1) self.klist.append(item) self.assertEqual(self.klist.count(item), 2) self.klist.clear() self.assertEqual(self.klist.count(item), 0) def testPop(self): self.assertRaises(NotImplementedError, self.klist.pop, None) def testReverse(self): self.assertRaises(NotImplementedError, self.klist.reverse, 1, 2) def testSort(self): self.assertRaises(NotImplementedError, self.klist.sort, 1, 2) def testSelectPath(self): self.klist.get_treeview().get_selection().set_mode(gtk.SELECTION_NONE) self.assertRaises(TypeError, self.klist.select_paths, (0,)) self.klist.get_treeview().get_selection().set_mode(gtk.SELECTION_SINGLE) self.klist.select_paths((0,)) def testSelect(self): self.klist.get_treeview().get_selection().set_mode(gtk.SELECTION_NONE) self.assertRaises(TypeError, self.klist.select, None) self.klist.get_treeview().get_selection().set_mode(gtk.SELECTION_SINGLE) def testGetSelected(self): item = self.klist[0] self.klist.select(item) self.klist.get_treeview().get_selection().set_mode(gtk.SELECTION_SINGLE) self.assertEqual(self.klist.get_selected(), item) def testGetSelectedRows(self): self.klist.get_treeview().get_selection().set_mode(gtk.SELECTION_MULTIPLE) item = self.klist[0] self.klist.select(item) self.assertEqual(self.klist.get_selected_rows(), [item]) def testGetNextAndPrevious(self): self.klist.append(Settable(name='second')) self.klist.append(Settable(name='third')) item1, item2, item3 = self.klist self.assertEqual(self.klist.get_next(item1), item2) self.assertEqual(self.klist.get_next(item2), item3) self.assertEqual(self.klist.get_next(item3), item1) self.assertRaises(ValueError, self.klist.get_next, None) self.assertEqual(self.klist.get_previous(item1), item3) self.assertEqual(self.klist.get_previous(item2), item1) self.assertEqual(self.klist.get_previous(item3), item2) self.assertRaises(ValueError, self.klist.get_previous, None) def testInsert(self): self.klist = ObjectList([Column('name')]) self.assertEqual(list(self.klist), []) self.klist.insert(0, Settable(name='one')) self.assertEqual(self.klist[0].name, 'one') self.klist.insert(0, Settable(name='two')) self.assertEqual(self.klist[0].name, 'two') self.assertEqual(self.klist[1].name, 'one') self.klist.insert(1, Settable(name='three')) self.assertEqual(self.klist[0].name, 'two') self.assertEqual(self.klist[1].name, 'three') self.assertEqual(self.klist[2].name, 'one')
class ListContainer(gtk.HBox): """A ListContainer is an L{ObjectList} with buttons to be able to modify the content of the list. Depending on the list_mode, @see L{set_list_mode} you will have add, remove and edit buttons. Signals ======= - B{add-item} (returns item): - emitted when the add button is clicked, you're expected to return an object here - B{remove-item} (item, returns bool): - emitted when removing an item, you can block the removal from the list by returning False - B{edit-item} (item): - emitted when editing an item you can block the update afterwards by returning False @ivar add_button: add button @type add_button: L{gtk.Button} @ivar remove_button: remove button @type remove_button: L{gtk.Button} @ivar edit_button: edit button @type edit_button: L{gtk.Button} """ gsignal('add-item', retval=object) gsignal('remove-item', object, retval=bool) gsignal('edit-item', object, retval=bool) gsignal('selection-changed', object) def __init__(self, columns, orientation=gtk.ORIENTATION_VERTICAL): """ Create a new ListContainer object. @param columns: columns for the L{kiwi.ui.objectlist.ObjectList} @type columns: a list of L{kiwi.ui.objectlist.Columns} @param orientation: the position where the buttons will be placed: at the right (vertically) or at the bottom (horizontally) of the list. Defaults to the right of the list. @type: gtk.ORIENTATION_HORIZONTAL or gtk.ORIENTATION_VERTICAL """ self._list_type = None gtk.HBox.__init__(self) self._orientation = orientation self._create_ui(columns) self.set_list_type(ListType.NORMAL) # Private API def _create_ui(self, columns): self.list = ObjectList(columns) self.list.connect('selection-changed', self._on_list__selection_changed) self.list.connect('row-activated', self._on_list__row_activated) self.add_button = gtk.Button(stock=gtk.STOCK_ADD) self.add_button.connect('clicked', self._on_add_button__clicked) self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE) self.remove_button.set_sensitive(False) self.remove_button.connect('clicked', self._on_remove_button__clicked) self.edit_button = gtk.Button(stock=gtk.STOCK_EDIT) self.edit_button.set_sensitive(False) self.edit_button.connect('clicked', self._on_edit_button__clicked) self._vbox = gtk.VBox(spacing=6) if self._orientation == gtk.ORIENTATION_VERTICAL: self.pack_start(self.list) self.list.show() self._add_buttons_to_box(self._vbox) self._pack_vbox() elif self._orientation == gtk.ORIENTATION_HORIZONTAL: self._vbox.pack_start(self.list) self.list.show() hbox = gtk.HBox(spacing=6) self._add_buttons_to_box(hbox) self._vbox.pack_start(hbox, expand=False) hbox.show() self._pack_vbox() else: raise TypeError( "buttons_orientation must be gtk.ORIENTATION_VERTICAL " " or gtk.ORIENTATION_HORIZONTAL") def _add_buttons_to_box(self, box): box.pack_start(self.add_button, expand=False) box.pack_start(self.remove_button, expand=False) box.pack_start(self.edit_button, expand=False) def _pack_vbox(self): self.pack_start(self._vbox, expand=False, padding=6) self._vbox.show() def _set_child_packing(self, padding): expand = self._orientation == gtk.ORIENTATION_HORIZONTAL self.set_child_packing(self._vbox, expand, True, padding, gtk.PACK_START) def _add_item(self): retval = self.emit('add-item') if retval is None: return elif isinstance(retval, NotImplementedError): raise retval self.list.append(retval) def _remove_item(self, item): retval = self.emit('remove-item', item) if retval: self.list.remove(item) def _edit_item(self, item): retval = self.emit('edit-item', item) if retval: self.list.update(item) # Public API def add_item(self, item): """Appends an item to the list @param item: item to append """ self.list.append(item) def add_items(self, items): """Appends a list of items to the list @param items: items to add @type items: a sequence of items """ self.list.extend(items) def remove_item(self, item): """Removes an item from the list @param item: item to remove """ self.list.remove(item) def update_item(self, item): """Updates an item in the list. You should call this if you change the object @param item: item to update """ self.list.update(item) def default_remove(self, item): """Asks the user confirmation for removal of an item. @param item: a description of the item that will be removed @returns: True if the user confirm the removal, False otherwise """ response = yesno(_('Do you want to remove %s ?') % (quote(str(item)), ), parent=None, default=gtk.RESPONSE_OK, buttons=((gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), (gtk.STOCK_REMOVE, gtk.RESPONSE_OK))) return response == gtk.RESPONSE_OK def set_list_type(self, list_type): """Sets the kind of list type. @param list_type: """ if not isinstance(list_type, ListType): raise TypeError("list_type must be a ListType enum") self.add_button.set_property('visible', (list_type != ListType.READONLY and list_type != ListType.REMOVEONLY and list_type != ListType.UNADDABLE)) self.remove_button.set_property( 'visible', (list_type != ListType.READONLY and list_type != ListType.UNREMOVABLE)) self.edit_button.set_property('visible', (list_type != ListType.READONLY and list_type != ListType.UNEDITABLE and list_type != ListType.REMOVEONLY)) if list_type in [ListType.READONLY, ListType.REMOVEONLY]: padding = 0 else: padding = 6 self._set_child_packing(padding) self._list_type = list_type def clear(self): """Removes all the items in the list""" self.list.clear() # Callbacks def _on_list__selection_changed(self, list, selection): object_selected = selection is not None self.remove_button.set_sensitive(object_selected) self.edit_button.set_sensitive(object_selected) self.emit('selection-changed', selection) def _on_list__row_activated(self, list, item): if (self._list_type != ListType.READONLY and self._list_type != ListType.UNEDITABLE): self._edit_item(item) def _on_add_button__clicked(self, button): self._add_item() def _on_remove_button__clicked(self, button): self._remove_item(self.list.get_selected()) def _on_edit_button__clicked(self, button): self._edit_item(self.list.get_selected())
class VirtLabView(BaseView): ''' MVC View ''' def __init__(self, model): self.__model = model #self.__model.set_view(self) BaseView.__init__(self, gladefile="virtlab", delete_handler=self.quit_if_last) # self.__col_pixbuf = gtk.TreeViewColumn("Image") # cellrenderer_pixbuf = gtk.CellRendererPixbuf() # cellrenderer_pixbuf.set_properties("pixbuf", ) # self.__col_pixbuf.pack_start(cellrenderer_pixbuf, False) # self.__col_pixbuf.add_attribute(cellrenderer_pixbuf, "pixbuf", 1) tableColumns = [ Column("image", title=" ", width=30, data_type=gtk.gdk.Pixbuf, sorted=False), Column("name", title='VM Name', width=130, sorted=True), Column("state", title='State', width=70), Column("order", title='Order (Delay/min)', width=145), Column("ordinal", visible=False), Column("delay", visible=False), Column("desc", title='Description', width=200) ] self.vmlist_widget = ObjectList(tableColumns) self.vmlist_widget.set_size_request(300, 400) self.vmlist_widget.set_selection_mode(gtk.SELECTION_SINGLE) self.hbox4.pack_start(self.vmlist_widget) store = gtk.ListStore(gobject.TYPE_STRING) self.vmlist_widget.show() self.__dialog = None self.__status_text = gtk.TextBuffer() try: self.populate_vmlist() self.populate_order_dropdown(store, len(self.__model.get_vms())) except VMLabException as exception: if exception.vme_id is c.EXCEPTION_LIBVIRT_001: error("Initialization error", "No connection to Libvirtd.\n Exiting.") exit(1) self.ordercombo.set_model(store) cell = gtk.CellRendererText() self.ordercombo.pack_start(cell, True) self.ordercombo.add_attribute(cell, 'text', 0) self.virtlab.set_size_request(800, 460) self.change_title("") self.__statusbar_ctx = self.statusbar.get_context_id("virtlab") self.virtlab.set_icon(gtk.gdk.pixbuf_new_from_file("pixmaps/about-logo.png")) def __delaystring(self, delay): if delay > 0: return " (" + str(delay) + ")" else: return "" def change_title(self, value): if value == "" or None: self.virtlab.set_title(c.WINDOW_TITLE) else: self.virtlab.set_title(c.WINDOW_TITLE + "(" + value + ")") def dialog_filechooser_open(self): chooser = gtk.FileChooserDialog(title="Open VMLab Project", action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) filter = gtk.FileFilter() filter.add_pattern("*"+c.SAVE_FILE_SUFFIX) chooser.set_filter(filter) file_name = "" response = chooser.run() if response == gtk.RESPONSE_OK: file_name = chooser.get_filename() chooser.destroy() return file_name elif response == gtk.RESPONSE_CANCEL: chooser.destroy() return def dialog_filechooser_save(self): chooser = gtk.FileChooserDialog(title="Save VMLab Project", action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_CANCEL) filter = gtk.FileFilter() filter.add_pattern("*"+c.SAVE_FILE_SUFFIX) file_name = "" response = chooser.run() if response == gtk.RESPONSE_OK: file_name = chooser.get_filename() chooser.destroy() return file_name elif response == gtk.RESPONSE_CANCEL: chooser.destroy() return elif response == gtk.RESPONSE_CLOSE: chooser.destroy() return def populate_vmlist(self): ''' Populates view with current status ''' self.vmlist_widget.clear() for vm_instance in self.__model.get_vms(): self.vmlist_widget.append(Settable(image=populate_image(vm_instance.get_state()), name=vm_instance.get_name(), state=vm_instance.get_state().get_state_str(), order=self.get_display_order(vm_instance.get_order()) + self.__delaystring(vm_instance.get_delay()), ordinal=vm_instance.get_order(), delay=vm_instance.get_delay(), desc=vm_instance.get_desc())) def populate_order_dropdown(self, list_store, vm_count): list_store.clear() list_store.append([""]) if vm_count > 0: for num in range(1, vm_count + 1): list_store.append([self.get_display_order(num)]) def add_status_dialogbox(self, text): field_content = self.__status_text.get_text(self.__status_text.get_start_iter(), self.__status_text.get_end_iter(), False) field_content += strftime("%d %b %Y %H:%M:%S", localtime()) + " " + text + "\n" self.__status_text.set_text(field_content) def clear_dialog_log(self): self.__status_text.set_text("") def show_dialog(self): self.__dialog = gtk.Dialog(title="Launch status", parent=self.virtlab, flags=gtk.DIALOG_MODAL, buttons=None) self.__dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT) self.__dialog.set_transient_for(self.virtlab) close_button = gtk.Button("Close window") terminate_button = gtk.Button("Terminate") clear_button = gtk.Button("Clear log") start_button = gtk.Button("Launch scheduled") start_once_button = gtk.Button("Launch all once") close_button.connect("clicked", lambda d, r: r.destroy(), self.__dialog) clear_button.connect("clicked", lambda d, r: r.clear_dialog_log(), self) terminate_button.connect("clicked", self.controller.hook_dialog_terminate_clicked, None) start_button.connect("clicked", self.controller.hook_dialog_start_clicked, None) start_once_button.connect("clicked", self.controller.hook_dialog_all_start_clicked, None) scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None) scrolled_window.set_policy(gtk.POLICY_NEVER, gtk.POLICY_ALWAYS) text_view = gtk.TextView() scrolled_window.add_with_viewport(text_view) scrolled_window.show() text_view.set_buffer(self.__status_text) # pylint: disable=E1101 self.__dialog.action_area.pack_start(start_button, True, True, 0) self.__dialog.action_area.pack_start(start_once_button, True, True, 0) self.__dialog.action_area.pack_start(clear_button, True, True, 0) self.__dialog.action_area.pack_start(terminate_button, True, True, 0) self.__dialog.action_area.pack_start(close_button, True, True, 0) self.__dialog.vbox.pack_start(scrolled_window, True, True, 0) scrolled_window.set_size_request(500, 200) start_button.show() start_once_button.show() terminate_button.show() close_button.show() clear_button.show() text_view.show() self.__dialog.show() text_view.set_editable(False) text_view.set_cursor_visible(False) def show_about(self): about = gtk.AboutDialog() about.set_program_name("Virtual Lab Manager") about.set_version("1.0 RC") import os path = os.path.dirname(virtlab.__file__) f = open(path + '/LICENCE', 'r') about.set_license(f.read()) about.set_copyright("GPLv3, (c) Authors") about.set_logo(gtk.gdk.pixbuf_new_from_file("pixmaps/about-logo.png")) about.set_authors(["Harri Savolainen", "Esa Elo"]) about.set_comments("Virtual Machine lab tool") about.set_website("https://github.com/hsavolai/vmlab") about.run() about.hide() def dialog_overwrite(self): response = messagedialog(gtk.MESSAGE_QUESTION, "File exists, overwrite?", None, self.toplevel, gtk.BUTTONS_OK_CANCEL ) if response == gtk.RESPONSE_OK: return True return False def dialog_file_error(self, error_msg): messagedialog(gtk.MESSAGE_ERROR, "File operation failed!", error_msg, self.toplevel, gtk.BUTTONS_OK ) def set_statusbar(self, value): #self.statusbar.remove_all(self.__statusbar_ctx) self.statusbar.pop(self.__statusbar_ctx) self.statusbar.push(self.__statusbar_ctx, value) @staticmethod def get_display_order(number): if number is 0: return "" upper_suffixes = { "11": "th", "12": "th", "13": "th" } lower_suffixes = { "1": "st", "2": "nd", "3": "rd", } digits = str(number) if digits[-2:] in upper_suffixes: return digits + upper_suffixes[digits[-2:]] if digits[-1:] in lower_suffixes: return digits + lower_suffixes[digits[-1:]] else: return digits + "th"
class DetailsTab(gtk.VBox): details_dialog_class = None def __init__(self, model, parent): super(DetailsTab, self).__init__() self.model = model self._parent = parent self.set_spacing(6) self.set_border_width(6) self.klist = ObjectList(self.get_columns()) self.klist.add_list(self.populate()) self.pack_start(self.klist) self.klist.show() if len(self.klist) and self.get_details_dialog_class(): self.button_box = gtk.HButtonBox() self.button_box.set_layout(gtk.BUTTONBOX_START) details_button = gtk.Button(self.details_lbl) self.button_box.pack_start(details_button) details_button.set_sensitive(bool(self.klist.get_selected())) details_button.show() self.pack_end(self.button_box, False, False) self.button_box.show() self.button_box.details_button = details_button details_button.connect('clicked', self._on_details_button__clicked) self.klist.connect('row-activated', self._on_klist__row_activated) self.klist.connect('selection-changed', self._on_klist__selection_changed) self.setup_widgets() def refresh(self): """Refreshes the list of respective tab.""" self.klist.clear() self.klist.add_list(self.populate()) def get_columns(self): """Returns a list of columns this tab should show.""" raise NotImplementedError def show_details(self): """Called when the details button is clicked. Displays the details of the selected object in the list.""" model = self.get_details_model(self.klist.get_selected()) run_dialog(self.get_details_dialog_class(), parent=self._parent, store=self._parent.store, model=model, visual_mode=True) def get_label(self): """Returns the name of the tab.""" label = gtk.Label(self.labels[1]) return label def get_details_model(self, model): """Subclassses can overwrite this method if the details dialog class needs a model different than the one on the list.""" return model def get_details_dialog_class(self): """Subclasses must return the dialog that should be displayed for more information about the item on the list""" return self.details_dialog_class def setup_widgets(self): """Override this if tab needs to do some custom widget setup.""" # # Callbacks # def _on_details_button__clicked(self, button): self.show_details() def _on_klist__row_activated(self, klist, item): self.show_details() def _on_klist__selection_changed(self, klist, data): self.button_box.details_button.set_sensitive(bool(data))
class PylintView(GladeDelegate, BaseReporter): """ A dokuwiki editor window """ mapping = {'E':'error', 'W':'warning', 'C':'low'} def __init__(self): self.icons = {} GladeDelegate.__init__(self, gladefile="lintgtk", delete_handler=self.quit_if_last) self.setup_sourceview() self.setup_side() self.throbber_icon = Throbber(self.view.throbber) self.show_all() def setup_config(self): """ Setup configuration file. """ nomondir = os.path.join(user.home,'.pylintgtk') if not os.path.exists(nomondir): os.mkdir(nomondir) cfg = FileDataSource(file=os.path.join(nomondir,'config.caf')) cfg.save() return cfg # quit override to work with twisted def quit_if_last(self, *_): """ Quit if we're the last window. """ windows = [toplevel for toplevel in gtk.window_list_toplevels() if toplevel.get_property('type') == gtk.WINDOW_TOPLEVEL] if len(windows) == 1: reactor.stop() def setup_sourceview(self): """ Setup the source editor. """ self.buffer = gtksourceview.Buffer() tagtable = self.buffer.get_tag_table() setup_tags(tagtable) lang_manager = gtksourceview.LanguageManager() lang = lang_manager.get_language('python') self.buffer.set_language(lang) self.editor = gtksourceview.View(self.buffer) accel_group = gtk.AccelGroup() self.get_toplevel().add_accel_group(accel_group) self.editor.add_accelerator("paste-clipboard", accel_group, ord('v'), gtk.gdk.CONTROL_MASK, 0) self.editor.add_accelerator("copy-clipboard", accel_group, ord('c'), gtk.gdk.CONTROL_MASK, 0) self.editor.add_accelerator("cut-clipboard", accel_group, ord('x'), gtk.gdk.CONTROL_MASK, 0) self.editor.set_left_margin(5) self.editor.set_right_margin(5) self.editor.set_show_line_marks(True) self.editor.set_show_line_numbers(True) self.editor.set_auto_indent(True) self.editor.set_insert_spaces_instead_of_tabs(True) self.editor.set_highlight_current_line(True) self.editor.set_indent_width(4) self.editor.set_indent_on_tab(True) path = environ.find_resource('images', 'red-warning.png') high = gtk.gdk.pixbuf_new_from_file(path) path = environ.find_resource('images', 'violet-warning.png') medium = gtk.gdk.pixbuf_new_from_file(path) path = environ.find_resource('images', 'yellow-warning.png') low = gtk.gdk.pixbuf_new_from_file(path) self.icons["low"] = low self.icons["warning"] = medium self.icons["error"] = high self.editor.set_mark_category_pixbuf('error', high) self.editor.set_mark_category_pixbuf('warning', medium) self.editor.set_mark_category_pixbuf('low', low) self.view.scrolledwindow1.add(self.editor) # setup functions def format_icon(self, value): """ return appropriate icon for kiwi. """ priority = self.mapping.get(value[0], 'low') return self.icons[priority] def setup_side(self): """ Setup the side statistics. """ columns = [Column('code', data_type=gtk.gdk.Pixbuf, format_func=self.format_icon, title=""), Column('line', sorted=True), Column('message'), Column('object'), Column('code')] self.problemlist = ObjectList(columns) self.view.side_vbox.pack_start(gtk.Label('Violations:'), False, False) self.view.side_vbox.add(self.problemlist) self.problemlist.connect("selection-changed", self.problem_selected) self.view.side_vbox.pack_start(gtk.Label('Stats:'), False, False) self.statslist = ObjectList([Column('name'), Column('value')]) #self.backlinks.connect("selection-changed", self.change_selected) self.view.side_vbox.add(self.statslist) def problem_selected(self, _, violation): """ A violation was selected on the objectlist. """ if not violation: return start = self.buffer.get_iter_at_line(violation.line-1) end = self.buffer.get_iter_at_line(violation.line-1) end.forward_to_line_end() self.buffer.place_cursor(start) self.editor.scroll_to_iter(start, 0.1) self.buffer.select_range(start, end) def load_file(self, filename): """ Load and check a file. """ self.linter = lint.PyLinter() self.linter.set_reporter(self) checkers.initialize(self.linter) source_file = open(filename, 'r') text = source_file.read() source_file.close() self.buffer.set_property('text', text) self.linecount = self.buffer.get_line_count() self.text = text self.lastfilename = filename self.check() def set_score(self, value): """ Set the score widget value. """ scoretext = "<big><big><big>%s</big></big></big>" % (value,) self.view.score.set_markup(scoretext) def _check_done(self, _): """ A pylint check has finished. """ self.set_score("%.1f"%(self.linter.stats['global_note'],)) self.view.comments.set_value(self.linter.stats['comment_lines']) self.view.lines.set_value(self.linter.stats['code_lines']) for key, value in self.linter.stats.iteritems(): if value.__class__ in [int, str, float]: self.statslist.append(Stat(key.replace("_"," "), value)) self.throbber_icon.stop() self.view.progressbar.set_fraction(1.0) def _check_error(self, failure): """ There was an error doing the pylint check. """ print self, failure def check(self): """ Perform a check on current file. """ self.view.progressbar.set_fraction(0.0) self.set_score('?') self.throbber_icon.start() self.idx = 0 self.linter = lint.PyLinter() self.linter.set_reporter(self) checkers.initialize(self.linter) deferred = threads.deferToThread(self.linter.check, self.lastfilename) deferred.addCallback(self._check_done) deferred.addErrback(self._check_error) def on_button_save__clicked(self, _): """ Kiwi callback for the save button. """ text = self.buffer.get_property('text') sourcefile = open(self.lastfilename, 'w') sourcefile.write(text) sourcefile.close() self.linecount = self.buffer.get_line_count() while self.idx > 0: mark = self.buffer.get_mark(str(self.idx-1)) if mark: self.buffer.delete_mark(mark) self.idx -= 1 self.idx = 0 self.problemlist.clear() self.statslist.clear() start, end = self.buffer.get_bounds() self.buffer.remove_source_marks(start, end, 'violation') self.buffer.remove_tag_by_name('violation', start, end) self.check() def _display(self, layout): """ Necessary for pylint.BaseReporter """ pass def add_message(self, msg_id, opts, msg): """ A message arrived from the checker thread. """ reactor.callFromThread(self.add_message_main, msg_id, opts, msg) def add_message_main(self, msg_id, opts, msg): """ Main thread callback for a message arriving from pylint. """ _, _, obj, line = opts self.problemlist.append(ViolationReport(code=msg_id, icon=msg_id, line=line, object=obj, message=msg)) startiter = self.buffer.get_iter_at_line(line-1) enditer = self.buffer.get_iter_at_line(line-1) enditer.forward_to_line_end() self.buffer.apply_tag_by_name('violation', startiter, enditer) fraction = self.linter.stats['statement'] / float(self.linecount) self.view.progressbar.set_fraction(fraction) priority = self.mapping.get(msg_id[0], 'low') self.buffer.create_source_mark(str(self.idx), priority, startiter) self.idx += 1
class ListContainer(gtk.HBox): """A ListContainer is an L{ObjectList} with buttons to be able to modify the content of the list. Depending on the list_mode, @see L{set_list_mode} you will have add, remove and edit buttons. Signals ======= - B{add-item} (returns item): - emitted when the add button is clicked, you're expected to return an object here - B{remove-item} (item, returns bool): - emitted when removing an item, you can block the removal from the list by returning False - B{edit-item} (item): - emitted when editing an item you can block the update afterwards by returning False @ivar add_button: add button @type add_button: L{gtk.Button} @ivar remove_button: remove button @type remove_button: L{gtk.Button} @ivar edit_button: edit button @type edit_button: L{gtk.Button} """ gsignal('add-item', retval=object) gsignal('remove-item', object, retval=bool) gsignal('edit-item', object, retval=bool) gsignal('selection-changed', object) def __init__(self, columns, orientation=gtk.ORIENTATION_VERTICAL): """ Create a new ListContainer object. @param columns: columns for the L{kiwi.ui.objectlist.ObjectList} @type columns: a list of L{kiwi.ui.objectlist.Columns} @param orientation: the position where the buttons will be placed: at the right (vertically) or at the bottom (horizontally) of the list. Defaults to the right of the list. @type: gtk.ORIENTATION_HORIZONTAL or gtk.ORIENTATION_VERTICAL """ self._list_type = None gtk.HBox.__init__(self) self._orientation = orientation self._create_ui(columns) self.set_list_type(ListType.NORMAL) # Private API def _create_ui(self, columns): self.list = ObjectList(columns) self.list.connect('selection-changed', self._on_list__selection_changed) self.list.connect('row-activated', self._on_list__row_activated) self.add_button = gtk.Button(stock=gtk.STOCK_ADD) self.add_button.connect('clicked', self._on_add_button__clicked) self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE) self.remove_button.set_sensitive(False) self.remove_button.connect('clicked', self._on_remove_button__clicked) self.edit_button = gtk.Button(stock=gtk.STOCK_EDIT) self.edit_button.set_sensitive(False) self.edit_button.connect('clicked', self._on_edit_button__clicked) self._vbox = gtk.VBox(spacing=6) if self._orientation == gtk.ORIENTATION_VERTICAL: self.pack_start(self.list) self.list.show() self._add_buttons_to_box(self._vbox) self._pack_vbox() elif self._orientation == gtk.ORIENTATION_HORIZONTAL: self._vbox.pack_start(self.list) self.list.show() hbox = gtk.HBox(spacing=6) self._add_buttons_to_box(hbox) self._vbox.pack_start(hbox, expand=False) hbox.show() self._pack_vbox() else: raise TypeError( "buttons_orientation must be gtk.ORIENTATION_VERTICAL " " or gtk.ORIENTATION_HORIZONTAL") def _add_buttons_to_box(self, box): box.pack_start(self.add_button, expand=False) box.pack_start(self.remove_button, expand=False) box.pack_start(self.edit_button, expand=False) def _pack_vbox(self): self.pack_start(self._vbox, expand=False, padding=6) self._vbox.show() def _set_child_packing(self, padding): expand = self._orientation == gtk.ORIENTATION_HORIZONTAL self.set_child_packing(self._vbox, expand, True, padding, gtk.PACK_START) def _add_item(self): retval = self.emit('add-item') if retval is None: return elif isinstance(retval, NotImplementedError): raise retval self.list.append(retval) def _remove_item(self, item): retval = self.emit('remove-item', item) if retval: self.list.remove(item) def _edit_item(self, item): retval = self.emit('edit-item', item) if retval: self.list.update(item) # Public API def add_item(self, item): """Appends an item to the list @param item: item to append """ self.list.append(item) def add_items(self, items): """Appends a list of items to the list @param items: items to add @type items: a sequence of items """ self.list.extend(items) def remove_item(self, item): """Removes an item from the list @param item: item to remove """ self.list.remove(item) def update_item(self, item): """Updates an item in the list. You should call this if you change the object @param item: item to update """ self.list.update(item) def default_remove(self, item): """Asks the user confirmation for removal of an item. @param item: a description of the item that will be removed @returns: True if the user confirm the removal, False otherwise """ response = yesno(_('Do you want to remove %s ?') % (quote(str(item)),), parent=None, default=gtk.RESPONSE_OK, buttons=((gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), (gtk.STOCK_REMOVE, gtk.RESPONSE_OK))) return response == gtk.RESPONSE_OK def set_list_type(self, list_type): """Sets the kind of list type. @param list_type: """ if not isinstance(list_type, ListType): raise TypeError("list_type must be a ListType enum") self.add_button.set_property( 'visible', (list_type != ListType.READONLY and list_type != ListType.REMOVEONLY and list_type != ListType.UNADDABLE)) self.remove_button.set_property( 'visible', (list_type != ListType.READONLY and list_type != ListType.UNREMOVABLE)) self.edit_button.set_property( 'visible', (list_type != ListType.READONLY and list_type != ListType.UNEDITABLE and list_type != ListType.REMOVEONLY)) if list_type in [ListType.READONLY, ListType.REMOVEONLY]: padding = 0 else: padding = 6 self._set_child_packing(padding) self._list_type = list_type def clear(self): """Removes all the items in the list""" self.list.clear() # Callbacks def _on_list__selection_changed(self, list, selection): object_selected = selection is not None self.remove_button.set_sensitive(object_selected) self.edit_button.set_sensitive(object_selected) self.emit('selection-changed', selection) def _on_list__row_activated(self, list, item): if (self._list_type != ListType.READONLY and self._list_type != ListType.UNEDITABLE): self._edit_item(item) def _on_add_button__clicked(self, button): self._add_item() def _on_remove_button__clicked(self, button): self._remove_item(self.list.get_selected()) def _on_edit_button__clicked(self, button): self._edit_item(self.list.get_selected())
class ListContainer(Gtk.Box): """A ListContainer is an :class:`ObjectList` with buttons to be able to modify the content of the list. Depending on the list_mode, @see :class:`set_list_mode` you will have add, remove and edit buttons. Signals ======= - B{add-item} (returns item): - emitted when the add button is clicked, you're expected to return an object here - B{remove-item} (item, returns bool): - emitted when removing an item, you can block the removal from the list by returning False - B{edit-item} (item): - emitted when editing an item you can block the update afterwards by returning False :ivar add_button: add button :type add_button: :class:`Gtk.Button` :ivar remove_button: remove button :type remove_button: :class:`Gtk.Button` :ivar edit_button: edit button :type edit_button: :class:`Gtk.Button` """ __gtype_name__ = 'ListContainer' gsignal('add-item', retval=object) gsignal('remove-item', object, retval=bool) gsignal('edit-item', object, retval=bool) gsignal('selection-changed', object) def __init__(self, columns, orientation=Gtk.Orientation.VERTICAL): """ Create a new ListContainer object. :param columns: columns for the :class:`kiwi.ui.objectlist.ObjectList` :type columns: a list of :class:`kiwi.ui.objectlist.Columns` :param orientation: the position where the buttons will be placed: at the right (vertically) or at the bottom (horizontally) of the list. Defaults to the right of the list. :type: Gtk.Orientation.HORIZONTAL or Gtk.Orientation.VERTICAL """ self._list_type = None super(ListContainer, self).__init__(orientation=Gtk.Orientation.HORIZONTAL) self._orientation = orientation self._create_ui(columns) self.set_list_type(ListType.NORMAL) # Private API def _create_ui(self, columns): self.list = ObjectList(columns) self.list.connect('selection-changed', self._on_list__selection_changed) self.list.connect('row-activated', self._on_list__row_activated) self.add_button = Gtk.Button(stock=Gtk.STOCK_ADD) self.add_button.connect('clicked', self._on_add_button__clicked) self.remove_button = Gtk.Button(stock=Gtk.STOCK_REMOVE) self.remove_button.set_sensitive(False) self.remove_button.connect('clicked', self._on_remove_button__clicked) self.edit_button = Gtk.Button(stock=Gtk.STOCK_EDIT) self.edit_button.set_sensitive(False) self.edit_button.connect('clicked', self._on_edit_button__clicked) self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6) if self._orientation == Gtk.Orientation.VERTICAL: self.pack_start(self.list, True, True, 0) self.list.show() self._add_buttons_to_box(self._vbox) self._pack_vbox() elif self._orientation == Gtk.Orientation.HORIZONTAL: self._vbox.pack_start(self.list, True, True, 0) self.list.show() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) self._add_buttons_to_box(hbox) self._vbox.pack_start(hbox, False, True, 0) hbox.show() self._pack_vbox() else: raise TypeError( "buttons_orientation must be Gtk.Orientation.VERTICAL " " or Gtk.Orientation.HORIZONTAL") def _add_buttons_to_box(self, box): box.pack_start(self.add_button, False, True, 0) box.pack_start(self.remove_button, False, True, 0) box.pack_start(self.edit_button, False, True, 0) def _pack_vbox(self): self.pack_start(self._vbox, False, True, 6) self._vbox.show() def _set_child_packing(self, padding): expand = self._orientation == Gtk.Orientation.HORIZONTAL self.set_child_packing(self._vbox, expand, True, padding, Gtk.PackType.START) def _add_item(self): retval = self.emit('add-item') if retval is None: return elif isinstance(retval, NotImplementedError): raise retval self.list.append(retval) self.list.refresh() def _remove_item(self, item): retval = self.emit('remove-item', item) if retval: self.list.remove(item) def _edit_item(self, item): retval = self.emit('edit-item', item) if retval: self.list.update(item) # Public API def add_item(self, item): """Appends an item to the list :param item: item to append """ self.list.append(item) def add_items(self, items): """Appends a list of items to the list :param items: items to add :type items: a sequence of items """ self.list.extend(items) def remove_item(self, item): """Removes an item from the list :param item: item to remove """ self.list.remove(item) def update_item(self, item): """Updates an item in the list. You should call this if you change the object :param item: item to update """ self.list.update(item) def default_remove(self, item): """Asks the user confirmation for removal of an item. :param item: a description of the item that will be removed :returns: True if the user confirm the removal, False otherwise """ response = yesno(_('Do you want to remove %s ?') % (GLib.markup_escape_text(str(item)), ), parent=None, default=Gtk.ResponseType.OK, buttons=((Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL), (Gtk.STOCK_REMOVE, Gtk.ResponseType.OK))) return response == Gtk.ResponseType.OK def set_list_type(self, list_type): """Sets the kind of list type. :param list_type: """ if not isinstance(list_type, ListType): raise TypeError("list_type must be a ListType enum") self.add_button.set_property( 'visible', list_type not in [ ListType.READONLY, ListType.REMOVEONLY, ListType.UNADDABLE ]) self.remove_button.set_property( 'visible', list_type not in [ListType.READONLY, ListType.ADDONLY, ListType.UNREMOVABLE]) self.edit_button.set_property( 'visible', list_type not in [ ListType.READONLY, ListType.ADDONLY, ListType.UNEDITABLE, ListType.REMOVEONLY ]) if list_type in [ListType.READONLY, ListType.REMOVEONLY]: padding = 0 else: padding = 6 self._set_child_packing(padding) self._list_type = list_type def clear(self): """Removes all the items in the list""" self.list.clear() # Callbacks def _on_list__selection_changed(self, list, selection): object_selected = selection is not None self.remove_button.set_sensitive(object_selected) self.edit_button.set_sensitive(object_selected) self.emit('selection-changed', selection) def _on_list__row_activated(self, list, item): if self._list_type not in [ ListType.READONLY, ListType.ADDONLY, ListType.UNEDITABLE ]: self._edit_item(item) def _on_add_button__clicked(self, button): self._add_item() def _on_remove_button__clicked(self, button): self._remove_item(self.list.get_selected()) def _on_edit_button__clicked(self, button): self._edit_item(self.list.get_selected())
class DokuwikiView(GladeDelegate): """ A dokuwiki editor window """ def __init__(self): GladeDelegate.__init__(self, gladefile="pydoku", delete_handler=self.quit_if_last) self._icons = {} self.throbber_icon = Throbber(self.view.throbber) self.setup_wikitree() self.setup_wikislist() self.setup_attachments() self.setup_lastchanges() self.setup_side() self.setup_sourceview() self.setup_htmlview() self.page_edit = self.view.notebook1.get_nth_page(0) self.page_view = self.view.notebook1.get_nth_page(1) self.page_attach = self.view.notebook1.get_nth_page(2) self.show_all() if len(cfg.getChildren()): wiki = cfg.getChildren()[0] self.connect(wiki.url, wiki.user, wiki.password) self.wiki = wiki if wiki.current: self.load_page(wiki.current) # quit override to work with twisted def quit_if_last(self, *args): self.htmlview.destroy() # for some reason has to be deleted explicitly windows = [toplevel for toplevel in gtk.window_list_toplevels() if toplevel.get_property('type') == gtk.WINDOW_TOPLEVEL] if len(windows) == 1: reactor.stop() # general interface functions def post(self, text): id = self.view.statusbar.get_context_id("zap") self.view.statusbar.push(id, text) # setup functions def setup_wikislist(self): columns = [Column('url',format_func=self.get_favicon,data_type=gtk.gdk.Pixbuf,icon_size=gtk.ICON_SIZE_SMALL_TOOLBAR)] self.wikislist = ObjectList(columns) columns.append(Column('url', title='Wiki', column='url')) self.wikislist.set_columns(columns) self.view.vbox2.pack_start(self.wikislist) self.view.vbox2.reorder_child(self.wikislist, 0) self.wikislist.add_list(cfg.getChildren()) self.wikislist.connect("selection-changed", self.wiki_selected) threads.deferToThread(self.download_favicons, cfg) def download_favicons(self, cfg): for wiki in cfg.getChildren(): self.download_favicon(wiki) def download_favicon(self, wiki): import urllib icon_url = wiki.url+"/lib/tpl/sidebar/images/favicon.ico" filename, headers = urllib.urlretrieve(icon_url, "/tmp/ico.ico") if headers["Content-Type"] == 'image/x-icon': self.add_favicon(wiki, filename) def get_favicon(self, wiki_url): return self._icons.get(wiki_url, page_icon) def add_favicon(self, wiki, filename): pixbuf = gtk.gdk.pixbuf_new_from_file(filename) pixbuf = pixbuf.scale_simple(16,16,gtk.gdk.INTERP_BILINEAR) self._icons[wiki.url] = pixbuf self.objectlist.refresh() def setup_side(self): columns = ['sum', 'user', 'type', 'version', 'ip'] columns = [Column(s) for s in columns] self.versionlist = ObjectList(columns) self.view.side_vbox.pack_start(gtk.Label('Version Log:'), False, False) self.view.side_vbox.add(self.versionlist) self.versionlist.connect("selection-changed", self.version_selected) self.view.side_vbox.pack_start(gtk.Label('BackLinks:'), False, False) self.backlinks = ObjectList([Column('name')]) self.backlinks.connect("selection-changed", self.change_selected) self.view.side_vbox.add(self.backlinks) def setup_attachments(self): columns = ['id', 'size', 'lastModified', 'writable', 'isimg', 'perms'] columns = [Column(s) for s in columns] self.attachmentlist = ObjectList(columns) self.view.attachments_vbox.add(self.attachmentlist) def setup_lastchanges(self): columns = ['name', 'author', 'lastModified', 'perms', 'version', 'size'] columns = [Column(s) for s in columns] columns.append(Column('lastModified', sorted=True, order=gtk.SORT_DESCENDING)) self.lastchangeslist = ObjectList(columns) self.lastchangeslist.connect("selection-changed", self.change_selected) self.view.side_vbox.add(self.lastchangeslist) def setup_wikitree(self): columns = ['id', 'lastModified', 'perms', 'size'] columns = [Column(s) for s in columns] columns.insert(0, Column('icon', title='name', data_type=gtk.gdk.Pixbuf)) self.objectlist = ObjectTree(columns) columns.insert(1, Column('name', column='icon')) self.objectlist.set_columns(columns) self.objectlist.connect("selection-changed", self.selected) self.view.vbox2.add(self.objectlist) def html_realized(self, widget): if self.wiki and self.wiki.current: self.get_htmlview(self.wiki.current) def setup_htmlview(self): self.htmlview = gtkmozembed.MozEmbed() self.view.html_scrolledwindow.add_with_viewport(self.htmlview) self.htmlview.connect('realize', self.html_realized) #self.htmlview.set_size_request(800,600) #self.htmlview.realize() #self.view.html_scrolledwindow.show_all() #self.htmlview.show() def setup_sourceview(self): self.buffer = DokuwikiBuffer(table) self.editor = gtksourceview.SourceView(self.buffer) #self.editor.set_show_line_numbers(True) accel_group = gtk.AccelGroup() self.get_toplevel().add_accel_group(accel_group) self.editor.add_accelerator("paste-clipboard", accel_group, ord('v'), gtk.gdk.CONTROL_MASK, 0) self.editor.add_accelerator("copy-clipboard", accel_group, ord('c'), gtk.gdk.CONTROL_MASK, 0) self.editor.add_accelerator("cut-clipboard", accel_group, ord('x'), gtk.gdk.CONTROL_MASK, 0) #self.editor = gtk.TextView(self.buffer) self.editor.set_left_margin(5) self.editor.set_right_margin(5) self.editor.set_wrap_mode(gtk.WRAP_WORD_CHAR) self.view.scrolledwindow1.add(self.editor) lm = gtksourceview.SourceLanguagesManager() langs = lm.get_available_languages() lang_diffs = filter(lambda s: s.get_name() == 'Diff', langs) if lang_diffs: self.buffer.set_language(lang_diffs[0]) # dokuwiki operations def _getVersion(self): return self._rpc.dokuwiki.getVersion() def get_version(self): return threads.deferToThread(self._getVersion) def get_pagelist(self): print "getpagelist1" pages = self._rpc.wiki.getAllPages() self._sections = {} self.objectlist.clear() print "getpagelist1.5" print "PAGES",pages for page in pages: self.add_page(page) print "getpagelist2" self.view.new_page.set_sensitive(True) self.view.delete_page.set_sensitive(True) if self.wiki.current: self.set_selection(self.wiki.current) print "getpagelist3" # XXX self.get_recent_changes() print "getpagelist2" def _getRecentChanges(self): return self._rpc.wiki.getRecentChanges(int(time.time()-(60*60*24*7*12))) def _gotRecentChanges(self, changes): changes = [DictWrapper(s) for s in changes] self.lastchangeslist.add_list(changes) def get_recent_changes(self): self.callDeferred(self._getRecentChanges, self._gotRecentChanges) def get_attachments(self, ns): attachments = self._rpc.wiki.getAttachments(ns, {}) attachments = [DictWrapper(s) for s in attachments] self.attachmentlist.add_list(attachments) def _getBackLinks(self, pagename): return self._rpc.wiki.getBackLinks(pagename) def _gotBackLinks(self, backlinks): backlinks = [Section(s) for s in backlinks] self.backlinks.add_list(backlinks) def get_backlinks(self, pagename): self.callDeferred(self._getBackLinks, self._gotBackLinks, pagename) def _getVersions(self, pagename): return self._rpc.wiki.getPageVersions(pagename, 0) def _gotVersions(self, versionlist): versionlist = [DictWrapper(s) for s in versionlist] self.versionlist.add_list(versionlist) def get_versions(self, pagename): self.callDeferred(self._getVersions, self._gotVersions, pagename) def _getHtmlData(self, pagename): text = self._rpc.wiki.getPageHTML(pagename) return text def _gotHtmlData(self, text): self.throbber_icon.stop() if not self.htmlview.window: return text = """<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head><body>"""+text+"</body>" self.htmlview.render_data(text, len(text), self.wiki.url, 'text/html') self.htmlview.realize() self.htmlview.show() def get_htmlview(self, pagename): self.throbber_icon.start() self.callDeferred(self._getHtmlData, self._gotHtmlData, pagename) #d.addErrback(self.someError) # XXX following is for gtkhtml (not used) #self.document.clear() #self.document.open_stream('text/html') #self.document.write_stream(text) #self.document.close_stream() def callDeferred(self, get_func, got_func, *args): d = threads.deferToThread(get_func, *args) d.addCallback(got_func) def _getEditText(self, pagename): return self._rpc.wiki.getPage(pagename) def _gotEditText(self, text): self.throbber_icon.stop() self.buffer.set_highlight(False) self.editor.set_editable(True) self.buffer.add_text(text) def _getDiffText(self, pagename, version, idx): return self._rpc.wiki.getPageVersion(pagename, version), idx def _gotDiffText(self, data): import difflib import StringIO text, idx = data self.textstack[idx] = text if not None in self.textstack: fromlines = self.textstack[0].split("\n") tolines = self.textstack[1].split("\n") diff_text = difflib.unified_diff(fromlines, tolines, "a", "b", self.versions[0], self.versions[1]) self.throbber_icon.stop() self.buffer.clear() str_buffer = StringIO.StringIO() for line in diff_text: str_buffer.write(line+'\n') str_buffer.seek(0) self.buffer.add_text(str_buffer.read()) self.buffer.set_highlight(True) self.editor.set_editable(False) def get_difftext(self, pagename, version, prev_version): self.throbber_icon.start() self.textstack = [None, None] self.versions = [version, prev_version] self.callDeferred(self._getDiffText, self._gotDiffText, pagename, prev_version, 0) self.callDeferred(self._getDiffText, self._gotDiffText, pagename, version, 1) def get_edittext(self, pagename): self.throbber_icon.start() self.callDeferred(self._getEditText, self._gotEditText, pagename) def put_page(self, text, summary, minor): pars = {} if summary: pars['sum'] = summary if minor: pars['minor'] = minor d = threads.deferToThread(self._rpc.wiki.putPage, self.wiki.current, text, pars) return d # put a page into the page tree def add_page(self, page): print page try: name = page["id"] path = name.split(":") prev = None for i, pathm in enumerate(path): if i == len(path)-1: # a page new = DictWrapper(page, pathm) self._sections[name] = new self.objectlist.append(prev, new, False) else: # a namespace part_path = ":".join(path[:i+1]) if not part_path in self._sections: new = Section(pathm, part_path) self._sections[part_path] = new self.objectlist.append(prev, new, False) else: new = self._sections[part_path] prev = new except: traceback.print_exc() def expand_to(self, pagename): path = pagename.split(":") for i, pathm in enumerate(path): if not i == len(path)-1: section = self._sections[":".join(path[:i+1])] self.view.objectlist.expand(section) def set_selection(self, pagename): obj = self._sections[pagename] self.expand_to(pagename) self.view.objectlist.select(obj, True) #self.selected(widget, obj) # page selected callback def wiki_selected(self, widget, wiki): self.connect(wiki.url, wiki.user, wiki.password) self.objectlist.clear() self.versionlist.clear() self.lastchangeslist.clear() self.backlinks.clear() self._sections = {} self.wiki = wiki self.buffer.clear() if wiki.current: self.load_page(wiki.current) def version_selected(self, widget, object): # yes, the previous item is the next in the widget if object == None: return previous = widget.get_next(object) if not previous: return prev_version = previous.version self.get_difftext(self.wiki.current, int(object.version), int(prev_version)) def change_selected(self, widget, object): if not object: return self.set_selection(object.name) def selected(self, widget, object): if not object: return if isinstance(object, Section): self.get_attachments(object.id) if not isinstance(object, DictWrapper): return self.wiki.current = object.id cfg.save() self.load_page(object.id) def load_page(self, pagename): self.get_edittext(pagename) self.get_htmlview(pagename) self.get_backlinks(pagename) self.get_versions(pagename) # kiwi interface callbacks def on_view_edit__toggled(self, widget): if widget.get_active(): self.notebook1.insert_page(self.page_edit, gtk.Label('edit'), 0) else: self.notebook1.remove_page(self.notebook1.page_num(self.page_edit)) def on_view_view__toggled(self, widget): if widget.get_active(): self.notebook1.insert_page(self.page_view, gtk.Label('view'), 1) else: self.notebook1.remove_page(self.notebook1.page_num(self.page_view)) def on_view_attachments__toggled(self, widget): if widget.get_active(): self.notebook1.insert_page(self.page_attach, gtk.Label('attach')) else: self.notebook1.remove_page(self.notebook1.page_num(self.page_attach)) def on_view_extra__toggled(self, widget): if widget.get_active(): self.backlinks.show() self.versionlist.show() self.view.hpaned2.set_position(self._prevpos) else: self.backlinks.hide() self.versionlist.hide() self._prevpos = self.view.hpaned2.get_position() self.view.hpaned2.set_position(self.view.hpaned2.allocation.width) def on_button_add__clicked(self, *args): dialog = ModalDialog("User Details") # prepare widgets = {} items = ["url","user", "password"] for i, item in enumerate(items): widgets[item] = gtk.Entry() if i == 2: widgets[item].set_visibility(False) hbox = gtk.HBox() hbox.pack_start(gtk.Label(item+': ')) hbox.add(widgets[item]) dialog.vbox.add(hbox) dialog.show_all() # run response = dialog.run() user = widgets['user'].get_text() password = widgets['password'].get_text() url = widgets['url'].get_text() dialog.destroy() if not response == gtk.RESPONSE_ACCEPT: return self.wiki = cfg.new(Dokuwiki, url=url, user=user, password=password) cfg.addChild(self.wiki) cfg.save() self.connect(url, user, password) def get_full_url(self, url, user, password): try: if user and password: split_url = url.split('://') proto = split_url[0] base_url = split_url[1] return proto + '://' + user + ':' + password + '@' + base_url return url except: traceback.print_exc() def connect(self, url, user, password): # following commented line is for gtkhtml (not used) #simplebrowser.currentUrl = self.view.url.get_text() # handle response self.post("Connecting to " + url) params = urlencode({'u':user, 'p':password}) print self.get_full_url(url, user, password) fullurl = self.get_full_url(url, user, password) + "/lib/exe/xmlrpc.php?"+ params print "serverproxy1" self._rpc = ServerProxy(fullurl) print "serverproxy1" d = self.get_version() d.addCallback(self.connected) d.addErrback(self.error_connecting) def error_connecting(self, failure): self.post("Error connecting to " + self.wiki.url) print failure.getErrorMessage() def connected(self, version): print "connected1" self.view.version.set_text(version) print "connected1.5" self.get_pagelist() print "connected2" self.post("Connected") def on_delete_page__clicked(self, *args): dialog = ModalDialog("Are you sure?") response = dialog.run() if response == gtk.RESPONSE_ACCEPT: value = self._sections[self.wiki.current] sel = self.objectlist.remove(value) self._rpc.wiki.putPage(self.wiki.current, "", {}) self.wiki.current = '' cfg.save() dialog.destroy() def on_new_page__clicked(self, *args): dialog = ModalDialog("Name for the new page") text_w = gtk.Entry() text_w.show() response = [] dialog.vbox.add(text_w) response = dialog.run() if response == gtk.RESPONSE_ACCEPT: text = text_w.get_text() if text: self.wiki.current = text cfg.save() self.buffer.clear() dialog.destroy() def on_button_h1__clicked(self, *args): self.buffer.set_style('h1') def on_button_h2__clicked(self, *args): self.buffer.set_style('h2') def on_button_h3__clicked(self, *args): self.buffer.set_style('h3') def on_button_h4__clicked(self, *args): self.buffer.set_style('h4') def on_button_h5__clicked(self, *args): self.buffer.set_style('h5') def on_button_h6__clicked(self, *args): self.buffer.set_style('h6') def on_button_bold__clicked(self, *args): self.buffer.set_style('bold') def on_button_italic__clicked(self, *args): self.buffer.set_style('italic') def on_button_clear_style__clicked(self, *args): self.buffer.clear_style() def _pagePut(self, *args): if not self.wiki.current in self._sections: self.add_page({"id":self.wiki.current}) self.get_htmlview(self.wiki.current) self.get_versions(self.wiki.current) self.post("Saved") def on_button_save__clicked(self, *args): """ Save button callback """ dialog = ModalDialog("Commit message") entry = gtk.Entry() minor = gtk.CheckButton("Minor") dialog.vbox.add(gtk.Label("Your attention to detail\nis greatly appreciated")) dialog.vbox.add(entry) dialog.vbox.add(minor) dialog.show_all() response = dialog.run() if response == gtk.RESPONSE_ACCEPT: self.post("Saving...") text = self.buffer.process_text() self.throbber_icon.start() d = self.put_page(text, entry.get_text(), minor.get_active()) d.addCallback(self._pagePut) dialog.destroy() # unused stuff def request_url(self, document, url, stream): f = simplebrowser.open_url(url) stream.write(f.read()) def setup_htmlview_gtkhtml(self): # XXX not used now self.document = gtkhtml2.Document() self.document.connect('request_url', self.request_url) self.htmlview = gtkhtml2.View() self.htmlview.set_document(self.document)
class DataTests(unittest.TestCase): """In all this tests we use the same configuration for a list""" def setUp(self): self.win = gtk.Window() self.win.set_default_size(400, 400) self.list = ObjectList([Column('name'), Column('age')]) self.win.add(self.list) refresh_gui() def tearDown(self): self.win.destroy() del self.win def testAddingOneInstance(self): # we should have two columns now self.assertEqual(2, len(self.list.get_columns())) person = Person('henrique', 21) self.list.append(person) refresh_gui() # usually you don't use the model directly, but tests are all about # breaking APIs, right? self.assertEqual(self.list[0], person) self.assertEqual(self.list[0].name, 'henrique') self.assertEqual(self.list[0].age, 21) # we still have to columns, right? self.assertEqual(2, len(self.list.get_columns())) def testAddingAObjectList(self): global persons self.list.add_list(persons) refresh_gui() self.assertEqual(len(self.list), len(persons)) def testAddingABunchOfInstances(self): global persons for person in persons: self.list.append(person) refresh_gui() self.assertEqual(len(self.list), len(persons)) def testRemovingOneInstance(self): global persons self.list.add_list(persons) refresh_gui() # we are going to remove Kiko person = persons[2] self.list.remove(person) self.assertEqual(len(self.list), len(persons) - 1) # now let's remove something that is not on the list #new_person = Person('Evandro', 24) #self.assertRaises(ValueError, self.list.remove, new_person) # note that even a new person with the same values as a person # in the list is not considered to be in the list #existing_person = Person('Gustavo', 25) #self.assertRaises(ValueError, self.list.remove, # existing_person) def testClearObjectList(self): global persons self.list.add_list(persons) refresh_gui() self.list.clear() self.assertEqual(len(self.list), 0) def testUpdatingOneInstance(self): global persons self.list.add_list(persons) refresh_gui() persons[0].age = 29 self.list.update(persons[0]) refresh_gui() # Do we have the same number of instances that we had before ? self.assertEqual(len(self.list), len(persons)) # Trying to find our updated instance in the list self.assertEqual(self.list[0].age, 29) # let's be evil new_person = Person('Nando', 32) self.assertRaises(ValueError, self.list.update, new_person) def testContains(self): global persons self.list.add_list(persons) self.assertEqual(persons[0] in self.list, True) new_person = Person('Nando', 32) self.assertEqual(new_person in self.list, False) def testSelect(self): first = persons[0] self.list.add_list(persons) self.list.select(first) self.assertEqual(self.list.get_selected(), first) self.list.remove(first) self.assertRaises(ValueError, self.list.select, first)
class ChecklistView(PidaView): key = 'checklist.view' icon_name = 'gtk-todo' label_text = _('Check list') def create_ui(self): self._vbox = gtk.VBox(spacing=3) self._vbox.set_border_width(3) self.create_toolbar() self.create_newitem() self.create_list() self.add_main_widget(self._vbox) self._vbox.show_all() def create_tab_label(self, icon_name, text): if None in [icon_name, text]: return None label = gtk.Label(text) b_factory = gtk.HBox b = b_factory(spacing=2) icon = gtk.image_new_from_stock(icon_name, gtk.ICON_SIZE_MENU) b.pack_start(icon) b.pack_start(label) b.show_all() return b def create_list(self): self._list = ObjectList([ Column('done', title=_('Done'), data_type=bool, editable=True), Column('title', title=_('Title'), data_type=str, editable=True, expand=True), Column('priority', title=_('Priority'), data_type=ChecklistStatus, editable=True) ]) self._list.connect('cell-edited', self._on_item_edit) self._list.connect('selection-changed', self._on_item_selected) self._list.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self._vbox.add(self._list) self._sort_combo = AttrSortCombo(self._list, [ ('done', _('Done')), ('title', _('Title')), ('priority', _('Priority')), ], 'title') self._vbox.pack_start(self._sort_combo, expand=False) self._list.show_all() self._sort_combo.show_all() def create_newitem(self): self._hbox = gtk.HBox(spacing=3) self._newitem_title = gtk.Entry() self._newitem_title.connect('changed', self._on_newitem_changed) self._newitem_ok = gtk.Button(stock=gtk.STOCK_ADD) self._newitem_ok.connect('clicked', self._on_item_add) self._newitem_ok.set_sensitive(False) self._hbox.pack_start(self._newitem_title, expand=True) self._hbox.pack_start(self._newitem_ok, expand=False) self._vbox.pack_start(self._hbox, expand=False) self._hbox.show_all() def create_toolbar(self): self._uim = gtk.UIManager() self._uim.insert_action_group(self.svc.get_action_group(), 0) uim_data = pkgutil.get_data(__name__, 'uidef/checklist-toolbar.xml') self._uim.add_ui_from_string(uim_data) self._uim.ensure_update() self._toolbar = self._uim.get_toplevels('toolbar')[0] self._toolbar.set_style(gtk.TOOLBAR_ICONS) self._toolbar.set_icon_size(gtk.ICON_SIZE_SMALL_TOOLBAR) self._vbox.pack_start(self._toolbar, expand=False) self.svc.get_action('checklist_del').set_sensitive(False) self._toolbar.show_all() def add_item(self, item): self._list.append(item, select=True) self.svc.save() def update_item(self, item): self._list.update(item) self.svc.save() def remove_item(self, item): self._list.remove(item) self.svc.save() def clear(self): self._list.clear() def _on_item_selected(self, olist, item): self.svc.get_action('checklist_del').set_sensitive(item is not None) self.svc.set_current(item) def _on_item_edit(self, olist, item, value): self.svc.save() def _on_item_add(self, w): title = self._newitem_title.get_text() self.svc.add_item(ChecklistItem(title=title)) self._newitem_title.set_text('') def _on_newitem_changed(self, w): self._newitem_ok.set_sensitive(self._newitem_title.get_text() != '') def can_be_closed(self): self.svc.get_action('show_checklist').set_active(False)
class DataTests(unittest.TestCase): """In all this tests we use the same configuration for a list""" def setUp(self): self.win = Gtk.Window() self.win.set_default_size(400, 400) self.list = ObjectList([Column('name'), Column('age')]) self.win.add(self.list) refresh_gui() def tearDown(self): self.win.destroy() del self.win def testAddingOneInstance(self): # we should have two columns now self.assertEqual(2, len(self.list.get_columns())) person = Person('henrique', 21) self.list.append(person) refresh_gui() # usually you don't use the model directly, but tests are all about # breaking APIs, right? self.assertEqual(self.list[0], person) self.assertEqual(self.list[0].name, 'henrique') self.assertEqual(self.list[0].age, 21) # we still have to columns, right? self.assertEqual(2, len(self.list.get_columns())) def testAddingAObjectList(self): global persons self.list.add_list(persons) refresh_gui() self.assertEqual(len(self.list), len(persons)) def testAddingABunchOfInstances(self): global persons for person in persons: self.list.append(person) refresh_gui() self.assertEqual(len(self.list), len(persons)) def testRemovingOneInstance(self): global persons self.list.add_list(persons) refresh_gui() # we are going to remove Kiko person = persons[2] self.list.remove(person) self.assertEqual(len(self.list), len(persons) - 1) # now let's remove something that is not on the list #new_person = Person('Evandro', 24) #self.assertRaises(ValueError, self.list.remove, new_person) # note that even a new person with the same values as a person # in the list is not considered to be in the list #existing_person = Person('Gustavo', 25) #self.assertRaises(ValueError, self.list.remove, # existing_person) def testClearObjectList(self): global persons self.list.add_list(persons) refresh_gui() self.list.clear() self.assertEqual(len(self.list), 0) def testUpdatingOneInstance(self): global persons self.list.add_list(persons) refresh_gui() persons[0].age = 29 self.list.update(persons[0]) refresh_gui() # Do we have the same number of instances that we had before ? self.assertEqual(len(self.list), len(persons)) # Trying to find our updated instance in the list self.assertEqual(self.list[0].age, 29) # let's be evil new_person = Person('Nando', 32) self.assertRaises(ValueError, self.list.update, new_person) def testContains(self): global persons self.list.add_list(persons) self.assertEqual(persons[0] in self.list, True) new_person = Person('Nando', 32) self.assertEqual(new_person in self.list, False) def testSelect(self): first = persons[0] self.list.add_list(persons) self.list.select(first) self.assertEqual(self.list.get_selected(), first) self.list.remove(first) self.assertRaises(ValueError, self.list.select, first)
class MethodTest(unittest.TestCase): def setUp(self): self.klist = ObjectList([Column('name', sorted=True)], [Settable(name='first')]) def testNonZero(self): self.assertEqual(self.klist.__nonzero__(), True) self.klist.remove(self.klist[0]) self.assertEqual(self.klist.__nonzero__(), True) if not self.klist: raise AssertionError def testIter(self): for item1 in self.klist: pass for item2 in iter(self.klist): self.assertEqual(item1, item2) def testGetItem(self): self.klist.append(Settable(name='second')) model = self.klist.get_model() item1 = model[0][0] item2 = model[1][0] self.assertEqual(self.klist[0], item1) self.assertEqual(self.klist[:1], [item1]) self.assertEqual(self.klist[-1:], [item2]) self.assertRaises(TypeError, self.klist.__getitem__, None) def testSetItem(self): self.klist[0] = Settable(name='second') self.assertRaises(NotImplementedError, self.klist.__setitem__, slice(0), None) self.assertRaises(TypeError, self.klist.__setitem__, None, None) def testIndex(self): self.assertRaises(NotImplementedError, self.klist.index, 0, start=0) self.assertRaises(NotImplementedError, self.klist.index, 0, stop=0) self.assertEqual(self.klist.index(self.klist[0]), 0) self.assertRaises(ValueError, self.klist.index, None) def testCount(self): item = self.klist[0] self.assertEqual(self.klist.count(item), 1) self.klist.append(item) self.assertEqual(self.klist.count(item), 2) self.klist.clear() self.assertEqual(self.klist.count(item), 0) def testPop(self): self.assertRaises(NotImplementedError, self.klist.pop, None) def testReverse(self): self.assertRaises(NotImplementedError, self.klist.reverse, 1, 2) def testSort(self): self.assertRaises(NotImplementedError, self.klist.sort, 1, 2) def testSelectPath(self): self.klist.get_treeview().get_selection().set_mode( Gtk.SelectionMode.NONE) self.assertRaises(TypeError, self.klist.select_paths, (0, )) self.klist.get_treeview().get_selection().set_mode( Gtk.SelectionMode.SINGLE) self.klist.select_paths((0, )) def testSelect(self): self.klist.get_treeview().get_selection().set_mode( Gtk.SelectionMode.NONE) self.assertRaises(TypeError, self.klist.select, None) self.klist.get_treeview().get_selection().set_mode( Gtk.SelectionMode.SINGLE) def testGetSelected(self): item = self.klist[0] self.klist.select(item) self.klist.get_treeview().get_selection().set_mode( Gtk.SelectionMode.SINGLE) self.assertEqual(self.klist.get_selected(), item) def testGetSelectedRows(self): self.klist.get_treeview().get_selection().set_mode( Gtk.SelectionMode.MULTIPLE) item = self.klist[0] self.klist.select(item) self.assertEqual(self.klist.get_selected_rows(), [item]) def testGetNextAndPrevious(self): self.klist.append(Settable(name='second')) self.klist.append(Settable(name='third')) item1, item2, item3 = self.klist self.assertEqual(self.klist.get_next(item1), item2) self.assertEqual(self.klist.get_next(item2), item3) self.assertEqual(self.klist.get_next(item3), item1) self.assertRaises(ValueError, self.klist.get_next, None) self.assertEqual(self.klist.get_previous(item1), item3) self.assertEqual(self.klist.get_previous(item2), item1) self.assertEqual(self.klist.get_previous(item3), item2) self.assertRaises(ValueError, self.klist.get_previous, None) def testInsert(self): self.klist = ObjectList([Column('name')]) self.assertEqual(list(self.klist), []) self.klist.insert(0, Settable(name='one')) self.assertEqual(self.klist[0].name, 'one') self.klist.insert(0, Settable(name='two')) self.assertEqual(self.klist[0].name, 'two') self.assertEqual(self.klist[1].name, 'one') self.klist.insert(1, Settable(name='three')) self.assertEqual(self.klist[0].name, 'two') self.assertEqual(self.klist[1].name, 'three') self.assertEqual(self.klist[2].name, 'one')
class ListContainer(Gtk.Box): """A ListContainer is an :class:`ObjectList` with buttons to be able to modify the content of the list. Depending on the list_mode, @see :class:`set_list_mode` you will have add, remove and edit buttons. Signals ======= - B{add-item} (returns item): - emitted when the add button is clicked, you're expected to return an object here - B{remove-item} (item, returns bool): - emitted when removing an item, you can block the removal from the list by returning False - B{edit-item} (item): - emitted when editing an item you can block the update afterwards by returning False :ivar add_button: add button :type add_button: :class:`Gtk.Button` :ivar remove_button: remove button :type remove_button: :class:`Gtk.Button` :ivar edit_button: edit button :type edit_button: :class:`Gtk.Button` """ __gtype_name__ = 'ListContainer' gsignal('add-item', retval=object) gsignal('remove-item', object, retval=bool) gsignal('edit-item', object, retval=bool) gsignal('selection-changed', object) def __init__(self, columns, orientation=Gtk.Orientation.VERTICAL): """ Create a new ListContainer object. :param columns: columns for the :class:`kiwi.ui.objectlist.ObjectList` :type columns: a list of :class:`kiwi.ui.objectlist.Columns` :param orientation: the position where the buttons will be placed: at the right (vertically) or at the bottom (horizontally) of the list. Defaults to the right of the list. :type: Gtk.Orientation.HORIZONTAL or Gtk.Orientation.VERTICAL """ self._list_type = None super(ListContainer, self).__init__(orientation=Gtk.Orientation.HORIZONTAL) self._orientation = orientation self._create_ui(columns) self.set_list_type(ListType.NORMAL) # Private API def _create_ui(self, columns): self.list = ObjectList(columns) self.list.connect('selection-changed', self._on_list__selection_changed) self.list.connect('row-activated', self._on_list__row_activated) self.add_button = Gtk.Button(stock=Gtk.STOCK_ADD) self.add_button.connect('clicked', self._on_add_button__clicked) self.remove_button = Gtk.Button(stock=Gtk.STOCK_REMOVE) self.remove_button.set_sensitive(False) self.remove_button.connect('clicked', self._on_remove_button__clicked) self.edit_button = Gtk.Button(stock=Gtk.STOCK_EDIT) self.edit_button.set_sensitive(False) self.edit_button.connect('clicked', self._on_edit_button__clicked) self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6) if self._orientation == Gtk.Orientation.VERTICAL: self.pack_start(self.list, True, True, 0) self.list.show() self._add_buttons_to_box(self._vbox) self._pack_vbox() elif self._orientation == Gtk.Orientation.HORIZONTAL: self._vbox.pack_start(self.list, True, True, 0) self.list.show() hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) self._add_buttons_to_box(hbox) self._vbox.pack_start(hbox, False, True, 0) hbox.show() self._pack_vbox() else: raise TypeError( "buttons_orientation must be Gtk.Orientation.VERTICAL " " or Gtk.Orientation.HORIZONTAL") def _add_buttons_to_box(self, box): box.pack_start(self.add_button, False, True, 0) box.pack_start(self.remove_button, False, True, 0) box.pack_start(self.edit_button, False, True, 0) def _pack_vbox(self): self.pack_start(self._vbox, False, True, 6) self._vbox.show() def _set_child_packing(self, padding): expand = self._orientation == Gtk.Orientation.HORIZONTAL self.set_child_packing(self._vbox, expand, True, padding, Gtk.PackType.START) def _add_item(self): retval = self.emit('add-item') if retval is None: return elif isinstance(retval, NotImplementedError): raise retval self.list.append(retval) self.list.refresh() def _remove_item(self, item): retval = self.emit('remove-item', item) if retval: self.list.remove(item) def _edit_item(self, item): retval = self.emit('edit-item', item) if retval: self.list.update(item) # Public API def add_item(self, item): """Appends an item to the list :param item: item to append """ self.list.append(item) def add_items(self, items): """Appends a list of items to the list :param items: items to add :type items: a sequence of items """ self.list.extend(items) def remove_item(self, item): """Removes an item from the list :param item: item to remove """ self.list.remove(item) def update_item(self, item): """Updates an item in the list. You should call this if you change the object :param item: item to update """ self.list.update(item) def default_remove(self, item): """Asks the user confirmation for removal of an item. :param item: a description of the item that will be removed :returns: True if the user confirm the removal, False otherwise """ response = yesno(_('Do you want to remove %s ?') % (GLib.markup_escape_text(str(item)),), parent=None, default=Gtk.ResponseType.OK, buttons=((Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL), (Gtk.STOCK_REMOVE, Gtk.ResponseType.OK))) return response == Gtk.ResponseType.OK def set_list_type(self, list_type): """Sets the kind of list type. :param list_type: """ if not isinstance(list_type, ListType): raise TypeError("list_type must be a ListType enum") self.add_button.set_property( 'visible', list_type not in [ListType.READONLY, ListType.REMOVEONLY, ListType.UNADDABLE]) self.remove_button.set_property( 'visible', list_type not in [ListType.READONLY, ListType.ADDONLY, ListType.UNREMOVABLE]) self.edit_button.set_property( 'visible', list_type not in [ListType.READONLY, ListType.ADDONLY, ListType.UNEDITABLE, ListType.REMOVEONLY]) if list_type in [ListType.READONLY, ListType.REMOVEONLY]: padding = 0 else: padding = 6 self._set_child_packing(padding) self._list_type = list_type def clear(self): """Removes all the items in the list""" self.list.clear() # Callbacks def _on_list__selection_changed(self, list, selection): object_selected = selection is not None self.remove_button.set_sensitive(object_selected) self.edit_button.set_sensitive(object_selected) self.emit('selection-changed', selection) def _on_list__row_activated(self, list, item): if self._list_type not in [ListType.READONLY, ListType.ADDONLY, ListType.UNEDITABLE]: self._edit_item(item) def _on_add_button__clicked(self, button): self._add_item() def _on_remove_button__clicked(self, button): self._remove_item(self.list.get_selected()) def _on_edit_button__clicked(self, button): self._edit_item(self.list.get_selected())
class BookmarkView(PidaView): icon_name = 'gtk-library' label_text = _('Bookmarks') def create_ui(self): self._vbox = gtk.VBox() self.create_toolbar() self.create_ui_list() self.add_main_widget(self._vbox) self._vbox.show_all() def create_tab_label(self, icon_name, text): if None in [icon_name, text]: return None label = gtk.Label(text) b_factory = gtk.HBox b = b_factory(spacing=2) icon = gtk.image_new_from_stock(icon_name, gtk.ICON_SIZE_MENU) b.pack_start(icon) b.pack_start(label) b.show_all() return b def create_ui_list(self): self._books = gtk.Notebook() self._books.set_border_width(6) self._list_dirs = ObjectList([Column('markup', data_type=str, use_markup=True)]) self._list_dirs.connect('row-activated', self._on_item_activated) self._list_dirs.connect('selection-changed', self._on_item_selected) self._list_dirs.set_headers_visible(False) self._list_dirs.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self._books.append_page(self._list_dirs, tab_label=self.create_tab_label('stock_folder', _('Dirs'))) self._list_files = ObjectList([Column('markup', data_type=str, use_markup=True)]) self._list_files.connect('row-activated', self._on_item_activated) self._list_files.connect('selection-changed', self._on_item_selected) self._list_files.set_headers_visible(False) self._list_files.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self._books.append_page(self._list_files, tab_label=self.create_tab_label('text-x-generic', _('Files'))) """ self._list_url = ObjectList([Column('markup', data_type=str, use_markup=True)]) self._list_url.set_headers_visible(False) self._books.add(self._list_url) """ self._vbox.add(self._books) self._books.show_all() def create_toolbar(self): self._uim = gtk.UIManager() self._uim.insert_action_group(self.svc.get_action_group(), 0) self._uim.add_ui_from_file(get_uidef_path('bookmark-toolbar.xml')) self._uim.ensure_update() self._toolbar = self._uim.get_toplevels('toolbar')[0] self._toolbar.set_style(gtk.TOOLBAR_ICONS) self._toolbar.set_icon_size(gtk.ICON_SIZE_SMALL_TOOLBAR) self._vbox.pack_start(self._toolbar, expand=False) self._toolbar.show_all() def add_item(self, item): if item.group == 'file': self._list_files.append(item) elif item.group == 'path': self._list_dirs.append(item) elif item.group == 'url': self._list_urls.append(item) def remove_item(self, item): if item.group == 'file': self._list_files.remove(item) elif item.group == 'path': self._list_dirs.remove(item) elif item.group == 'url': self._list_urls.remove(item) def clear_all(self): self._list_files.clear() self._list_dirs.clear() #self._list_urls.clear() def can_be_closed(self): self.svc.get_action('show_bookmark').set_active(False) def _on_item_selected(self, olist, item): self.svc.set_current(item) def _on_item_activated(self, olist, item): item.run(self.svc)
class Connections(GladeWidget): gladeFile = "connections.glade" gsignal("have-connection", bool) gsignal("connection-activated", object) gsignal("connections-cleared") def __init__(self): GladeWidget.__init__(self) columns = [ Column("host", title=_("Hostname"), searchable=True), Column( "timestamp", title=_("Last used"), sorted=True, order=gtk.SORT_DESCENDING, format_func=format_timestamp ), ] self._connections = ObjectList(columns, objects=getRecentConnections(), mode=gtk.SELECTION_SINGLE) self._connections.connect("row-activated", self._on_objectlist_row_activated) self._connections.connect("selection-changed", self._on_objectlist_selection_changed) self._connections.set_size_request(-1, 160) self.page.pack_start(self._connections) self.page.reorder_child(self._connections, 0) self._connections.get_treeview().set_search_equal_func(self._searchEqual) self._connections.show() self._updateButtons() def _updateButtons(self): canClear = hasRecentConnections() self.button_clear.set_sensitive(canClear) self.button_clear_all.set_sensitive(canClear) if not canClear: self.emit("connections-cleared") def _searchEqual(self, model, column, key, iter): connection = model.get(iter, column)[0] if key in connection.name: return False # True means doesn't match return True def _clear_all(self): for conn in self._connections: os.unlink(conn.filename) self._connections.clear() def _clear(self, conn): self._connections.remove(conn) os.unlink(conn.filename) # Public API def grab_focus(self): if len(self._connections): self._connections.select(self._connections[0]) self._connections.grab_focus() def get_selected(self): return self._connections.get_selected() def update(self, connection): os.utime(connection.filename, None) # Callbacks def on_button_clear_clicked(self, button): conn = self._connections.get_selected() if conn: self._clear(conn) self._updateButtons() def on_button_clear_all_clicked(self, button): self._clear_all() self._updateButtons() def _on_objectlist_row_activated(self, connections, connection): self.emit("connection-activated", connection) def _on_objectlist_selection_changed(self, connections, connection): self.emit("have-connection", bool(connection))