def _create_source_view(self): ''' Creacion de las pestanas que mostraran el codigo fuente de las paginas TODO: Obtener el html a traves del webview y no con urllib ''' ''' obtenemos la url que esta mostrando la pestana actual ''' url = self.tabs[self.notebook.get_current_page()][0].url_bar.get_text() ''' Pedimos la pagina con urllib ''' response = urllib2.urlopen(url) page = response.read() soup = BeautifulSoup(page) ''' La ponemos bonita con bs4''' html = soup.prettify() ''' Ahora hacemos uso de la libreria pygtkcodebuffer para mostrar el codigo que acabamos de obtener Primero establecemos el lenguaje que estamos usando para colorear el codigo ''' lang = SyntaxLoader("html") ''' Creamos el buffer ''' buff = CodeBuffer(lang=lang) ''' Lo metemos dentro de una ventana con scroll ''' scr = gtk.ScrolledWindow() scr.add(gtk.TextView(buff)) ''' Y lo mostramos ''' buff.set_text(html) return url, scr
def __init__(self): self.__gladefile = os.path.join(os.path.dirname(__file__), "simpleedit.glade") self.__xml = gtk.glade.XML(self.__gladefile, "mainwindow") synmenu = self.__xml.get_widget("syntaxmenu") lst = glob.glob("../syntax/*.xml") lst.sort() lst = map( lambda x: re.match("^(.+)\.xml$", os.path.basename(x)).group(1), lst) for lang in lst: item = gtk.MenuItem(lang, False) synmenu.append(item) item.connect("activate", self.on_lang_changed, lang) self.__xml.get_widget("fileopen").connect("activate", self.on_open) self.__xml.get_widget("helpinfo").connect("activate", self.on_show_info) self.__xml.get_widget("mainwindow").show_all() self.__xml.get_widget("mainwindow").connect("destroy", self.on_destroy) self.__buffer = CodeBuffer(None) self.__xml.get_widget("textview").set_buffer(self.__buffer)
def __init__(self): _path = path.dirname(sys.modules[self.__module__].__file__) _conf_filename = '%s/config' %_path _conf_dict = { 'Menu': {'Layer': 'gimp-layer*'}, 'Templates': {'Get first layer': 'layer = image.layers[0]'} } if not(path.isfile(_conf_filename)): self._create_conf_file(_conf_filename, _conf_dict) self.config = ConfigParser() self.config.read(_conf_filename) self._check_conf(_conf_filename, _conf_dict) self.ui = gtk.Builder() self.ui.set_translation_domain('GEB') self.ui.add_from_file('%s/batch_ex.ui' %_path) self.ui.connect_signals(self) self.status = self.ui.get_object('status') #Check Gimp version and updade syntax file, if needed self._check_syntax('%s/python-fu.xml' %_path) add_syntax_path(_path) buff = CodeBuffer(lang=SyntaxLoader("python-fu")) self.ui.get_object('code').set_buffer(buff) buff.connect('changed', self.code_changed) self.base = shelve.open('%s/batch_base' %_path) self._get_macro_list() self._ckey = "" self.browse_dlg = None # Menu self._create_menu() # colors self.red_color = pango.AttrList() self.red_color.insert(pango.AttrForeground(65535, 0, 0, 0, -1)) self.red_color.insert(pango.AttrWeight(pango.WEIGHT_HEAVY, 0, -1)) self.green_color = pango.AttrList() self.green_color.insert(pango.AttrForeground(0, 65535, 0, 0, -1)) self.green_color.insert(pango.AttrWeight(pango.WEIGHT_HEAVY, 0, -1)) self.blue_color = pango.AttrList() self.blue_color.insert(pango.AttrForeground(0, 0, 65535, 0, -1)) self.blue_color.insert(pango.AttrWeight(pango.WEIGHT_HEAVY, 0, -1)) # Log self._log = self.ui.get_object('log').get_buffer() self._log.create_tag('alert', foreground='red', weight=700) self._log.create_tag('ok', foreground='black') self._log.create_tag('done', foreground='blue', weight=700) self._set_status(ST_NEW) self.format_changed(self.ui.get_object('format_combo')) self._add_log(_('GEB started!'), 'done')
def GetCodeBuffer(filename): codeBuffer = None if filename not in CodeBuffers: codeBuffer = CodeBuffer(lang=lang) filePath = os.path.join(Config_Application_Folder, filename) fileContents = open(filePath, 'r').read() codeBuffer.set_text(fileContents) CodeBuffers[filename] = codeBuffer else: codeBuffer = CodeBuffers[filename] return codeBuffer
class Editor: def __init__(self): self.__gladefile = os.path.join(os.path.dirname(__file__), "simpleedit.glade") self.__xml = gtk.glade.XML(self.__gladefile, "mainwindow") synmenu = self.__xml.get_widget("syntaxmenu") lst = glob.glob("../syntax/*.xml") lst.sort() lst = map( lambda x: re.match("^(.+)\.xml$", os.path.basename(x)).group(1), lst) for lang in lst: item = gtk.MenuItem(lang, False) synmenu.append(item) item.connect("activate", self.on_lang_changed, lang) self.__xml.get_widget("fileopen").connect("activate", self.on_open) self.__xml.get_widget("helpinfo").connect("activate", self.on_show_info) self.__xml.get_widget("mainwindow").show_all() self.__xml.get_widget("mainwindow").connect("destroy", self.on_destroy) self.__buffer = CodeBuffer(None) self.__xml.get_widget("textview").set_buffer(self.__buffer) def on_lang_changed(self, widget, lang): lspec = SyntaxLoader(lang) self.__buffer.reset_language(lspec) def on_open(self, widget): dlg = gtk.FileSelection("Open...") if not dlg.run() == gtk.RESPONSE_OK: dlg.destroy() return fname = dlg.get_filename() dlg.destroy() self.__buffer.set_text(open(fname, "r").read()) def on_show_info(self, widget): dlg = gtk.glade.XML(self.__gladefile, "aboutdialog").get_widget("aboutdialog") dlg.run() dlg.destroy() def on_destroy(self, widget): gtk.main_quit()
class Editor: def __init__(self): self.__gladefile = os.path.join(os.path.dirname(__file__), "simpleedit.glade") self.__xml = gtk.glade.XML(self.__gladefile, "mainwindow") synmenu = self.__xml.get_widget("syntaxmenu") lst = glob.glob("../syntax/*.xml") lst.sort() lst = map(lambda x: re.match("^(.+)\.xml$",os.path.basename(x)).group(1), lst) for lang in lst: item = gtk.MenuItem(lang, False) synmenu.append(item) item.connect("activate", self.on_lang_changed, lang) self.__xml.get_widget("fileopen").connect("activate", self.on_open) self.__xml.get_widget("helpinfo").connect("activate", self.on_show_info) self.__xml.get_widget("mainwindow").show_all() self.__xml.get_widget("mainwindow").connect("destroy",self.on_destroy) self.__buffer = CodeBuffer(None) self.__xml.get_widget("textview").set_buffer(self.__buffer) def on_lang_changed(self, widget, lang): lspec = SyntaxLoader(lang) self.__buffer.reset_language(lspec) def on_open(self, widget): dlg = gtk.FileSelection("Open...") if not dlg.run() == gtk.RESPONSE_OK: dlg.destroy() return fname = dlg.get_filename() dlg.destroy() self.__buffer.set_text(open(fname, "r").read()) def on_show_info(self, widget): dlg = gtk.glade.XML(self.__gladefile, "aboutdialog").get_widget("aboutdialog") dlg.run() dlg.destroy() def on_destroy(self, widget): gtk.main_quit()
def userNewFile(self, widget, data=None): tab_box = gtk.HBox(False, 0) tab_box.show() new_file_label = gtk.Label("Untitled") tab_box.pack_start(new_file_label, False, False, 5) new_file_label.show() close_button = gtk.Button("X") tab_box.pack_start(close_button, False, False, 5) close_button.show() scrolledwindow = gtk.ScrolledWindow() scrolledwindow.show() lang = SyntaxLoader("python") buff = CodeBuffer(lang=lang) textview = gtk.TextView(buff) textview.connect("key-press-event", self.markFileAsModified) textview.filepath = "" #so we don't get an error when we try to save scrolledwindow.add(textview) textview.show() self.file_notebook.append_page(scrolledwindow, tab_box) close_button.connect("clicked", self.removePage, scrolledwindow)
def __init__(self, render_callback, src, settings): """Takes the following parameters: * render_callback: callback function to execute with "apply" button * src: source code that should be pre-inserted into the LaTeX input""" self.render_callback = render_callback self.src = src if src else "" self.settings = settings # init the syntax highlighting buffer lang = SyntaxLoader("latex") self.syntax_buffer = CodeBuffer(lang=lang) self.setup_ui()
def userOpenFile(self, widget, data=None): chooser = gtk.FileChooserDialog( title=None, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) chooser.show() response = chooser.run() if response == gtk.RESPONSE_OK: #read file filepath = chooser.get_filename() fo = open(filepath, "r") text = fo.read() fo.close() #put text into textview #create (and pack some stuff into) box for page's label tab_box = gtk.HBox(False, 0) tab_box.show() file_label = gtk.Label(os.path.basename(filepath)) tab_box.pack_start(file_label, False, False, 5) file_label.show() close_button = gtk.Button("X") tab_box.pack_start(close_button, False, False, 5) close_button.show() scrolledwindow = gtk.ScrolledWindow() scrolledwindow.show() lang = SyntaxLoader("python") buff = CodeBuffer(lang=lang) textview = gtk.TextView(buff) textview.connect("key-press-event", self.markFileAsModified) textview.filepath = filepath #storing so we can save file later scrolledwindow.add(textview) textview.show() textv_buffer = textview.get_buffer() textv_buffer.set_text(text) self.file_notebook.append_page(scrolledwindow, tab_box) close_button.connect("clicked", self.removePage, scrolledwindow) chooser.destroy()
def __create_text_with_line_number(self): scrolled_window = gtk.ScrolledWindow() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scrolled_window.set_shadow_type(gtk.SHADOW_IN) from gtkcodebuffer import CodeBuffer, SyntaxLoader lang = SyntaxLoader("pl0") buffer = CodeBuffer(lang=lang) text_view = gtk.TextView(buffer) fontdesc = pango.FontDescription('Monospace 11') text_view.modify_font(fontdesc) scrolled_window.add(text_view) #text_view.set_editable(False) #text_view.set_cursor_visible(False) text_view.set_border_window_size(gtk.TEXT_WINDOW_LEFT, 20) text_view.connect("expose_event", self.line_numbers_expose) return scrolled_window, buffer
def __init__(self): self.__gladefile = os.path.join(os.path.dirname(__file__), "simpleedit.glade") self.__xml = gtk.glade.XML(self.__gladefile, "mainwindow") synmenu = self.__xml.get_widget("syntaxmenu") lst = glob.glob("../syntax/*.xml") lst.sort() lst = map(lambda x: re.match("^(.+)\.xml$",os.path.basename(x)).group(1), lst) for lang in lst: item = gtk.MenuItem(lang, False) synmenu.append(item) item.connect("activate", self.on_lang_changed, lang) self.__xml.get_widget("fileopen").connect("activate", self.on_open) self.__xml.get_widget("helpinfo").connect("activate", self.on_show_info) self.__xml.get_widget("mainwindow").show_all() self.__xml.get_widget("mainwindow").connect("destroy",self.on_destroy) self.__buffer = CodeBuffer(None) self.__xml.get_widget("textview").set_buffer(self.__buffer)
def __init__(self): #Set the Glade file self.builder = gtk.Builder() self.builder.add_from_file(GLADE_PATH) # get top window self.window = self.builder.get_object("top_window") # status bar stuff self.statusbar = self.builder.get_object("statusbar") self.statusbar_ctx = self.statusbar.get_context_id("default") # set buttons self.save_button = self.builder.get_object('save_file_toolbutton') self.connect_button = self.builder.get_object('connect_button') self.save_button.set_sensitive(False) self.connect_button.set_sensitive(True) # set control buttons self.controls = [ self.builder.get_object('reset_button'), self.builder.get_object('bootloader_button'), self.builder.get_object('exec_button'), self.builder.get_object('stop_button'), self.builder.get_object('zoomin_button'), self.builder.get_object('zoomout_button'), self.builder.get_object('bestfit_button'), self.builder.get_object('refresh_button')] self.connected = False map(lambda x:x.set_sensitive(False), self.controls) # workaround bug in gtkcodebuffer gtkcodebuffer.SYNTAX_PATH.append(os.path.join(sys.prefix,"local", "share","pygtkcodebuffer","syntax")) # Configure source viewer self.buffer = CodeBuffer(lang=SyntaxLoader("python")) self.buffer.connect("changed", self.text_changed) tabs = pango.TabArray(1, True) tabs.set_tab(0, pango.TAB_LEFT, 8*4) #seems right txtview = gtk.TextView(self.buffer) txtview.set_tabs(tabs) self.builder.get_object("src_scrolledwindow").add(txtview) # Configure terminal window self.terminal_scroll = self.builder.get_object('vte_scrolledwindow') self.terminal = self.builder.get_object('vte_textview') self.terminal.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('black')) self.terminal.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('green')) # get drawingarea self.pixbuf = None self.drawingarea = self.builder.get_object("drawingarea") self.da_menu = self.builder.get_object("da_menu") # selection coords self.sel_ended=False self.selection_started=False self.x1 = self.y1 = self.x2 = self.y2 =0 # set control scales attributes self.builder.get_object("contrast_adjust").attr= openmv.ATTR_CONTRAST self.builder.get_object("brightness_adjust").attr= openmv.ATTR_BRIGHTNESS self.builder.get_object("saturation_adjust").attr= openmv.ATTR_SATURATION self.builder.get_object("gainceiling_adjust").attr= openmv.ATTR_GAINCEILING #connect signals signals = { "on_top_window_destroy" : self.quit, "on_connect_clicked" : self.connect_clicked, "on_reset_clicked" : self.reset_clicked, "on_fwupdate_clicked" : self.fwupdate_clicked, "on_fwpath_clicked" : self.fwpath_clicked, "on_execute_clicked" : self.execute_clicked, "on_stop_clicked" : self.stop_clicked, "on_motion_notify" : self.motion_notify, "on_button_press" : self.button_pressed, "on_button_release" : self.button_released, "on_open_file" : self.open_file, "on_new_file" : self.new_file, "on_save_file" : self.save_file, "on_save_file_as" : self.save_file_as, "on_save_template_activate" : self.save_template, "on_save_descriptor_activate" : self.save_descriptor, "on_ctrl_scale_value_changed" : self.on_ctrl_scale_value_changed, "on_zoomin_clicked" : self.zoomin_clicked, "on_zoomout_clicked" : self.zoomout_clicked, "on_bestfit_clicked" : self.bestfit_clicked, "on_preferences_clicked" : self.preferences_clicked, "on_updatefb_clicked" : self.updatefb_clicked, "on_vte_size_allocate" : self.scroll_terminal, } self.builder.connect_signals(signals) # create data directory if not os.path.isdir(DATA_DIR): os.makedirs(DATA_DIR) # create user scripts directory if not os.path.isdir(SCRIPTS_DIR): os.makedirs(SCRIPTS_DIR) # create fresh config if needed if not os.path.isfile(CONFIG_PATH): try: with open(CONFIG_PATH, "w") as f: f.write(DEFAULT_CONFIG) except Exception as e: print ("Failed to create config file %s"%(e)) sys.exit(1) # load config self.config = configparser.ConfigParser() try: self.config.read(CONFIG_PATH) except Exception as e: print ("Failed to open config file %s"%(e)) sys.exit(1) # current file path self.file_path= None self.fw_file_path="" # path = self.config.get("main", "last_opened_file") # if os.path.isfile(path): # self._load_file(path) # built-in examples menu submenu = gtk.Menu() menu = self.builder.get_object('example_menu') files = sorted(os.listdir(EXAMPLES_DIR)) for f in files: if f.endswith(".py"): label = os.path.basename(f) mitem = gtk.MenuItem(label) mitem.connect("activate", self.open_example, EXAMPLES_DIR) submenu.append(mitem) menu.set_submenu(submenu) # recent files menu self.files = [] files =self.config.get("main", "recent") if files: self.files = files.split(',') self.update_recent_files()
class OMVGtk: def __init__(self): #Set the Glade file self.builder = gtk.Builder() self.builder.add_from_file(GLADE_PATH) # get top window self.window = self.builder.get_object("top_window") # status bar stuff self.statusbar = self.builder.get_object("statusbar") self.statusbar_ctx = self.statusbar.get_context_id("default") # set buttons self.save_button = self.builder.get_object('save_file_toolbutton') self.connect_button = self.builder.get_object('connect_button') self.save_button.set_sensitive(False) self.connect_button.set_sensitive(True) # set control buttons self.controls = [ self.builder.get_object('reset_button'), self.builder.get_object('bootloader_button'), self.builder.get_object('exec_button'), self.builder.get_object('stop_button'), self.builder.get_object('zoomin_button'), self.builder.get_object('zoomout_button'), self.builder.get_object('bestfit_button'), self.builder.get_object('refresh_button')] self.connected = False map(lambda x:x.set_sensitive(False), self.controls) # workaround bug in gtkcodebuffer gtkcodebuffer.SYNTAX_PATH.append(os.path.join(sys.prefix,"local", "share","pygtkcodebuffer","syntax")) # Configure source viewer self.buffer = CodeBuffer(lang=SyntaxLoader("python")) self.buffer.connect("changed", self.text_changed) tabs = pango.TabArray(1, True) tabs.set_tab(0, pango.TAB_LEFT, 8*4) #seems right txtview = gtk.TextView(self.buffer) txtview.set_tabs(tabs) self.builder.get_object("src_scrolledwindow").add(txtview) # Configure terminal window self.terminal_scroll = self.builder.get_object('vte_scrolledwindow') self.terminal = self.builder.get_object('vte_textview') self.terminal.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('black')) self.terminal.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('green')) # get drawingarea self.pixbuf = None self.drawingarea = self.builder.get_object("drawingarea") self.da_menu = self.builder.get_object("da_menu") # selection coords self.sel_ended=False self.selection_started=False self.x1 = self.y1 = self.x2 = self.y2 =0 # set control scales attributes self.builder.get_object("contrast_adjust").attr= openmv.ATTR_CONTRAST self.builder.get_object("brightness_adjust").attr= openmv.ATTR_BRIGHTNESS self.builder.get_object("saturation_adjust").attr= openmv.ATTR_SATURATION self.builder.get_object("gainceiling_adjust").attr= openmv.ATTR_GAINCEILING #connect signals signals = { "on_top_window_destroy" : self.quit, "on_connect_clicked" : self.connect_clicked, "on_reset_clicked" : self.reset_clicked, "on_fwupdate_clicked" : self.fwupdate_clicked, "on_fwpath_clicked" : self.fwpath_clicked, "on_execute_clicked" : self.execute_clicked, "on_stop_clicked" : self.stop_clicked, "on_motion_notify" : self.motion_notify, "on_button_press" : self.button_pressed, "on_button_release" : self.button_released, "on_open_file" : self.open_file, "on_new_file" : self.new_file, "on_save_file" : self.save_file, "on_save_file_as" : self.save_file_as, "on_save_template_activate" : self.save_template, "on_save_descriptor_activate" : self.save_descriptor, "on_ctrl_scale_value_changed" : self.on_ctrl_scale_value_changed, "on_zoomin_clicked" : self.zoomin_clicked, "on_zoomout_clicked" : self.zoomout_clicked, "on_bestfit_clicked" : self.bestfit_clicked, "on_preferences_clicked" : self.preferences_clicked, "on_updatefb_clicked" : self.updatefb_clicked, "on_vte_size_allocate" : self.scroll_terminal, } self.builder.connect_signals(signals) # create data directory if not os.path.isdir(DATA_DIR): os.makedirs(DATA_DIR) # create user scripts directory if not os.path.isdir(SCRIPTS_DIR): os.makedirs(SCRIPTS_DIR) # create fresh config if needed if not os.path.isfile(CONFIG_PATH): try: with open(CONFIG_PATH, "w") as f: f.write(DEFAULT_CONFIG) except Exception as e: print ("Failed to create config file %s"%(e)) sys.exit(1) # load config self.config = configparser.ConfigParser() try: self.config.read(CONFIG_PATH) except Exception as e: print ("Failed to open config file %s"%(e)) sys.exit(1) # current file path self.file_path= None self.fw_file_path="" # path = self.config.get("main", "last_opened_file") # if os.path.isfile(path): # self._load_file(path) # built-in examples menu submenu = gtk.Menu() menu = self.builder.get_object('example_menu') files = sorted(os.listdir(EXAMPLES_DIR)) for f in files: if f.endswith(".py"): label = os.path.basename(f) mitem = gtk.MenuItem(label) mitem.connect("activate", self.open_example, EXAMPLES_DIR) submenu.append(mitem) menu.set_submenu(submenu) # recent files menu self.files = [] files =self.config.get("main", "recent") if files: self.files = files.split(',') self.update_recent_files() def show_message_dialog(self, msg_type, msg): message = gtk.MessageDialog(parent=self.window, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=msg_type, buttons=gtk.BUTTONS_OK, message_format=msg) message.run() message.destroy() def refresh_gui(self, delay=0.0001, wait=0.0001): sleep(delay) gtk.main_iteration_do(block=False) sleep(wait) def connect(self): init = False for i in range(0, 5): # init openmv init = openmv.init() if init: break sleep(0.200) if init == False: self.show_message_dialog(gtk.MESSAGE_ERROR, "Failed to connect to OpenMV") return # interrupt any running code openmv.stop_script() try: # open VCP and configure the terminal self.serial = serial.Serial(self.config.get("main", "serial_port"), 115200, timeout=0.001) gobject.gobject.idle_add(omvgtk.update_terminal) except Exception as e: self.show_message_dialog(gtk.MESSAGE_ERROR, "Failed to open serial port (check prefernces)\n%s"%e) return self.connected = True self._update_title() self.connect_button.set_sensitive(False) map(lambda x:x.set_sensitive(True), self.controls) def disconnect(self): #reset terminal #self.terminal.set_pty(-1) #self.terminal.reset(True, True) try: # stop running code openmv.stop_script(); except: pass # release OpenMV openmv.release() self.connected = False self._update_title() self.connect_button.set_sensitive(True) map(lambda x:x.set_sensitive(False), self.controls) def connect_clicked(self, widget): self.connect() def fwpath_clicked(self, widget): fw_entry = self.builder.get_object("fw_entry") dialog = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(SCRIPTS_DIR) ff = gtk.FileFilter() ff.set_name("dfu") ff.add_pattern("*.bin") #TODO change to DFU dialog.add_filter(ff) if dialog.run() == gtk.RESPONSE_OK: fw_entry.set_text(dialog.get_filename()) dialog.destroy() # Fake multitasking :P def fwupdate_task(self, state): if (state["init"]): pydfu.init() state["init"]=False state["erase"]=True state["bar"].set_text("Erasing...") return True elif (state["erase"]): page = state["page"] total = len(FLASH_OFFSETS) pydfu.page_erase(FLASH_OFFSETS[page]) page +=1 state["bar"].set_fraction(page/float(total)) if (page == total): state["erase"] = False state["write"] = True state["bar"].set_text("Uploading...") state["page"] = page return True elif (state["write"]): buf = state["buf"] xfer_bytes = state["xfer_bytes"] xfer_total = state["xfer_total"] # Send chunk chunk = min (64, xfer_total-xfer_bytes) pydfu.write_page(buf[xfer_bytes:xfer_bytes+chunk], xfer_bytes) xfer_bytes += chunk state["xfer_bytes"] = xfer_bytes state["bar"].set_fraction(xfer_bytes/float(xfer_total)) if (xfer_bytes == xfer_total): pydfu.exit_dfu() state["dialog"].hide() return False return True def fwupdate_clicked(self, widget): if (self.connected): dialog = self.builder.get_object("fw_dialog") fw_entry = self.builder.get_object("fw_entry") fw_progress = self.builder.get_object("fw_progressbar") ok_button = self.builder.get_object("fw_ok_button") cancel_button = self.builder.get_object("fw_cancel_button") ok_button.set_sensitive(True) cancel_button.set_sensitive(True) dialog.set_transient_for(self.window); # default FW bin path fw_entry.set_text(self.fw_file_path) fw_progress.set_text("") fw_progress.set_fraction(0.0) if dialog.run() == gtk.RESPONSE_OK: ok_button.set_sensitive(False) cancel_button.set_sensitive(False) fw_path = fw_entry.get_text() try: with open(fw_path, 'r') as f: buf= f.read() except Exception as e: dialog.hide() self.show_message_dialog(gtk.MESSAGE_ERROR, "Failed to open file %s"%str(e)) return self.fw_file_path = fw_path state={"init":True, "erase":False, "write":False, "page":0, "buf":buf, "bar":fw_progress, "dialog":dialog, "xfer_bytes":0, "xfer_total":len(buf)} # call dfu-util openmv.enter_dfu() sleep(1.0) gobject.gobject.idle_add(self.fwupdate_task, state) else: dialog.hide() def reset_clicked(self, widget): if (self.connected): openmv.reset() def execute_clicked(self, widget): buf = self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter()) # interrupt any running code openmv.stop_script() sleep(0.1) # exec script openmv.exec_script(buf) def stop_clicked(self, widget): openmv.stop_script(); def zoomin_clicked(self, widget): global SCALE SCALE+=1 def zoomout_clicked(self, widget): global SCALE if SCALE>1: SCALE-=1 def bestfit_clicked(self, widget): global SCALE SCALE=1 def preferences_clicked(self, widget): board_combo = self.builder.get_object("board_combo") sport_combo = self.builder.get_object("sport_combo") dialog = self.builder.get_object("preferences_dialog") # Fill serial ports combo sport_combo.get_model().clear() serial_ports = self.list_serial_ports() for i in serial_ports: sport_combo.append_text(i) if len(serial_ports): sport_combo.set_active(0) # Save config if dialog.run() == gtk.RESPONSE_OK: self.config.set("main", "board", board_combo.get_active_text()) self.config.set("main", "serial_port", sport_combo.get_active_text()) self.save_config() dialog.hide() def updatefb_clicked(self, widget): openmv.fb_update() def button_pressed(self, widget, event): self.x1 = int(event.x) self.y1 = int(event.y) self.x2 = int(event.x) self.y2 = int(event.y) self.selection_started = True def button_released(self, widget, event): self.x2 = int(event.x) self.y2 = int(event.y) self.selection_started = False self.da_menu.popup(None, None, None, event.button, event.time, None) self.da_menu.show_all() def motion_notify(self, widget, event): x = int(event.x) y = int(event.y) self.x2 = int(event.x) self.y2 = int(event.y) if self.pixbuf and x < self.pixbuf.get_width() and y < self.pixbuf.get_height(): pixel = self.pixbuf.get_pixels_array()[y][x] rgb = "(%d, %d, %d)" %(pixel[0], pixel[1], pixel[2]) self.statusbar.pop(self.statusbar_ctx) self.statusbar.push(self.statusbar_ctx, rgb) def scroll_terminal(self, widget, event): adj = self.terminal_scroll.get_vadjustment() adj.set_value(adj.upper - adj.page_size) def update_terminal(self): if (self.serial.readable()): buffer = self.terminal.get_buffer() try: buffer.insert(buffer.get_end_iter(), self.serial.readline()) except: return False return True def update_drawing(self): if (not self.connected): return True try: # read drawingarea fb = openmv.fb_dump() except Exception as e: self.disconnect() self._update_title() return True if fb: # create pixbuf from RGB888 self.pixbuf =gtk.gdk.pixbuf_new_from_data(fb[2], gtk.gdk.COLORSPACE_RGB, False, 8, fb[0], fb[1], fb[0]*3) self.pixbuf = self.pixbuf.scale_simple(fb[0]*SCALE, fb[1]*SCALE, gtk.gdk.INTERP_BILINEAR) self.drawingarea.realize(); cm = self.drawingarea.window.get_colormap() gc = self.drawingarea.window.new_gc(foreground=cm.alloc_color('#FFFFFF',True,False)) self.drawingarea.set_size_request(fb[0]*SCALE, fb[1]*SCALE) self.drawingarea.window.draw_pixbuf(gc, self.pixbuf, 0, 0, 0, 0) if self.selection_started or self.da_menu.flags() & gtk.MAPPED: self.drawingarea.window.draw_rectangle(gc, False, self.x1, self.y1, self.x2-self.x1, self.y2-self.y1) return True def on_ctrl_scale_value_changed(self, adjust): openmv.set_attr(adjust.attr, int(adjust.value)) def save_config(self): # config.set("section", "key", value) self.config.set("main", "recent", ','.join(self.files)) with open(CONFIG_PATH, "w") as file: self.config.write(file) def _update_title(self): if (self.file_path==None): title = "Untitled" else: title = os.path.basename(self.file_path) title += " [Connected]" if self.connected else " [Disconnected]" self.window.set_title(title) def update_recent_files(self): if (self.file_path and self.file_path not in self.files ): self.files.insert(0, self.file_path) if len(self.files)>RECENT_FILES_LIMIT: self.files.pop() submenu = gtk.Menu() menu = self.builder.get_object('recent_menu') for f in self.files: if f.endswith(".py"): mitem =gtk.MenuItem(f) mitem.connect("activate", self.open_example, "") submenu.append(mitem) menu.set_submenu(submenu) menu.show_all() def _load_file(self, path): self.file_path = path if path == None: # New file self.save_button.set_sensitive(True) self.buffer.set_text("") else: self.save_button.set_sensitive(False) with open(path, "r") as file: self.buffer.set_text(file.read()) self.update_recent_files() self._update_title() def _save_file(self, new_file): if new_file: dialog = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(SCRIPTS_DIR) ff = gtk.FileFilter() ff.set_name("python") ff.add_pattern("*.py") dialog.add_filter(ff) if dialog.run() == gtk.RESPONSE_OK: self.file_path = dialog.get_filename() self.save_button.set_sensitive(False) self._update_title() self.update_recent_files() with open(dialog.get_filename(), "w") as file: file.write(self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter())) dialog.destroy() else: self.save_button.set_sensitive(False) with open(self.file_path, "w") as file: file.write(self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter())) def save_template(self, widget): self.da_menu.hide() x = self.x1 y = self.y1 w = self.x2-self.x1 h = self.y2-self.y1 entry = self.builder.get_object("template_entry") image = self.builder.get_object("template_image") image.set_from_pixbuf(self.pixbuf.subpixbuf(x, y, w, h)) dialog = self.builder.get_object("save_template_dialog") dialog.set_transient_for(self.window); #dialog.set_default_response(gtk.RESPONSE_OK) if dialog.run() == gtk.RESPONSE_OK: openmv.save_template(x/SCALE, y/SCALE, w/SCALE, h/SCALE, entry.get_text()) #Use Scale dialog.hide() def save_descriptor(self, widget): self.da_menu.hide() x = self.x1 y = self.y1 w = self.x2-self.x1 h = self.y2-self.y1 entry = self.builder.get_object("desc_entry") image = self.builder.get_object("desc_image") image.set_from_pixbuf(self.pixbuf.subpixbuf(x, y, w, h)) dialog = self.builder.get_object("save_descriptor_dialog") dialog.set_transient_for(self.window); #dialog.set_default_response(gtk.RESPONSE_OK) if dialog.run() == gtk.RESPONSE_OK: #if not entry.get_text(): openmv.save_descriptor(x/SCALE, y/SCALE, w/SCALE, h/SCALE, entry.get_text()) #Use Scale dialog.hide() def new_file(self, widget): self._load_file(None) def save_file(self, widget): self._save_file(self.file_path==None) def save_file_as(self, widget): self._save_file(True) def open_file(self, widget): dialog = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(SCRIPTS_DIR) ff = gtk.FileFilter() ff.set_name("python") ff.add_pattern("*.py") dialog.add_filter(ff) if dialog.run() == gtk.RESPONSE_OK: self._load_file(dialog.get_filename()) dialog.destroy() def open_example(self, widget, basedir): self.file_path = os.path.join(basedir, widget.get_label()) self._load_file(self.file_path) def text_changed(self, widget): self.save_button.set_sensitive(True) def list_serial_ports(self): serial_ports = [] system_name = platform.system() if system_name == "Windows": for i in range(256): try: port = "COM%d"%i s = serial.Serial(port) serial_ports.append(port) s.close() except serial.SerialException: pass else: # Linux/Mac serial_ports.append("/dev/openmvcam") return serial_ports def quit(self, widget): try: # disconnect self.disconnect() except: pass self.save_config() # exit sys.exit(0)
def setCodeText(codeView, str): lang = SyntaxLoader("c") buff = CodeBuffer(lang=lang) codeView.set_buffer(buff) buff.set_text(str) addTags(codeView)
def __init__(self): #Set the Glade file self.builder = gtk.Builder() self.builder.add_from_file(GLADE_PATH) # get top window self.window = self.builder.get_object("top_window") # status bar stuff self.statusbar = self.builder.get_object("statusbar") self.statusbar_ctx = self.statusbar.get_context_id("default") # set buttons self.save_button = self.builder.get_object('save_file_toolbutton') self.connect_button = self.builder.get_object('connect_button') self.save_button.set_sensitive(False) self.connect_button.set_sensitive(True) # set control buttons self.controls = [ self.builder.get_object('reset_button'), self.builder.get_object('bootloader_button'), self.builder.get_object('exec_button'), self.builder.get_object('stop_button'), self.builder.get_object('zoomin_button'), self.builder.get_object('zoomout_button'), self.builder.get_object('bestfit_button'), self.builder.get_object('refresh_button') ] self.connected = False map(lambda x: x.set_sensitive(False), self.controls) # workaround bug in gtkcodebuffer gtkcodebuffer.SYNTAX_PATH.append( os.path.join(sys.prefix, "local", "share", "pygtkcodebuffer", "syntax")) # Configure source viewer self.buffer = CodeBuffer(lang=SyntaxLoader("python")) self.buffer.connect("changed", self.text_changed) tabs = pango.TabArray(1, True) tabs.set_tab(0, pango.TAB_LEFT, 8 * 4) #seems right txtview = gtk.TextView(self.buffer) txtview.set_tabs(tabs) self.builder.get_object("src_scrolledwindow").add(txtview) # Configure terminal window self.terminal_scroll = self.builder.get_object('vte_scrolledwindow') self.terminal = self.builder.get_object('vte_textview') self.terminal.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('black')) self.terminal.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('green')) # get drawingarea self.pixbuf = None self.drawingarea = self.builder.get_object("drawingarea") self.da_menu = self.builder.get_object("da_menu") # selection coords self.sel_ended = False self.selection_started = False self.x1 = self.y1 = self.x2 = self.y2 = 0 # set control scales attributes self.builder.get_object("contrast_adjust").attr = openmv.ATTR_CONTRAST self.builder.get_object( "brightness_adjust").attr = openmv.ATTR_BRIGHTNESS self.builder.get_object( "saturation_adjust").attr = openmv.ATTR_SATURATION self.builder.get_object( "gainceiling_adjust").attr = openmv.ATTR_GAINCEILING #connect signals signals = { "on_top_window_destroy": self.quit, "on_connect_clicked": self.connect_clicked, "on_reset_clicked": self.reset_clicked, "on_fwupdate_clicked": self.fwupdate_clicked, "on_fwpath_clicked": self.fwpath_clicked, "on_execute_clicked": self.execute_clicked, "on_stop_clicked": self.stop_clicked, "on_motion_notify": self.motion_notify, "on_button_press": self.button_pressed, "on_button_release": self.button_released, "on_open_file": self.open_file, "on_new_file": self.new_file, "on_save_file": self.save_file, "on_save_file_as": self.save_file_as, "on_save_template_activate": self.save_template, "on_save_descriptor_activate": self.save_descriptor, "on_ctrl_scale_value_changed": self.on_ctrl_scale_value_changed, "on_zoomin_clicked": self.zoomin_clicked, "on_zoomout_clicked": self.zoomout_clicked, "on_bestfit_clicked": self.bestfit_clicked, "on_preferences_clicked": self.preferences_clicked, "on_updatefb_clicked": self.updatefb_clicked, "on_vte_size_allocate": self.scroll_terminal, } self.builder.connect_signals(signals) # create data directory if not os.path.isdir(DATA_DIR): os.makedirs(DATA_DIR) # create user scripts directory if not os.path.isdir(SCRIPTS_DIR): os.makedirs(SCRIPTS_DIR) # create fresh config if needed if not os.path.isfile(CONFIG_PATH): try: with open(CONFIG_PATH, "w") as f: f.write(DEFAULT_CONFIG) except Exception as e: print("Failed to create config file %s" % (e)) sys.exit(1) # load config self.config = configparser.ConfigParser() try: self.config.read(CONFIG_PATH) except Exception as e: print("Failed to open config file %s" % (e)) sys.exit(1) # current file path self.file_path = None self.fw_file_path = "" # path = self.config.get("main", "last_opened_file") # if os.path.isfile(path): # self._load_file(path) # built-in examples menu submenu = gtk.Menu() menu = self.builder.get_object('example_menu') files = sorted(os.listdir(EXAMPLES_DIR)) for f in files: if f.endswith(".py"): label = os.path.basename(f) mitem = gtk.MenuItem(label) mitem.connect("activate", self.open_example, EXAMPLES_DIR) submenu.append(mitem) menu.set_submenu(submenu) # recent files menu self.files = [] files = self.config.get("main", "recent") if files: self.files = files.split(',') self.update_recent_files()
class OMVGtk: def __init__(self): #Set the Glade file self.builder = gtk.Builder() self.builder.add_from_file(GLADE_PATH) # get top window self.window = self.builder.get_object("top_window") # status bar stuff self.statusbar = self.builder.get_object("statusbar") self.statusbar_ctx = self.statusbar.get_context_id("default") # set buttons self.save_button = self.builder.get_object('save_file_toolbutton') self.connect_button = self.builder.get_object('connect_button') self.save_button.set_sensitive(False) self.connect_button.set_sensitive(True) # set control buttons self.controls = [ self.builder.get_object('reset_button'), self.builder.get_object('bootloader_button'), self.builder.get_object('exec_button'), self.builder.get_object('stop_button'), self.builder.get_object('zoomin_button'), self.builder.get_object('zoomout_button'), self.builder.get_object('bestfit_button'), self.builder.get_object('refresh_button') ] self.connected = False map(lambda x: x.set_sensitive(False), self.controls) # workaround bug in gtkcodebuffer gtkcodebuffer.SYNTAX_PATH.append( os.path.join(sys.prefix, "local", "share", "pygtkcodebuffer", "syntax")) # Configure source viewer self.buffer = CodeBuffer(lang=SyntaxLoader("python")) self.buffer.connect("changed", self.text_changed) tabs = pango.TabArray(1, True) tabs.set_tab(0, pango.TAB_LEFT, 8 * 4) #seems right txtview = gtk.TextView(self.buffer) txtview.set_tabs(tabs) self.builder.get_object("src_scrolledwindow").add(txtview) # Configure terminal window self.terminal_scroll = self.builder.get_object('vte_scrolledwindow') self.terminal = self.builder.get_object('vte_textview') self.terminal.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('black')) self.terminal.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('green')) # get drawingarea self.pixbuf = None self.drawingarea = self.builder.get_object("drawingarea") self.da_menu = self.builder.get_object("da_menu") # selection coords self.sel_ended = False self.selection_started = False self.x1 = self.y1 = self.x2 = self.y2 = 0 # set control scales attributes self.builder.get_object("contrast_adjust").attr = openmv.ATTR_CONTRAST self.builder.get_object( "brightness_adjust").attr = openmv.ATTR_BRIGHTNESS self.builder.get_object( "saturation_adjust").attr = openmv.ATTR_SATURATION self.builder.get_object( "gainceiling_adjust").attr = openmv.ATTR_GAINCEILING #connect signals signals = { "on_top_window_destroy": self.quit, "on_connect_clicked": self.connect_clicked, "on_reset_clicked": self.reset_clicked, "on_fwupdate_clicked": self.fwupdate_clicked, "on_fwpath_clicked": self.fwpath_clicked, "on_execute_clicked": self.execute_clicked, "on_stop_clicked": self.stop_clicked, "on_motion_notify": self.motion_notify, "on_button_press": self.button_pressed, "on_button_release": self.button_released, "on_open_file": self.open_file, "on_new_file": self.new_file, "on_save_file": self.save_file, "on_save_file_as": self.save_file_as, "on_save_template_activate": self.save_template, "on_save_descriptor_activate": self.save_descriptor, "on_ctrl_scale_value_changed": self.on_ctrl_scale_value_changed, "on_zoomin_clicked": self.zoomin_clicked, "on_zoomout_clicked": self.zoomout_clicked, "on_bestfit_clicked": self.bestfit_clicked, "on_preferences_clicked": self.preferences_clicked, "on_updatefb_clicked": self.updatefb_clicked, "on_vte_size_allocate": self.scroll_terminal, } self.builder.connect_signals(signals) # create data directory if not os.path.isdir(DATA_DIR): os.makedirs(DATA_DIR) # create user scripts directory if not os.path.isdir(SCRIPTS_DIR): os.makedirs(SCRIPTS_DIR) # create fresh config if needed if not os.path.isfile(CONFIG_PATH): try: with open(CONFIG_PATH, "w") as f: f.write(DEFAULT_CONFIG) except Exception as e: print("Failed to create config file %s" % (e)) sys.exit(1) # load config self.config = configparser.ConfigParser() try: self.config.read(CONFIG_PATH) except Exception as e: print("Failed to open config file %s" % (e)) sys.exit(1) # current file path self.file_path = None self.fw_file_path = "" # path = self.config.get("main", "last_opened_file") # if os.path.isfile(path): # self._load_file(path) # built-in examples menu submenu = gtk.Menu() menu = self.builder.get_object('example_menu') files = sorted(os.listdir(EXAMPLES_DIR)) for f in files: if f.endswith(".py"): label = os.path.basename(f) mitem = gtk.MenuItem(label) mitem.connect("activate", self.open_example, EXAMPLES_DIR) submenu.append(mitem) menu.set_submenu(submenu) # recent files menu self.files = [] files = self.config.get("main", "recent") if files: self.files = files.split(',') self.update_recent_files() def show_message_dialog(self, msg_type, msg): message = gtk.MessageDialog(parent=self.window, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=msg_type, buttons=gtk.BUTTONS_OK, message_format=msg) message.run() message.destroy() def refresh_gui(self, delay=0.0001, wait=0.0001): sleep(delay) gtk.main_iteration_do(block=False) sleep(wait) def connect(self): try: # open VCP and configure the terminal self.serial = serial.Serial(self.config.get("main", "serial_port"), 12000000, timeout=0.1) gobject.gobject.idle_add(omvgtk.update_terminal) except Exception as e: self.show_message_dialog( gtk.MESSAGE_ERROR, "Failed to open serial port (check prefernces)\n%s" % e) return openmv.init(self.serial) # interrupt any running code openmv.stop_script() self.connected = True self._update_title() self.connect_button.set_sensitive(False) map(lambda x: x.set_sensitive(True), self.controls) def disconnect(self): try: # stop running code openmv.stop_script() except: pass self.serial.close() self.connected = False self._update_title() self.connect_button.set_sensitive(True) map(lambda x: x.set_sensitive(False), self.controls) def connect_clicked(self, widget): self.connect() def fwpath_clicked(self, widget): fw_entry = self.builder.get_object("fw_entry") dialog = gtk.FileChooserDialog( title=None, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(SCRIPTS_DIR) ff = gtk.FileFilter() ff.set_name("dfu") ff.add_pattern("*.bin") #TODO change to DFU dialog.add_filter(ff) if dialog.run() == gtk.RESPONSE_OK: fw_entry.set_text(dialog.get_filename()) dialog.destroy() # Fake multitasking :P def fwupdate_task(self, state): if (state["init"]): pydfu.init() state["init"] = False state["erase"] = True state["bar"].set_text("Erasing...") return True elif (state["erase"]): page = state["page"] total = len(FLASH_OFFSETS) pydfu.page_erase(FLASH_OFFSETS[page]) page += 1 state["bar"].set_fraction(page / float(total)) if (page == total): state["erase"] = False state["write"] = True state["bar"].set_text("Uploading...") state["page"] = page return True elif (state["write"]): buf = state["buf"] xfer_bytes = state["xfer_bytes"] xfer_total = state["xfer_total"] # Send chunk chunk = min(64, xfer_total - xfer_bytes) pydfu.write_page(buf[xfer_bytes:xfer_bytes + chunk], xfer_bytes) xfer_bytes += chunk state["xfer_bytes"] = xfer_bytes state["bar"].set_fraction(xfer_bytes / float(xfer_total)) if (xfer_bytes == xfer_total): pydfu.exit_dfu() state["dialog"].hide() return False return True def fwupdate_clicked(self, widget): if (self.connected): dialog = self.builder.get_object("fw_dialog") fw_entry = self.builder.get_object("fw_entry") fw_progress = self.builder.get_object("fw_progressbar") ok_button = self.builder.get_object("fw_ok_button") cancel_button = self.builder.get_object("fw_cancel_button") ok_button.set_sensitive(True) cancel_button.set_sensitive(True) dialog.set_transient_for(self.window) # default FW bin path fw_entry.set_text(self.fw_file_path) fw_progress.set_text("") fw_progress.set_fraction(0.0) if dialog.run() == gtk.RESPONSE_OK: ok_button.set_sensitive(False) cancel_button.set_sensitive(False) fw_path = fw_entry.get_text() try: with open(fw_path, 'r') as f: buf = f.read() except Exception as e: dialog.hide() self.show_message_dialog(gtk.MESSAGE_ERROR, "Failed to open file %s" % str(e)) return self.fw_file_path = fw_path state = { "init": True, "erase": False, "write": False, "page": 0, "buf": buf, "bar": fw_progress, "dialog": dialog, "xfer_bytes": 0, "xfer_total": len(buf) } # call dfu-util openmv.enter_dfu() sleep(1.0) gobject.gobject.idle_add(self.fwupdate_task, state) else: dialog.hide() def reset_clicked(self, widget): if (self.connected): openmv.reset() def execute_clicked(self, widget): buf = self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter()) # interrupt any running code openmv.stop_script() sleep(0.1) # exec script openmv.exec_script(buf) def stop_clicked(self, widget): openmv.stop_script() def zoomin_clicked(self, widget): global SCALE SCALE += 1 def zoomout_clicked(self, widget): global SCALE if SCALE > 1: SCALE -= 1 def bestfit_clicked(self, widget): global SCALE SCALE = 1 def preferences_clicked(self, widget): board_combo = self.builder.get_object("board_combo") sport_combo = self.builder.get_object("sport_combo") dialog = self.builder.get_object("preferences_dialog") # Fill serial ports combo sport_combo.get_model().clear() serial_ports = self.list_serial_ports() for i in serial_ports: sport_combo.append_text(i) if len(serial_ports): sport_combo.set_active(0) # Save config if dialog.run() == gtk.RESPONSE_OK: self.config.set("main", "board", board_combo.get_active_text()) self.config.set("main", "serial_port", sport_combo.get_active_text()) self.save_config() dialog.hide() def updatefb_clicked(self, widget): openmv.fb_update() def button_pressed(self, widget, event): self.x1 = int(event.x) self.y1 = int(event.y) self.x2 = int(event.x) self.y2 = int(event.y) self.selection_started = True def button_released(self, widget, event): self.x2 = int(event.x) self.y2 = int(event.y) self.selection_started = False self.da_menu.popup(None, None, None, event.button, event.time, None) self.da_menu.show_all() def motion_notify(self, widget, event): x = int(event.x) y = int(event.y) self.x2 = int(event.x) self.y2 = int(event.y) if self.pixbuf and x < self.pixbuf.get_width( ) and y < self.pixbuf.get_height(): pixel = self.pixbuf.get_pixels_array()[y][x] rgb = "(%d, %d, %d)" % (pixel[0], pixel[1], pixel[2]) self.statusbar.pop(self.statusbar_ctx) self.statusbar.push(self.statusbar_ctx, rgb) def scroll_terminal(self, widget, event): adj = self.terminal_scroll.get_vadjustment() adj.set_value(adj.upper - adj.page_size) def update_terminal(self): buf_len = openmv.tx_buf_len() buf = openmv.tx_buf(buf_len) buffer = self.terminal.get_buffer() try: buffer.insert(buffer.get_end_iter(), buf) except: return False return True def update_drawing(self): if (not self.connected): return True try: # read drawingarea fb = openmv.fb_dump() except Exception as e: self.disconnect() self._update_title() return True if fb: # create pixbuf from RGB888 self.pixbuf = gtk.gdk.pixbuf_new_from_data(fb[2], gtk.gdk.COLORSPACE_RGB, False, 8, fb[0], fb[1], fb[0] * 3) self.pixbuf = self.pixbuf.scale_simple(fb[0] * SCALE, fb[1] * SCALE, gtk.gdk.INTERP_BILINEAR) self.drawingarea.realize() cm = self.drawingarea.window.get_colormap() gc = self.drawingarea.window.new_gc( foreground=cm.alloc_color('#FFFFFF', True, False)) self.drawingarea.set_size_request(fb[0] * SCALE, fb[1] * SCALE) self.drawingarea.window.draw_pixbuf(gc, self.pixbuf, 0, 0, 0, 0) if self.selection_started or self.da_menu.flags() & gtk.MAPPED: self.drawingarea.window.draw_rectangle(gc, False, self.x1, self.y1, self.x2 - self.x1, self.y2 - self.y1) return True def on_ctrl_scale_value_changed(self, adjust): openmv.set_attr(adjust.attr, int(adjust.value)) def save_config(self): # config.set("section", "key", value) self.config.set("main", "recent", ','.join(self.files)) with open(CONFIG_PATH, "w") as file: self.config.write(file) def _update_title(self): if (self.file_path == None): title = "Untitled" else: title = os.path.basename(self.file_path) title += " [Connected]" if self.connected else " [Disconnected]" self.window.set_title(title) def update_recent_files(self): if (self.file_path and self.file_path not in self.files): self.files.insert(0, self.file_path) if len(self.files) > RECENT_FILES_LIMIT: self.files.pop() submenu = gtk.Menu() menu = self.builder.get_object('recent_menu') for f in self.files: if f.endswith(".py"): mitem = gtk.MenuItem(f) mitem.connect("activate", self.open_example, "") submenu.append(mitem) menu.set_submenu(submenu) menu.show_all() def _load_file(self, path): self.file_path = path if path == None: # New file self.save_button.set_sensitive(True) self.buffer.set_text("") else: self.save_button.set_sensitive(False) with open(path, "r") as file: self.buffer.set_text(file.read()) self.update_recent_files() self._update_title() def _save_file(self, new_file): if new_file: dialog = gtk.FileChooserDialog( title=None, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(SCRIPTS_DIR) ff = gtk.FileFilter() ff.set_name("python") ff.add_pattern("*.py") dialog.add_filter(ff) if dialog.run() == gtk.RESPONSE_OK: self.file_path = dialog.get_filename() self.save_button.set_sensitive(False) self._update_title() self.update_recent_files() with open(dialog.get_filename(), "w") as file: file.write( self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter())) dialog.destroy() else: self.save_button.set_sensitive(False) with open(self.file_path, "w") as file: file.write( self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter())) def save_template(self, widget): self.da_menu.hide() x = self.x1 y = self.y1 w = self.x2 - self.x1 h = self.y2 - self.y1 entry = self.builder.get_object("template_entry") image = self.builder.get_object("template_image") image.set_from_pixbuf(self.pixbuf.subpixbuf(x, y, w, h)) dialog = self.builder.get_object("save_template_dialog") dialog.set_transient_for(self.window) #dialog.set_default_response(gtk.RESPONSE_OK) if dialog.run() == gtk.RESPONSE_OK: openmv.save_template(x / SCALE, y / SCALE, w / SCALE, h / SCALE, entry.get_text()) #Use Scale dialog.hide() def save_descriptor(self, widget): self.da_menu.hide() x = self.x1 y = self.y1 w = self.x2 - self.x1 h = self.y2 - self.y1 entry = self.builder.get_object("desc_entry") image = self.builder.get_object("desc_image") image.set_from_pixbuf(self.pixbuf.subpixbuf(x, y, w, h)) dialog = self.builder.get_object("save_descriptor_dialog") dialog.set_transient_for(self.window) #dialog.set_default_response(gtk.RESPONSE_OK) if dialog.run() == gtk.RESPONSE_OK: #if not entry.get_text(): openmv.save_descriptor(x / SCALE, y / SCALE, w / SCALE, h / SCALE, entry.get_text()) #Use Scale dialog.hide() def new_file(self, widget): self._load_file(None) def save_file(self, widget): self._save_file(self.file_path == None) def save_file_as(self, widget): self._save_file(True) def open_file(self, widget): dialog = gtk.FileChooserDialog( title=None, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(SCRIPTS_DIR) ff = gtk.FileFilter() ff.set_name("python") ff.add_pattern("*.py") dialog.add_filter(ff) if dialog.run() == gtk.RESPONSE_OK: self._load_file(dialog.get_filename()) dialog.destroy() def open_example(self, widget, basedir): self.file_path = os.path.join(basedir, widget.get_label()) self._load_file(self.file_path) def text_changed(self, widget): self.save_button.set_sensitive(True) def list_serial_ports(self): serial_ports = [] system_name = platform.system() if system_name == "Windows": for i in range(256): try: port = "COM%d" % i s = serial.Serial(port) serial_ports.append(port) s.close() except serial.SerialException: pass else: # Linux/Mac serial_ports.append("/dev/openmvcam") return serial_ports def quit(self, widget): try: # disconnect self.disconnect() except: pass self.save_config() # exit sys.exit(0)
#!/usr/bin/python import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader, add_syntax_path # # This example shows how to use the CodeBuffer. # Note: You need to have PyGTKCodeBuffer installed! txt = """fsd sdfsd sdfsd is fsdfdf""" lang = SyntaxLoader("pascal") buff = CodeBuffer(lang=lang) win = gtk.Window(gtk.WINDOW_TOPLEVEL) scr = gtk.ScrolledWindow() win.add(scr) scr.add(gtk.TextView(buff)) win.set_default_size(300,200) win.show_all() win.connect("destroy", lambda w: gtk.main_quit()) buff.set_text(txt) gtk.main()
#!/usr/bin/python import gtk import sys # comment-out if CodeBuffer is installed sys.path.insert(0, "..") from gtkcodebuffer import CodeBuffer, SyntaxLoader, add_syntax_path # comment-out if CodeBuffer is installed add_syntax_path("../syntax") lang = SyntaxLoader("python") buff = CodeBuffer(lang=lang) win = gtk.Window(gtk.WINDOW_TOPLEVEL) scr = gtk.ScrolledWindow() win.add(scr) scr.add(gtk.TextView(buff)) win.set_default_size(300,200) win.show_all() win.connect("destroy", lambda w: gtk.main_quit()) buff.set_text(open(__file__,'r').read()) gtk.main()
def __init__(self,assembly,entity): super(PropertyWindow,self).__init__() self.set_size_request(500, 400) self.set_position(gtk.WIN_POS_CENTER) # Remove this property window from the static store self.connect("destroy", self.on_destroy) # Store data structures self.assembly = assembly self.entity = entity self.set_title(str(self.entity)) ######################################### vpaned = gtk.VPaned() vbox = gtk.VBox(False, 8) sw = gtk.ScrolledWindow() sw.set_shadow_type(gtk.SHADOW_ETCHED_IN) sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) vbox.pack_start(sw, True, True, 0) store = self.create_model() treeView = gtk.TreeView(store) treeView.connect("row-activated", self.on_activated) treeView.set_rules_hint(True) sw.add(treeView) self.create_columns(treeView) ################################################### ################################################### if assembly.rule_src.has_key(self.entity.name): rule_name = self.entity.name # Create the syntax hilighter and code buffer lang = SyntaxLoader("cpp") buff = CodeBuffer(lang=lang) hbox = gtk.HBox(False, 8) scr = gtk.ScrolledWindow() scr.add(gtk.TextView(buff)) scr.set_shadow_type(gtk.SHADOW_ETCHED_IN) scr.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) # Get the source file path, and start line src_path = assembly.rule_src[rule_name][0] src_line_start = int(assembly.rule_src[rule_name][1])-1 # Open the source file src_file = open(src_path,'r') src_file_lines = src_file.readlines() src_line_end = len(src_file_lines) # Find the line on which the next rule is defined for line in range(src_line_start+1,len(src_file_lines)): if src_file_lines[line].find("::") != -1: src_line_end = line; break # Display the source code of just this rule srccode = "".join(src_file_lines[src_line_start:src_line_end]) buff.set_text(srccode) hbox.pack_start(scr, True, True, 0) vbox.pack_start(hbox, True, True, 0) ################################################## self.statusbar = gtk.Statusbar() vbox.pack_start(self.statusbar, False, False, 0) self.add(vbox) self.show_all()
#!/usr/bin/python import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader, add_syntax_path # # This example shows how to use the CodeBuffer. # Note: You need to have PyGTKCodeBuffer installed! txt = """fsd sdfsd sdfsd is fsdfdf""" lang = SyntaxLoader("pascal") buff = CodeBuffer(lang=lang) win = gtk.Window(gtk.WINDOW_TOPLEVEL) scr = gtk.ScrolledWindow() win.add(scr) scr.add(gtk.TextView(buff)) win.set_default_size(300, 200) win.show_all() win.connect("destroy", lambda w: gtk.main_quit()) buff.set_text(txt) gtk.main()
def __init__(self, obj, name, notebook): self.notebook = notebook self.obj = obj self.name = name # vpane self.page = gtk.HPaned() # left view, navigation left_view = gtk.VBox() nav_frame = gtk.Frame('Navigation') self.treeview = gtk.TreeView() self.treeview.connect("cursor-changed", self.on_cursor_changed) self.treeview.connect("row-activated", self.on_row_activated) self.treeview.set_headers_visible(False) self.treeview.set_enable_tree_lines(True) col_name = gtk.TreeViewColumn('Name', gtk.CellRendererText(), markup=0) self.treeview.append_column(col_name) scrolledwindow = gtk.ScrolledWindow() scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scrolledwindow.add_with_viewport(self.treeview) nav_frame.add(scrolledwindow) left_view.pack_start(nav_frame, True, True) np_frame = gtk.Frame('Navigation path') self.path_label = gtk.Entry() self.path_label.set_editable(False) np_frame.add(self.path_label) left_view.pack_start(np_frame, False, False) no_frame = gtk.Frame('Navigation options') no_hbox = gtk.HBox() self.b_hide_builtin = gtk.CheckButton(label='Hide Builtin') self.b_hide_builtin.set_active(True) self.b_hide_builtin.connect("clicked", self.on_button_hide_builtin_toggle) no_hbox.pack_start(self.b_hide_builtin, False, False) b_refresh = gtk.Button(label='Refresh') b_refresh.connect("clicked", self.on_button_refresh_click) no_hbox.pack_end(b_refresh, False, False) no_frame.add(no_hbox) left_view.pack_end(no_frame, expand=False, fill=False, padding=5) self.page.add1(left_view) # Right view (sources) right_view = gtk.VBox() sd_frame = gtk.Frame('Definition') self.source_def = gtk.Entry() self.source_def.set_editable(False) sd_frame.add(self.source_def) right_view.pack_start(sd_frame, False, False) source_frame = gtk.Frame('Source code') source_scroll = gtk.ScrolledWindow() source_scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) lang = python_lang.lang self.source_content = CodeBuffer(lang=lang) source_tv = gtk.TextView(self.source_content) source_tv.set_editable(False) source_scroll.add_with_viewport(source_tv) source_frame.add(source_scroll) right_view.pack_start(source_frame, True, True) sfp_frame = gtk.Frame('Source file path') self.source_file = gtk.Entry() self.source_file.set_editable(False) sfp_frame.add(self.source_file) right_view.pack_start(sfp_frame, False, False) self.page.add2(right_view) self.tree_model = model.ObjectModel(self.obj, self.name, self.b_hide_builtin.get_active()) self.treeview.set_model(self.tree_model) self.page.show_all() # Notebook tab Label control nbt_view = gtk.HBox() nbt_label = gtk.Label(name) nbt_view.pack_start(nbt_label, False, False) #nbt_close_btn = gtk.Button('x') image_close = gtk.Image() nbt_close_btn = gtk.Button() nbt_close_btn.set_relief(gtk.RELIEF_NONE) nbt_close_btn.set_focus_on_click(False) nbt_close_btn.set_tooltip_text("Close Tab") image_close.set_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU) #nbt_close_btn.get_settings() nbt_close_btn.add(image_close) nbt_close_btn.connect("style-set", self.on_style_set) #set_relief(button,gtk.RELIEF_NONE) #nbt_close_btn = gtk.Button(None, gtk.STOCK_CLOSE) nbt_close_btn.connect("clicked", self.on_close_btn_clicked) nbt_view.pack_end(nbt_close_btn, False, False) nbt_view.show_all() notebook.append_page(self.page, nbt_view) notebook.set_tab_reorderable(self.page, True) self.check_show_tab()
class DebugView(object): def __init__(self, obj, name, notebook): self.notebook = notebook self.obj = obj self.name = name # vpane self.page = gtk.HPaned() # left view, navigation left_view = gtk.VBox() nav_frame = gtk.Frame('Navigation') self.treeview = gtk.TreeView() self.treeview.connect("cursor-changed", self.on_cursor_changed) self.treeview.connect("row-activated", self.on_row_activated) self.treeview.set_headers_visible(False) self.treeview.set_enable_tree_lines(True) col_name = gtk.TreeViewColumn('Name', gtk.CellRendererText(), markup=0) self.treeview.append_column(col_name) scrolledwindow = gtk.ScrolledWindow() scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scrolledwindow.add_with_viewport(self.treeview) nav_frame.add(scrolledwindow) left_view.pack_start(nav_frame, True, True) np_frame = gtk.Frame('Navigation path') self.path_label = gtk.Entry() self.path_label.set_editable(False) np_frame.add(self.path_label) left_view.pack_start(np_frame, False, False) no_frame = gtk.Frame('Navigation options') no_hbox = gtk.HBox() self.b_hide_builtin = gtk.CheckButton(label='Hide Builtin') self.b_hide_builtin.set_active(True) self.b_hide_builtin.connect("clicked", self.on_button_hide_builtin_toggle) no_hbox.pack_start(self.b_hide_builtin, False, False) b_refresh = gtk.Button(label='Refresh') b_refresh.connect("clicked", self.on_button_refresh_click) no_hbox.pack_end(b_refresh, False, False) no_frame.add(no_hbox) left_view.pack_end(no_frame, expand=False, fill=False, padding=5) self.page.add1(left_view) # Right view (sources) right_view = gtk.VBox() sd_frame = gtk.Frame('Definition') self.source_def = gtk.Entry() self.source_def.set_editable(False) sd_frame.add(self.source_def) right_view.pack_start(sd_frame, False, False) source_frame = gtk.Frame('Source code') source_scroll = gtk.ScrolledWindow() source_scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) lang = python_lang.lang self.source_content = CodeBuffer(lang=lang) source_tv = gtk.TextView(self.source_content) source_tv.set_editable(False) source_scroll.add_with_viewport(source_tv) source_frame.add(source_scroll) right_view.pack_start(source_frame, True, True) sfp_frame = gtk.Frame('Source file path') self.source_file = gtk.Entry() self.source_file.set_editable(False) sfp_frame.add(self.source_file) right_view.pack_start(sfp_frame, False, False) self.page.add2(right_view) self.tree_model = model.ObjectModel(self.obj, self.name, self.b_hide_builtin.get_active()) self.treeview.set_model(self.tree_model) self.page.show_all() # Notebook tab Label control nbt_view = gtk.HBox() nbt_label = gtk.Label(name) nbt_view.pack_start(nbt_label, False, False) #nbt_close_btn = gtk.Button('x') image_close = gtk.Image() nbt_close_btn = gtk.Button() nbt_close_btn.set_relief(gtk.RELIEF_NONE) nbt_close_btn.set_focus_on_click(False) nbt_close_btn.set_tooltip_text("Close Tab") image_close.set_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU) #nbt_close_btn.get_settings() nbt_close_btn.add(image_close) nbt_close_btn.connect("style-set", self.on_style_set) #set_relief(button,gtk.RELIEF_NONE) #nbt_close_btn = gtk.Button(None, gtk.STOCK_CLOSE) nbt_close_btn.connect("clicked", self.on_close_btn_clicked) nbt_view.pack_end(nbt_close_btn, False, False) nbt_view.show_all() notebook.append_page(self.page, nbt_view) notebook.set_tab_reorderable(self.page, True) self.check_show_tab() def on_style_set(self, widget, prevstyle): settings = widget.get_settings() x, y = gtk.icon_size_lookup_for_settings(settings, gtk.ICON_SIZE_MENU) widget.set_size_request(x + 2, y + 2) def on_button_refresh_click(self, widget, data=None): self.tree_model = model.ObjectModel(self.obj, self.name, self.b_hide_builtin.get_active()) self.treeview.set_model(self.tree_model) self.update_path_label((0, )) def on_button_hide_builtin_toggle(self, widget, data=None): self.tree_model.set_hide_builtin(widget.get_active()) def on_cursor_changed(self, treeview): path, column = treeview.get_cursor() self.update_path_label(path) iter = self.tree_model.iters[self.tree_model.on_get_iter(path)] self.update_source(iter.obj, iter.name) def on_row_activated(self, treeview, path, view_column): # Open a new tab with the selected object iter = self.tree_model.iters[self.tree_model.on_get_iter(path)] DebugView(iter.obj, iter.name, self.notebook) def on_close_btn_clicked(self, button): self.notebook.remove_page(self.notebook.page_num(self.page)) self.check_show_tab() del self # Hara-kiri def check_show_tab(self): self.notebook.set_show_tabs(self.notebook.get_n_pages() > 1) def update_path_label(self, path): path_txt = self.tree_model.get_path_txt(path) self.path_label.set_text(path_txt) def update_source(self, obj, name): self.source_def.set_text(source.get_def(obj, name)) self.source_content.set_text(source.get_source(obj)) self.source_file.set_text(source.get_path(obj))
def __init__(self, dbase, register, bit_field, modified, top_builder): self.__db = dbase self.__modified = modified self.__register = register self.__bit_field = bit_field self.__builder = gtk.Builder() self.__top_builder = top_builder self.__builder.add_from_file(GLADE_BIT) self.__top_window = self.__builder.get_object("editfield") self.__control_obj = self.__builder.get_object('control') self.__name_obj = self.__builder.get_object("field_name") self.__register_obj = self.__builder.get_object("register_name") self.__output_obj = self.__builder.get_object("output") self.__type_obj = self.__builder.get_object('type') self.__input_obj = self.__builder.get_object("input") self.__reset_obj = self.__builder.get_object("reset_value") self.__static_obj = self.__builder.get_object('static') self.__text_buffer = self.__builder.get_object("descr").get_buffer() self.__value_tree_obj = self.__builder.get_object('values') self.__output_enable_obj = self.__builder.get_object("outen") self.__side_effect_obj = self.__builder.get_object("side_effect") self.__verilog_obj = self.__builder.get_object('verilog_code') self.__volatile_obj = self.__builder.get_object('volatile') self.__col = None self.__top_window.set_title( "Edit Bit Field - [%02x] %s" % (register.address, register.register_name)) self.__spell = Spell(self.__builder.get_object("descr")) self.__top_window.set_icon_from_file( os.path.join(INSTALL_PATH, "media", "flop.svg")) (input_enb, control_enb) = TYPE_TO_ENABLE[bit_field.field_type] self.__input_obj.set_sensitive(input_enb) self.__control_obj.set_sensitive(control_enb) pango_font = pango.FontDescription("monospace") self.__builder.get_object("descr").modify_font(pango_font) self.build_values_list() self.__list_model = gtk.ListStore(str, str, str) self.__model_selection = self.__value_tree_obj.get_selection() self.__value_tree_obj.set_model(self.__list_model) self.__used_tokens = set() for value in self.__bit_field.values: self.__used_tokens.add(value[1]) self.__list_model.append(row=value) self.__initialize_from_data(bit_field) self.__output_obj.set_sensitive(self.__output_enable_obj.get_active()) self.__check_data() self.__text_buffer.connect('changed', self.__description_changed) try: edge = "posedge" if self.__db.reset_active_level else "negedge" condition = "" if self.__db.reset_active_level else "~" be_level = "" if self.__db.byte_strobe_active_level else "~" name_map = {'MODULE': self.__db.module_name, 'BE_LEVEL': be_level, 'RESET_CONDITION': condition, 'RESET_EDGE': edge } text = REG[TYPE_TO_ID[bit_field.field_type].lower()] % name_map except KeyError: text = "" if USE_HIGHLIGHT: buff = CodeBuffer(lang=SyntaxLoader("verilog")) self.__verilog_obj.set_buffer(buff) else: self.__verilog_obj.modify_font(pango_font) buff = self.__verilog_obj.get_buffer() buff.set_text(text) self.__builder.connect_signals(self) self.__top_window.show_all()
'underline': pango.UNDERLINE_DOUBLE } } # Syntax definition emph = String(r"\*", r"\*", style="comment") emph2 = String(r"\*\*", r"\*\*", style="bold") code = String(r'`', r'`', style="special") head = Pattern(r"^#+.+$", style="heading") list1 = Pattern(r"^(- ).+$", style="comment", group=1) list2 = Pattern(r"^(\d+\. ).+$", style="comment", group=1) # create lexer: lang = LanguageDefinition([emph, emph2, code, head, list1, list2]) # create buffer and update style-definition buff = CodeBuffer(lang=lang, styles=styles) win = gtk.Window(gtk.WINDOW_TOPLEVEL) scr = gtk.ScrolledWindow() win.add(scr) scr.add(gtk.TextView(buff)) win.set_default_size(300, 200) win.show_all() win.connect("destroy", lambda w: gtk.main_quit()) buff.set_text(txt) gtk.main()
#!/usr/bin/python import gtk import sys # comment-out if CodeBuffer is installed sys.path.insert(0, "..") from gtkcodebuffer import CodeBuffer, SyntaxLoader, add_syntax_path # comment-out if CodeBuffer is installed add_syntax_path("../syntax") lang = SyntaxLoader("python") buff = CodeBuffer(lang=lang) win = gtk.Window(gtk.WINDOW_TOPLEVEL) scr = gtk.ScrolledWindow() win.add(scr) scr.add(gtk.TextView(buff)) win.set_default_size(300, 200) win.show_all() win.connect("destroy", lambda w: gtk.main_quit()) buff.set_text(open(__file__, 'r').read()) gtk.main()