class Dan: def __init__(self): self.url = "http://www.bibud.com" self.setupWindow() self.setupBrowser() main() def setupWindow(self): self.window_title = "Bibud" self.window = Window() self.window.show() self.window.connect("destroy-event", self.browser_quit) self.window.resize(1024,768) self.window.set_title(self.window_title) def setupBrowser(self): self.browser = WebView() self.browser.show() self.browser.open(self.url) self.scroller = ScrolledWindow() self.scroller.add(self.browser) self.window.add(self.scroller) self.browser.connect("title-changed", self.title_changed) self.scroller.show() def eTitleChanged(self, webview, frame, title): self.window.set_title(title) def eQuit(self): main_quit()
class Dan: def __init__(self): self.url = "http://www.bibud.com" self.setupWindow() self.setupBrowser() main() def setupWindow(self): self.window_title = "Bibud" self.window = Window() self.window.show() self.window.connect("destroy-event", self.browser_quit) self.window.resize(1024, 768) self.window.set_title(self.window_title) def setupBrowser(self): self.browser = WebView() self.browser.show() self.browser.open(self.url) self.scroller = ScrolledWindow() self.scroller.add(self.browser) self.window.add(self.scroller) self.browser.connect("title-changed", self.title_changed) self.scroller.show() def eTitleChanged(self, webview, frame, title): self.window.set_title(title) def eQuit(self): main_quit()
def show(self): import gtk from gtk import Window, Label w = Window() w.set_size_request(*self.resolution) l = gtk.Label('Coordinates') w.add(l) l.show() w.add_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK) def configure_event(widget, event): pass def button_release_event(widget, event): if event.button == 1: print "unclick" self.server.send('u', 1, event.x, event.y) return True def button_press_event(widget, event): if event.button == 1: print "click" self.server.send('d', 1, event.x, event.y) return True def motion_notify_event(widget, event): if event.is_hint: x, y, state = event.window.get_pointer() else: print "no hint" x, y, state = event.x, event.y, event.state l.set_text("(%d,%d)" % (x, y)) print "Event number %d, (%d,%d)" % (event.type, x, y) self.server.send('.', 1, event.x, event.y) return True w.connect("configure_event", configure_event) w.connect("motion_notify_event", motion_notify_event) w.connect("button_press_event", button_press_event) w.connect("button_release_event", button_release_event) w.connect("delete_event", gtk.main_quit) if self.fullscreen: w.fullscreen() w.show() self.server.resolution = w.get_size() gtk.main()
def show(self): import gtk from gtk import Window, Label w = Window() w.set_size_request(*self.resolution) l = gtk.Label('Coordinates') w.add(l) l.show() w.add_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK) def configure_event(widget, event): pass def button_release_event(widget, event): if event.button == 1: print "unclick" self.server.send('u', 1, event.x, event.y) return True def button_press_event(widget, event): if event.button == 1: print "click" self.server.send('d', 1, event.x, event.y) return True def motion_notify_event(widget, event): if event.is_hint: x, y, state = event.window.get_pointer() else: print "no hint" x, y, state = event.x, event.y, event.state l.set_text("(%d,%d)" % (x,y)) print "Event number %d, (%d,%d)" % (event.type, x, y) self.server.send('.', 1, event.x, event.y) return True w.connect("configure_event", configure_event) w.connect("motion_notify_event", motion_notify_event) w.connect("button_press_event", button_press_event) w.connect("button_release_event", button_release_event) w.connect("delete_event", gtk.main_quit) if self.fullscreen: w.fullscreen() w.show() self.server.resolution = w.get_size() gtk.main()
def main(): print 'answer', input_entry_dialog("who what?", 'edit me') gtk_info_message("hi there missy") w = Window() w.resize(200, 200) w.connect( "delete-event", main_quit ) vbox = VBox() w.add(vbox) ONE_DAY = timedelta(days=1) existing_list = [PersistentList(test_program_return_new_row())] model, tv, tv_vbox = \ create_editable_type_defined_listview_and_model( ( ('date', date,), ('choose-me', (True, str, 'yo', 'hi', 'me', 'fun') ), # end choose-me tuple ('choose-me-only', (False, str, 'yo', 'hi', 'me', 'fun') ), # end choose-me-only tuple ('choose-me-num', (False, int, 1, 2, 3, 4) ), # end choose-num tuple ('description', str), ('count', int), ('file_path', {'type': file, 'file_type':FILE_CHOOSER_ACTION_SELECT_FOLDER} ), ('choose-me-date', (False, date, date.today() - ONE_DAY, date.today(), date.today() + ONE_DAY ) ), ('choose-me-obj', (False, (None, TestProgType(), TestProgType()), 'None', 'obj 1', 'obj 2' ) ), ('choose-me-Decimal', (True, Decimal, '3.1', '3.4') ), ), # end type tuple test_program_return_new_row, existing_list, test_prog_list_changed, False ) # create_editable_type_defined_listview_and_model vbox.pack_start( tv_vbox ) w.show_all() gtk_main()
class SimpleTransactionEditor(object): def __init__(self, trans, transid, plugin, gui_parent, change_register_function, book): """Sub classes should not override this __init__ but instead implement simple_init_before_show() to hook in at the right time """ self.trans = trans self.transid = transid self.plugin = plugin self.gui_parent = gui_parent self.change_register_function = change_register_function self.book = book # An offscreen place for the transaction's GUI to hide while not in use. self.hide_parent = Window() self.hide_parent.hide() self.mainvbox = VBox() self.hide_parent.add(self.mainvbox) self.simple_init_before_show() self.mainvbox.show_all() self.mainvbox.reparent(self.gui_parent) def simple_init_before_show(self): """Create the GUI for this type of BoKeep transaction. Widgets can be added to the "self.mainvbox" object.""" raise Exception("simple_init_before_show must be overrided by " "sub classes of SimpleTransactionEditor") def detach(self): """Detach the BoKeep transaction's GUI from the visible window and attach it to a hidden window. Sub classes overriding this are recommended to do their own work first, and then delegate back up to this original detach so it may do the widget reparenting work""" self.mainvbox.reparent(self.hide_parent)
class MDSplusNidOptionWidget(props, MDSplusWidget, ComboBox): __gtype_name__ = 'MDSplusNidOptionWidget' __gproperties__ = props.__gproperties__ def xdbox_cancel(self, button): self.xdbox.set_modal(False) self.xdbox.expr.set_text(self.node_value()) button.get_toplevel().hide() def xdbox_close(self, button): try: value = self.value self.xdbox.set_modal(False) button.get_toplevel().hide() except: pass def xdbox_redo(self, button): self.xdbox.expr.set_text(self.node_value()) def button_press(self, cb, event): if self.get_active_text() == "Computed": if self.get_property('popup-shown'): self.popup_xd = True else: if self.popup_xd: if not hasattr(self, 'xdbox'): self.initXdbox() self.get_toplevel().set_focus(None) self.xdbox.set_modal(False) self.xdbox.show_all() self.popup_xd = False def node_value(self): value = self.record if value is None: value = '' else: value = str(value.decompile()) return value def fixValues(self): idx = 0 for value in self.values: if value.find('<DEVTOP>') > -1: try: self.values[idx] = value.replace( '<DEVTOP>', str(self.devnode)) except Exception: pass idx = idx+1 def updateItems(self): if not hasattr(self, 'values'): return m = self.get_model() if isinstance(self.values, str): self.values = self.values.split('\n') self.fixValues() if len(self.values) > len(m): self.values = self.values[0:len(m)-1] self.append_text('Computed') def initXdbox(self): self.xdbox = Window() try: self.xdbox.set_title(str(self.node)) except: pass vbox = VBox() self.xdbox.expr = MDSplusExprWidget() vbox.pack_start(self.xdbox.expr, True, True, 20) close = Button(stock=STOCK_CLOSE) close.connect("clicked", self.xdbox_close) redo = Button(stock=STOCK_REDO) redo.connect("clicked", self.xdbox_redo) cancel = Button(stock=STOCK_CANCEL) cancel.connect("clicked", self.xdbox_cancel) hbox = HBox() hbox.pack_start(close, False, False, 20) hbox.pack_start(redo, False, False, 20) hbox.pack_start(cancel, False, False, 20) vbox.pack_start(hbox, False, False, 20) self.xdbox.add(vbox) self.xdbox.expr.set_text(self.node_value()) def reset(self): value = self.node_value() if not hasattr(self, "has_been_initialized"): self.updateItems() self.has_been_initialized = True if not guibuilder: self.popup_xd = True self.connect('event', self.button_press) if hasattr(self, 'values'): self.set_active(len(self.values)) if not guibuilder: for idx in range(len(self.values)): val = self.values[idx] if val != '': try: newval = self.getNode().compile(val).decompile() val = str(newval) except Exception: print("Invalid value specified for an option item. Value string was <%s>. \nError was %s." % ( val, sys.exc_info())) if value == val: self.set_active(idx) break if hasattr(self, 'xdbox'): self.xdbox.expr.set_text(value) def getValue(self): idx = self.get_active() if idx < len(self.values): value = self.values[idx] elif hasattr(self, 'xdbox'): value = self.xdbox.expr.get_text() else: value = self.node_value() if value == '': return None else: try: return self.node.compile(value) except Exception: MDSplusErrorMsg('Invalid value', 'Invalid value specified.\n\n%s\n\n%s' % ( value, sys.exc_info())) raise value = property(getValue)
self.vbox = VBox() self.add_with_viewport(self.vbox) HasRecordBox.__init__(self, self.vbox, data, name=name) self.vbox.show() self.show() self.vbox.set_events(BUTTON_PRESS_MASK) class CommandBox(VBox, HasMenuBar): def __init__(self, name='CommandBox'): VBox.__init__(self) self.set_name(name) self.tbar = HandleToolbar() self.menubar = SimpleMenuBar() self.pack_start(self.menubar, FALSE, FALSE, 0) self.pack_end(self.tbar, FALSE, FALSE, 0) self.show() if __name__ == '__main__': import paella.gtk from gtk import mainloop, mainquit from paella.base.util import file2str from gtk import Window tt = TextTemplater(file2str('/etc/debconf.conf')) win = Window() win.add(tt) win.show() win.connect('destroy', mainquit) mainloop()
if machine not in self.pages: self.append_page(text, machine) self.set_current_page(machine) def _print_items(self, machine, raw=True): slines = _itemlines(self.cfg, machine, SYSOPTS, raw=raw) dblines = _itemlines(self.cfg, machine, DBOPTS, raw=raw) mnlines = _itemlines(self.cfg, machine, MAINOPTS, raw=raw) mclines = _itemlines(self.cfg, machine, MACHOPTS, raw=raw) umlines = _itemlines(self.cfg, machine, UMLOPTS, raw=raw) xumlines = _itemlines(self.cfg, machine, XUMLOPTS, raw=raw) alllines = [slines, dblines, mnlines, mclines, umlines, xumlines] sep = '\n\n------------------\n\n' text = sep.join(['\n'.join(lines) for lines in alllines]) + '\n' return text if __name__ == '__main__': from gtk import Window cfg = get_machines_config() sections = cfg.sections() print sections #d.set_rows([dict(section=x) for x in sections]) m = MachineBrowser(cfg) win = Window() win.add(m) win.show() win.connect('destroy', mainquit) mainloop()
class PointAndPick(object): def __init__(self, title=TITLE, level=WINDOW_TOPLEVEL, on_exit=None): self.title = title self.grabbing = False self.events = [] self.rgb = WHITE_RGB self.on_exit = on_exit self.window = Window(level) self.window.set_title(title) self.window.set_resizable(True) self.window.add_events(POINTER_MOTION_MASK) self.window.set_default_size(350, 150) self.colors = [] grab_btn = Button('Grab') grab_btn.connect_object('clicked', self.toggle_grab, self.window) self.grab_btn = grab_btn exit_btn = Button('Exit') exit_btn.connect_object('clicked', self.destroy, self.window) drawing = DrawingArea() drawing.connect_object('expose_event', self.do_expose, self.window) self.drawing = drawing label = Label(rgb_to_string(WHITE_RGB)) self.label = label table = Table(2, 2, True) table.attach(self.drawing, 0, 1, 0, 1) table.attach(label, 0, 1, 1, 2) table.attach(grab_btn, 1, 2, 0, 1) table.attach(exit_btn, 1, 2, 1, 2) self.window.add(table) def show(self): self.window.show_all() def destroy(self, *args, **kwargs): self.window.hide_all() self.window.do_destroy(self.window) if self.on_exit: self.on_exit() def toggle_grab(self, *args, **kwargs): """Toggle pointer grabbing""" { True: self.ungrab, False: self.grab }[self.grabbing]() def grab(self): """Grab pointer""" if pointer_grab(self.window.window, True, GRAB_MASK) == GRAB_SUCCESS: self.grabbing = True self.grab_btn.set_label('Ungrab') e = [ ('motion_notify_event', self.motion_notify_event), ('button_press_event', self.button_press_event) ] self.events = [ self.window.connect(n, h) for n, h in e ] def ungrab(self): """Ungrab pointer""" pointer_ungrab() while self.events: self.window.disconnect(self.events.pop()) self.grabbing = False self.grab_btn.set_label('Grab') def do_expose(self, *args, **kwargs): """Expose the window""" gc_obj = self.drawing.window.new_gc() gc_obj.set_foreground(SYS_COLORMAP.alloc_color('black')) self.drawing.window.draw_rectangle(gc_obj, False, 10, 10, 100, 100) self.draw_color() def draw_color(self): """Drag the color box with the pixel under the mouse pointer""" gc_obj = self.drawing.window.new_gc() gc_obj.set_foreground(SYS_COLORMAP.alloc_color(rgb_to_string(self.rgb), True)) self.drawing.window.draw_rectangle(gc_obj, True, 11, 11, 99, 99) def motion_notify_event(self, win, event): """Mouse motion_notify_event handler""" pixbuf = Pixbuf(COLORSPACE_RGB, False, 8, 1, 1) root = get_default_root_window() xcoord, ycoord = event.get_root_coords() from_draw = pixbuf.get_from_drawable(root, root.get_colormap(), int(xcoord), int(ycoord), 0, 0, 1, 1) pixel = from_draw.get_pixels_array()[0][0] self.rgb = (pixel[0], pixel[1], pixel[2]) self.draw_color() self.label.set_label(rgb_to_string(self.rgb).upper()) def button_press_event(self, *args, **kwargs): """Mouse button_press_event handler""" self.ungrab()
self.form = GeoForm() self.result = GeoResult() self.pack_start(self.form, False) self.pack_start(self.result) self.login = GeoCaching() self.search = None self.form.connect('search', self.do_search) def do_search(self, widget, lat, long): self.search = self.login.search_lat_long(lat, long) for row in self.search.results: self.result.add_cache(row) self.result.show_all() if __name__ == '__main__': W = Window() S = Search() W.connect('destroy', main_quit) W.set_title("Search for caches") W.set_size_request(300, 200) W.add(S) W.show_all() main()
return False def _on_toggled(self, button): if button.get_active(): self._do_show_popup() else: self._do_hide_popup() def _on_expose(self, widget, event): self._update_popup_geometry() if __name__ == '__main__': btn = PopupWidgetButton(label='TestMe', widget=gtk.Button('Click me')) hb = gtk.HBox() hb.pack_start(gtk.Button('Left'), expand=False, fill=False) hb.pack_start(btn, expand=False, fill=False) hb.pack_start(gtk.Button('Right'), expand=False, fill=False) vb = gtk.VBox() vb.pack_start(hb, expand=False, fill=False) from gtk import Window wnd = Window() wnd.set_size_request(400, 300) wnd.set_title('Pop-up Window Button Test') wnd.add(vb) wnd.connect('destroy', lambda *args: gtk.main_quit()) wnd.show_all() gtk.main()
text = TextScroll(self._print_items(machine)) if machine not in self.pages: self.append_page(text, machine) self.set_current_page(machine) def _print_items(self, machine, raw=True): slines = _itemlines(self.cfg, machine, SYSOPTS, raw=raw) dblines = _itemlines(self.cfg, machine, DBOPTS, raw=raw) mnlines = _itemlines(self.cfg, machine, MAINOPTS, raw=raw) mclines = _itemlines(self.cfg, machine, MACHOPTS, raw=raw) umlines = _itemlines(self.cfg, machine, UMLOPTS, raw=raw) xumlines = _itemlines(self.cfg, machine, XUMLOPTS, raw=raw) alllines = [slines, dblines, mnlines, mclines, umlines, xumlines] sep = '\n\n------------------\n\n' text = sep.join(['\n'.join(lines) for lines in alllines]) + '\n' return text if __name__ == '__main__': from gtk import Window cfg = get_machines_config() sections = cfg.sections() print sections #d.set_rows([dict(section=x) for x in sections]) m = MachineBrowser(cfg) win = Window() win.add(m) win.show() win.connect('destroy', mainquit) mainloop()
class MDSplusNidOptionWidget(props,MDSplusWidget,ComboBox): __gtype_name__ = 'MDSplusNidOptionWidget' __gproperties__ = props.__gproperties__ def xdbox_cancel(self,button): self.xdbox.set_modal(False) self.xdbox.expr.set_text(self.node_value()) button.get_toplevel().hide() def xdbox_close(self,button): try: value=self.value self.xdbox.set_modal(False) button.get_toplevel().hide() except: pass def xdbox_redo(self,button): self.xdbox.expr.set_text(self.node_value()) def button_press(self,cb,event): if self.get_active_text() == "Computed": if self.get_property('popup-shown'): self.popup_xd=True else: if self.popup_xd: if not hasattr(self,'xdbox'): self.initXdbox() self.get_toplevel().set_focus(None) self.xdbox.set_modal(False) self.xdbox.show_all() self.popup_xd=False def node_value(self): value=self.record if value is None: value='' else: value=str(value.decompile()) return value def fixValues(self): idx=0 for value in self.values: if value.find('<DEVTOP>') > -1: try: self.values[idx]=value.replace('<DEVTOP>',str(self.devnode)) except Exception: pass idx=idx+1 def updateItems(self): if not hasattr(self,'values'): return m=self.get_model() if isinstance(self.values,str): self.values=self.values.split('\n') self.fixValues() if len(self.values) > len(m): self.values=self.values[0:len(m)-1] self.append_text('Computed') def initXdbox(self): self.xdbox=Window() try: self.xdbox.set_title(str(self.node)) except: pass vbox=VBox() self.xdbox.expr=MDSplusExprWidget() vbox.pack_start(self.xdbox.expr,True,True,20) close=Button(stock=STOCK_CLOSE) close.connect("clicked",self.xdbox_close) redo=Button(stock=STOCK_REDO) redo.connect("clicked",self.xdbox_redo) cancel=Button(stock=STOCK_CANCEL) cancel.connect("clicked",self.xdbox_cancel) hbox=HBox() hbox.pack_start(close,False,False,20) hbox.pack_start(redo,False,False,20) hbox.pack_start(cancel,False,False,20) vbox.pack_start(hbox,False,False,20) self.xdbox.add(vbox) self.xdbox.expr.set_text(self.node_value()) def reset(self): value=self.node_value() if not hasattr(self,"has_been_initialized"): self.updateItems() self.has_been_initialized=True if not guibuilder: self.popup_xd=True self.connect('event',self.button_press) if hasattr(self,'values'): self.set_active(len(self.values)) if not guibuilder: for idx in range(len(self.values)): val=self.values[idx] if val != '': try: newval=self.getNode().compile(val).decompile() val=str(newval) except Exception: print("Invalid value specified for an option item. Value string was <%s>. \nError was %s." % (val,sys.exc_info())) if value == val: self.set_active(idx) break if hasattr(self,'xdbox'): self.xdbox.expr.set_text(value) def getValue(self): idx=self.get_active() if idx < len(self.values): value=self.values[idx] elif hasattr(self,'xdbox'): value=self.xdbox.expr.get_text() else: value=self.node_value() if value == '': return None else: try: return self.node.compile(value) except Exception: MDSplusErrorMsg('Invalid value','Invalid value specified.\n\n%s\n\n%s' % (value,sys.exc_info())) raise value=property(getValue)
#!/usr/bin/env python from gtk import Window, ColorSelection, main window = Window() window.add(ColorSelection()) window.show_all() main()
box = gtk.VBox(False, 0) stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') btn_same = Button("SAME") btn_same.connect_object("button_press_event", same_cb, window) box.pack_start(btn_same, True, True, 0) btn_project = Button("project") btn_project.connect_object("button_press_event", project_cb, window) box.pack_start(btn_project, True, True, 0) btn_study = Button("study") btn_study.connect_object("button_press_event", study_cb, window) box.pack_start(btn_study, True, True, 0) btn_life = Button("life") btn_life.connect_object("button_press_event", life_cb, window) box.pack_start(btn_life, True, True, 0) btn_other = Button("other") btn_other.connect_object("button_press_event", other_cb, window) box.pack_start(btn_other, True, True, 0) window.add(box) window.show_all() gtk.main()
self.pack_start(self.form, False) self.pack_start(self.result) self.login = GeoCaching() self.search = None self.form.connect('search', self.do_search) def do_search(self, widget, lat, long): self.search = self.login.search_lat_long(lat, long) for row in self.search.results: self.result.add_cache(row) self.result.show_all() if __name__ == '__main__': W = Window() S = Search() W.connect('destroy', main_quit) W.set_title("Search for caches") W.set_size_request(300,200) W.add(S) W.show_all() main()
def __init__(self, name='CommandBox'): VBox.__init__(self) self.set_name(name) self.tbar = HandleToolbar() self.menubar = SimpleMenuBar() self.pack_start(self.menubar, False, False, 0) self.pack_end(self.tbar, False, False, 0) self.show() class TwinScrollCList(HPaned): def __init__(self, name='TwinScrollCList'): HPaned.__init__(self) self.set_name(name) self.lbox = ScrollCList() self.rbox = ScrollCList() self.add1(self.lbox) self.add2(self.rbox) self.show() if __name__ == '__main__': import useless.gtk from gtk import mainloop, mainquit from useless.base.util import file2str from gtk import Window tt = TextTemplater(file2str('/etc/debconf.conf')) win = Window() win.add(tt) win.show() win.connect('destroy', mainquit) mainloop()
class Base(object): def __init__(self): from gtk import Window,WINDOW_TOPLEVEL,Button,Label,HBox,Entry,VBox,VSeparator self.window = Window(WINDOW_TOPLEVEL) self.window.set_title("Slideshow") self.window.connect("delete_event", self.delete_event) self.window.set_border_width(10) self.vbox = VBox(False, 0) self.window.add(self.vbox) self.hbox1 = HBox(False, 0) self.vbox.pack_start(self.hbox1, True, True, 1) self.hbox = HBox(False, 0) self.vbox.pack_start(self.hbox, False, False, 1) self.hbox2 = HBox(False, 0) self.vbox.pack_start(self.hbox2, True, True, 1) self.label = Label('Identifikační číslo:') self.hbox.pack_start(self.label, False, False, 1) self.label.show() self.editable = Entry() self.editable.connect('key_press_event', self.key_press_event) self.hbox.pack_start(self.editable, True, True, 1) self.editable.show() self.button = Button("Začít") self.button.connect("clicked", self.callback) self.button.set_receives_default(True) self.button.set_can_focus(True) self.hbox.pack_start(self.button, False, False, 1) self.button.show() self.hbox1.show() self.hbox.show() self.hbox2.show() self.vbox.show() self.window.show() def delete_event(self, widget, event, data=None): gtk.main_quit() return False def key_press_event(self, widget, event): from gtk.gdk import keyval_from_name,keyval_name if event.keyval in (keyval_from_name('Return'),keyval_from_name('KP_Enter')): self.callback(widget) def _getFilePaths(self, fileTypes, recursive=True): import os import re from sys import argv pt = re.compile(r'.*([%(0)s][^%(0)s]*)'%{'0':os.path.extsep}) path = [a for m,a in ((pt.match(os.path.basename(a)),a) for a in argv[1:]) if m and m.group(1) in fileTypes] if not path: path = '/home/pi/img/*.jpg' if isinstance(path, str): ## Returns list containing paths of files in /path/ that are of a file type in /fileTypes/, ## if /recursive/ is False subdirectories are not checked. paths = [] if recursive: for root, folders, files in os.walk(path, followlinks=True): for file in files: for fileType in fileTypes: if file.endswith(fileType): paths.append(os.path.join(root, file)) else: for item in os.listdir(path): for fileType in fileTypes: if item.endswith(fileType): paths.append(os.path.join(root, item)) return paths elif iterable(path): return path else: return [] def _init_cb(self,trans): from threading import Thread if not iterable(trans): trans = trans, callbacks = [] for name,cb in trans: t = Thread(target=cb, name='%sThread'%name) t.daemon = True t.start() callbacks.append(cb.enqueue) def wrap(msg): for cb in callbacks: if not cb(msg): return False return True return wrap def callback(self, widget): from slideshow import SlideShow from trans import Message,GpioTransceiver,JsonTransceiver if not self.editable.get_text(): return False img_cbs = self._init_cb([('ImgGpioCallback',GpioTransceiver(24)),('ImgJsonCallback',JsonTransceiver('img.json'))]) kp_cbs = self._init_cb([('KpGpioCallback',GpioTransceiver(26,bcd=False)),('KpJsonCallback',JsonTransceiver('kp.json'))]) def ordfnc(path): from numpy.random import permutation gray = path[0] result = [] for p in permutation(path[1:]): result.append(p) result.append(gray) return result slide = SlideShow( path=self._getFilePaths(('.jpg', '.jpeg', '.png')), transition='None', fullscreen=True, delay=5, order=ordfnc, principal=self.editable.get_text(), img_callback = img_cbs, kp_callback = kp_cbs, ) self.editable.set_text('') slide() def __call__(self): gtk.main()
from moodlight import moodlight_list, moodlight_get from gtk import Window, ColorSelection, main def makeChanger(moodlight): def cChanged(c): colour = c.get_current_color() r, g, b = (colour.red >> 8, colour.green >> 8, colour.blue >> 8) #print("(%s, %s, %s)" % (r, g, b)) moodlight.setRGB(r, g, b) return cChanged for umi in moodlight_list(): moodlight = moodlight_get(umi) w = Window() w.set_title(umi) c = ColorSelection() c.connect('color-changed', makeChanger(moodlight)) w.add(c) w.show_all() # Enter mainloop main()
class multipage_glade_editor(object): def __init__(self, trans, transid, plugin, gui_parent, change_register_function, book, display_mode=TRANSACTION_ALL_EDIT_FIRST_TIME, transaction_edit_finished_function=null_function): self.trans = trans self.transid = transid self.plugin = plugin self.gui_parent = gui_parent self.change_register_function = change_register_function self.book = book self.display_mode = display_mode self.transaction_edit_finished_function = ( null_function if display_mode not in HEADLESS_MODES else transaction_edit_finished_function ) self.hide_parent = Window() self.hide_parent.hide() self.mainvbox = VBox() self.hide_parent.add(self.mainvbox) config = self.trans.get_configuration_and_provide_on_load_hook() config_module_name = self.plugin.config_module_name if not config_valid(config): # even in the case of a broken config, we should still # display all of the data we have available... self.mainvbox.pack_start(Label("no configuration")) elif not self.trans.can_safely_proceed_with_config_module(config): # should display all data that's available instead of just # this label # # and should give # user an overide option where they either pick an old config # for one time use or just blow out the memory of having used # a different config... # # should also print the checksum itself so they know # what they need... # # perhaps eventually we even put in place some archival support # for saving old glade and config files and then code into the # the transaction -- hey, code you need to be editable is # over here.. # # now hopefully there is no marking of this transaction dirty # in this mode and the extra safegaurds we put into # MultipageGladeTransaction don't get activated self.mainvbox.pack_start( Label("out of date configuration. data is read only here for " "the safety of your old information, last adler " "CRC was %s" % self.trans.config_crc_cache )) else: # if the safety cache was relied on before we need to tell the # backend that the transaction is actually dirty, # and now that we know that we have a workable config, # there's a chance that we'll actually be able to avoid # relying on the cache this time if self.trans.get_safety_cache_was_used(): self.change_register_function() self.page_label = Label("") (x_align, y_align) = self.page_label.get_alignment() self.page_label.set_alignment(0.0, y_align) self.mainvbox.pack_start(self.page_label, expand=False) # establish maincontainer, which is where the actual glade # pages are put by attach_current_page # # The order of placement here is important, we place this # after page_label has already been added to main # and we also need to do this prior to attach_current_page # being called, as it depends on self.maincontainer being # there # # when we're in headless mode the maincontainer can just be # the mainvbox itself # # but, outside headless mode we save screen real-estate and # place a scrolled window (which becomes the maincontainer) # inside the mainvbox and the glade by glade pages end up # in there instead (again, in attach_current_page) if display_mode in HEADLESS_MODES: self.maincontainer = self.mainvbox else: self.maincontainer = Viewport() sw = ScrolledWindow() sw.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) sw.add( self.maincontainer) self.mainvbox.pack_start(sw) self.glade_pages = [ self.__setup_page(glade_file, top_glade_element) for glade_file, top_glade_element in config.pages ] self.glade_pages_by_ident_index = dict( ( (key, self.glade_pages[i]) for i, key in enumerate(config.pages) ) # end generator expression ) # end dict self.__setup_auto_widgets() self.current_page = 0 self.attach_current_page() button_hbox = HBox() self.mainvbox.pack_end(button_hbox, expand=False) self.nav_buts = dict( (Button(), i) for i in range(2) ) for but, i in self.nav_buts.iteritems(): but.set_property('use-stock', True) but.set_label( STOCK_GO_BACK if i == GLADE_BACK_NAV else STOCK_GO_FORWARD ) button_hbox.pack_start(but, expand=False) but.connect("clicked", self.nav_but_clicked) config.gui_initialization_hook( self, self.trans, self.plugin, self.book) self.mainvbox.show_all() self.mainvbox.reparent(self.gui_parent) def page_is_current(self, page): # assumption is that config is fine and we're on a page assert( hasattr(self, 'glade_pages_by_ident_index') and True ) return \ self.glade_pages_by_ident_index[page] == self.current_widget_dict def __setup_page(self, glade_file, top_glade_element): widget_dict = {} # this should come from the config, seeing how we're setting up # our stuff manually event_handlers_dict = {} load_glade_file_get_widgets_and_connect_signals( glade_file, top_glade_element, widget_dict, event_handlers_dict ) widget_dict[top_glade_element].hide() return widget_dict def __setup_auto_widgets(self): # go through each page for key, widget_dict in self.glade_pages_by_ident_index.iteritems(): # go through each widget for widget_name, widget in widget_dict.iteritems(): widget_key = (key, widget_name) # determine if the current widget is one that we can take # care of automatically saving, we do this with a linear # search through a table of eligible types, # where the first element of each entry is Widget class # # Once we have a match do one of the following # * Change the widget from the existing stored stage # * Establish new state from some default # The next two entries in the table # (change_widget_from_state, new_state_from_widget) # provide functions to do this # # Lastly, we establish event handlers for this widget using # the last element in the table for (cls, change_widget_from_state, new_state_from_widget, establish_event_handlers) in ( # start table (Entry, lambda w, wk: w.set_text(self.trans.get_widget_state(wk)), lambda w: '', lambda w: w.connect("changed", self.entry_changed), ), # Entry (Calendar, self.__change_calendar_from_saved_version, get_current_date_of_gtkcal, lambda w: w.connect( "day_selected", self.calendar_changed ), ), # Calendar (CheckButton, lambda w, wk: w.set_active(self.trans.get_widget_state(wk)), get_state_of_checkbutton, lambda w: w.connect("toggled", self.checkbutton_changed), ), # CheckButton ): # end of table and for declartion # does the widget match the type in the current table entry? if isinstance(widget, cls): # use the three remaining functions in the table # as appropriate if self.trans.has_widget_state( widget_key ): change_widget_from_state(widget, widget_key) else: self.trans.update_widget_state( widget_key, new_state_from_widget(widget) ) establish_event_handlers(widget) def __change_calendar_from_saved_version(self, widget, widget_key): set_current_date_of_gtkcal(widget, self.trans.get_widget_state( widget_key ) ) def attach_current_page(self): config = self.plugin.get_configuration(allow_reload=False) self.current_widget_dict = self.glade_pages[self.current_page] self.current_window = self.current_widget_dict[ config.pages[self.current_page][TOP_WIDGET] ] self.current_top_vbox = self.current_window.child self.current_top_vbox.reparent( self.maincontainer) self.page_label.set_text( "page %s of %s" %( self.current_page + 1, len(config.pages) ) ) self.update_auto_labels() def detach_current_page(self): # put the spawn back to wence it came self.current_top_vbox.reparent( self.current_window) def detach(self): if hasattr(self, 'current_page'): self.detach_current_page() self.mainvbox.reparent(self.hide_parent) def page_change_acceptable_by_input_valid(self): bad_fields = ', '.join( widget_name for widget_name, widget in self.current_widget_dict.iteritems() if not self.widget_valid(widget_name, widget) ) if bad_fields == '': return True else: # this is kind of primiative, it would be better to # just highlight them by inserting red lights or something gtk_error_message("The following fields are invalid %s" % bad_fields ) return False def __current_page_ident(self): config = self.plugin.get_configuration(allow_reload=False) return config.pages[self.current_page] def __entry_widget_is_check_excempt(self, widget_name): config = self.plugin.get_configuration(allow_reload=False) return (self.__current_page_ident(), widget_name) in \ config.non_decimal_check_labels def widget_valid(self, widget_name, widget): config = self.plugin.get_configuration(allow_reload=False) if isinstance(widget, Entry) and \ not self.__entry_widget_is_check_excempt(widget_name): try: entry_to_decimal_convert( widget.get_text(), widget_name, self.__current_page_ident(), config) except EntryTextToDecimalConversionFail: return False # this covers not only the else case on the first if, but the # the case with the above try, except passes without exception return True def nav_but_clicked(self, but, *args): config = self.plugin.get_configuration(allow_reload=False) old_page = self.current_page delta = -1 if self.nav_buts[but] == GLADE_BACK_NAV else 1 new_page = old_page + delta # reject a change outside the acceptable range.. and hmm, # perhaps this event handler should never even run under those # conditions because we should really just grey the buttons if not (new_page < 0 or new_page == len(self.glade_pages)) and \ self.page_change_acceptable_by_input_valid() and \ config.page_change_acceptable(self.trans, old_page, new_page): # intentionally done before the page is actually attached, # that's what we mean by pre config.page_pre_change_config_hooks(self.trans, old_page, new_page) self.detach_current_page() self.current_page = new_page self.attach_current_page() # intentionally done after the page is actually attached, # that's what we mean by post config.page_post_change_config_hooks(self.trans, old_page, new_page) entry_changed = make_widget_changed_func(lambda w: w.get_text() ) calendar_changed = make_widget_changed_func(get_current_date_of_gtkcal) checkbutton_changed = make_widget_changed_func(get_state_of_checkbutton) def update_auto_labels(self): config = self.plugin.get_configuration(allow_reload=False) # this function should never be called if the config hasn't been # checked out as okay assert( hasattr(config, 'auto_update_labels') ) for page, label_name, label_source_func in config.auto_update_labels: if self.page_is_current(page): try: label_text = str(label_source_func( self.trans.widget_states, config)) except EntryTextToDecimalConversionFail, e: label_text = '' except WidgetFindError, no_find_e: label_text = str(no_find_e) self.current_widget_dict[label_name].set_text(label_text)