def __init__(self, main): self.main = main #debug(self.main.ttyport,self.main.team) builder = Gtk.Builder() #builder.add_from_file("/home/alex/ips/glade_gui/daedalus.glade") builder.add_from_file(os.path.join(dir, 'daedalus.glade')) builder.connect_signals(eventhandler.EventHandler(self.main)) window = builder.get_object("window2") self.ttybox = builder.get_object("buttonbox4") self.teambox = builder.get_object("buttonbox5") reloadbtn = builder.get_object("button12") reloadbtn.connect("pressed", self.reloadtty) self.reloadtty("") #add your team here DONE button1 = Gtk.RadioButton(group=None, label="Team Blowfish") button1.connect("toggled", self.setteam, "TeamBlowfish") self.teambox.pack_start(button1, True, True, 0) self.main.team = "TeamBlowfish" button = Gtk.RadioButton(group=button1, label="Alex") button.connect("toggled", self.setteam, "TeamX") self.teambox.pack_start(button, True, True, 0) #button = Gtk.RadioButton(group=button1, label="Team1") #button.connect("toggled", self.setteam, "Team1") #self.teambox.pack_start(button, True, True, 0) button = Gtk.RadioButton(group=button1, label="Team2") button.connect("toggled", self.setteam, "Team2") self.teambox.pack_start(button, True, True, 0) button = Gtk.RadioButton(group=button1, label="Team3") button.connect("toggled", self.setteam, "Team3") self.teambox.pack_start(button, True, True, 0) # end: add team window.show_all() #startet das init-Fenster Gtk.main()
def start(self, bridge): """Start the UI event loop.""" bridge.attach(80, 24, True) drawing_area = Gtk.DrawingArea() drawing_area.connect('draw', self._gtk_draw) window = Gtk.Window() window.add(drawing_area) window.set_events(window.get_events() | Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.SCROLL_MASK) window.connect('configure-event', self._gtk_configure) window.connect('delete-event', self._gtk_quit) window.connect('key-press-event', self._gtk_key) window.connect('key-release-event', self._gtk_key_release) window.connect('button-press-event', self._gtk_button_press) window.connect('button-release-event', self._gtk_button_release) window.connect('motion-notify-event', self._gtk_motion_notify) window.connect('scroll-event', self._gtk_scroll) window.connect('focus-in-event', self._gtk_focus_in) window.connect('focus-out-event', self._gtk_focus_out) window.show_all() im_context = Gtk.IMMulticontext() im_context.set_client_window(drawing_area.get_window()) im_context.set_use_preedit(False) # TODO: preedit at cursor position im_context.connect('commit', self._gtk_input) self._pango_context = drawing_area.create_pango_context() self._drawing_area = drawing_area self._window = window self._im_context = im_context self._bridge = bridge Gtk.main()
def main(self): log.LOG("START main") "Run main loop" gtk.main() log.LOG("END main")
def __init__(self): window = Gtk.Window() window.set_title('Random Name Generator') window.set_default_size(180, -1) window.set_border_width(16) window.set_resizable(False) window.connect('destroy', self.on_window_destroy) vbox = Gtk.VBox(homogeneous=False, spacing=16) window.add(vbox) title_label = Gtk.Label('Random Name Generator') vbox.pack_start(title_label, False, False, 0) combobox = Gtk.ComboBoxText.new() name_type = [ 'Inn/Tavern Name', 'Male Character Name', 'Female Character Name' ] for string in name_type: combobox.append_text(string) combobox.set_active(0) vbox.pack_start(combobox, False, False, 0) entry = Gtk.Entry() entry.set_editable('False') entry.set_alignment(0.5) vbox.pack_start(entry, False, False, 0) button = Gtk.Button(label='Generate') button.connect('clicked', self.on_button_clicked, entry, combobox) vbox.pack_start(button, False, False, 0) window.show_all() Gtk.main()
def main(self): tdbglobal.tdblogdebug("start gtk main loop") self.window.connect("delete-event", Gtk.main_quit) self.host = self.builder.get_object("e_main_db") self.host.set_text(config.SERVERNAME) self.window.show() Gtk.main()
def main(): for opt in sys.argv[1:]: if opt in ('-h', '--help'): usage() sys.exit() elif opt in ('-d', '--dev'): config.ENABLE_INSPECTOR = True else: print "hotot: unrecognized option '%s'" % opt usage() sys.exit(1) try: import i18n except: from gettext import gettext as _ try: import prctl prctl.set_name('hotot') except: pass GObject.threads_init() config.loads(); agent.init_notify() app = Hotot() agent.app = app Gdk.threads_enter() Gtk.main() Gdk.threads_leave()
def run(server_list, random, default=False): """Run""" window = GraphicalUI(server_list, random, default) window.connect("delete-event", Gtk.main_quit) window.show_all() Gtk.main() return window
def on_botonVer_clicked(self, widget): ''' Evento del boton Ver para mostrar los datos del evento. Llama a la clase Evento que crea una ventana con las tablas de la BD ''' ventanaEvento = vEvento.Evento() ventanaEvento.connect("delete-event", Gtk.main_quit) ventanaEvento.show_all() Gtk.main()
def main(): win = ScrolledInfoBarDemoWindow() win.set_size_request(600, 300) win.set_position(Gtk.WindowPosition.MOUSE) win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
def run(screen_name): window = Gtk.Window() window.connect('destroy', Gtk.main_quit) window.set_size_request(800, 500) window.set_border_width(12) window.set_title("Cnchi - Test of %s screen" % screen_name) import config settings = config.Settings() settings.set('data', '/usr/share/cnchi/data') from desktop_environments import DESKTOPS settings.set('desktops', DESKTOPS) settings.set('language_code', 'ca') params = {} params['title'] = "Cnchi" params['ui_dir'] = "/usr/share/cnchi/ui" params['disable_tryit'] = False params['settings'] = settings params['forward_button'] = Gtk.Button.new() params['backwards_button'] = Gtk.Button.new() params['main_progressbar'] = Gtk.ProgressBar.new() params['header'] = Gtk.HeaderBar.new() params['testing'] = True params['callback_queue'] = None params['alternate_package_list'] = "" screen = get_screen(screen_name, params) if screen != None: screen.prepare('forward') window.add(screen) window.show_all() Gtk.main() else: print("Unknown screen")
def _runSpoke(self, action): from gi.repository import Gtk # This duplicates code in widgets/src/BaseWindow.c, but we want to make sure # maximize gets called every time a spoke is displayed to prevent the 25% # UI from showing up. action.window.maximize() action.window.set_property("expand", True) action.refresh() action.window.set_beta(self.window.get_beta()) action.window.set_property("distribution", distributionText().upper()) action.window.set_transient_for(self.window) action.window.show_all() # Start a recursive main loop for this spoke, which will prevent # signals from going to the underlying (but still displayed) Hub and # prevent the user from switching away. It's up to the spoke's back # button handler to kill its own layer of main loop. Gtk.main() action.window.set_transient_for(None) action._visitedSinceApplied = True # Don't take _visitedSinceApplied into account here. It will always be # True from the line above. if action.changed and (not action.skipTo or (action.skipTo and action.applyOnSkip)): action.apply() action.execute() action._visitedSinceApplied = False
def main(db, debug=False): builder = Gtk.Builder() builder.add_from_file("view/notebook.glade") liststore = builder.get_object("liststore") view = builder.get_object("treeview_notelist") textbuffer = builder.get_object("current_note_buffer") selection = builder.get_object("treeview_notelist_selection") # Populate the liststore. Set the text buffer to the first note text if # the note db is non-empty query = db.query('') if query != []: for title, uid in query: liststore.append([title, uid]) textbuffer.set_text(db.get_text(query[0][1])) # 0,1 means first note, uid else: liststore.append(db.add_note('')) # Handle empty db # Make sure the first note is selected selection.select_iter(liststore.get_iter("0")) # 0 means first note, no search in-tree handler = Handler(liststore, selection, textbuffer, view, db) builder.connect_signals(handler) if debug is False: window = builder.get_object("main_window") window.show_all() Gtk.main() else: return handler
def _gtk_main(): gui = GtkRll() gui.connect("delete-event", Gtk.main_quit) signal(SIGINT, SIG_DFL) gui.show_all() # FIXME: KeyboardInterrupt here hangs it. Gtk.main()
def __init__(self): # set execution directory to base_uri base_uri = os.path.dirname(__file__) # make builder object self.builder = Gtk.Builder() self.builder.add_from_file(base_uri+"/nfoView.glade") # get widgets from builder object self.window_main = self.builder.get_object("window_main") self.window_about = self.builder.get_object("window_about") self.window_file = self.builder.get_object("window_file") #self.window_about.show() self.text_view = self.builder.get_object("text_view") # conect signals self.builder.connect_signals(self) # creats a text buffer object text_buffer self.text_buffer = Gtk.TextBuffer() # sets the initial text to text_buffer and set the text buffer to text_view if len(sys.argv)>=2 and os.path.isfile(sys.argv[1]): fil = open(sys.argv[1], "r") else: fil = open(base_uri+'/start.nfo', "r") self.text_buffer.set_text(fil.read()) fil.close() self.text_view.set_buffer(self.text_buffer) # runs the gtk main loop Gtk.main()
def test_dance_grid (): from . import gsudoku window = Gtk.Window() game = '''9 1 6 3 2 8 4 5 7 5 7 4 6 1 9 2 8 3 8 3 2 5 7 4 9 6 1 6 8 7 2 4 1 3 9 5 2 9 5 7 3 6 1 4 8 3 4 1 8 9 5 7 2 6 4 6 9 1 8 7 5 3 2 1 2 8 9 5 3 6 7 4 7 5 3 4 6 2 8 1 9''' gsd = gsudoku.SudokuGameDisplay(game) dancer = GridDancer(gsd) button = Gtk.Button('toggle') button.connect('clicked', lambda *args: dancer.stop_dancing() if dancer.dancing else dancer.start_dancing()) vbox = Gtk.VBox() vbox.pack_start(gsd, True, True, 0) vbox.pack_end(button, True, True, 0) vbox.set_focus_child(button) window.add(vbox) window.show_all() window.connect('delete-event', Gtk.main_quit) Gtk.main()
def test_searchentry(self): from softwarecenter.ui.gtk3.widgets.searchentry import get_test_searchentry_window win = get_test_searchentry_window() s = "foo" win.entry.insert_text(s, len(s)) GObject.timeout_add(TIMEOUT, lambda: win.destroy()) Gtk.main()
def main(): indicator = appindicator.Indicator.new(APPINDICATOR_ID, gtk.STOCK_YES, appindicator.IndicatorCategory.SYSTEM_SERVICES) indicator.set_status(appindicator.IndicatorStatus.ACTIVE) indicator.set_menu(build_menu()) gtk.main()
def __init__(self): self.tnc = None self.connect_message = None self.builder = Gtk.Builder() self.builder.add_from_file( os.path.join(glade_location(), "glade/MobilinkdTnc1Config.glade")) self.window = self.builder.get_object("window") self.window.connect("delete-event", self.close) self.init_serial_port_combobox() self.init_power_section() self.init_transmit_volume() self.init_receive_volume() self.init_kiss_parameters() self.init_firmware_section() self.init_eeprom_section() self.status = self.builder.get_object("statusbar") self.builder.connect_signals(self) self.tnc_disconnect() self.window.show() Gtk.main()
def main(): debug = False print("Trackma-gtk v{}".format(utils.VERSION)) if '-h' in sys.argv: print("Usage: trackma-qt [options]") print() print('Options:') print(' -d Shows debugging information') print(' -h Shows this help') return if '-d' in sys.argv: debug = True app = TrackmaWindow(debug) try: GObject.threads_init() Gdk.threads_init() Gdk.threads_enter() app.main() Gtk.main() except utils.TrackmaFatal as e: md = Gtk.MessageDialog(None, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, str(e)) md.run() md.destroy() finally: Gdk.threads_leave()
def run(): # Protobuf #c = ControllerProtobuf() # Directly connected to the vision server c = VisionManager() if not c.is_connected(): print("Vision server is not accessible.") return server = Server() server.start("127.0.0.1", 5030) # add observer output for "server" c.add_filter_output_observer(server.send) from gi.repository import Gtk, GObject import CapraVision.client.gtk.main GObject.threads_init() w = CapraVision.client.gtk.main.WinFilterChain(c) w.window.show_all() Gtk.main() # Close connection server.stop() c.close_server()
def run (self): if self.use_callback: raise RuntimeError if self.show_dialog: wait = Gtk.MessageDialog (self.parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.INFO, Gtk.ButtonsType.CANCEL, _("Please wait")) wait.connect ("delete_event", lambda *args: False) wait.connect ("response", self._wait_window_response) if self.parent: wait.set_transient_for (self.parent) wait.set_position (Gtk.WindowPosition.CENTER_ON_PARENT) wait.format_secondary_text (_("Gathering information")) wait.show_all () self.timeout_source = GLib.timeout_add (50, self._check_thread) Gtk.main () GLib.source_remove (self.timeout_source) if self.show_dialog: wait.destroy () return self.thread.collect_result ()
def main(): locale.setlocale(locale.LC_ALL, '') showFindUI() Gtk.main() sys.exit(0)
def main(store=False, metadata=False, port=6601): win = Gtk.Window() # Connect to the test-server boot_base( verbosity=logging.DEBUG, protocol_machine='idle', host='localhost', port=port ) if store: boot_store() if metadata: boot_metadata() win.connect('destroy', Gtk.main_quit) try: yield win except: raise else: win.show_all() Gtk.main() finally: shutdown_application()
def __init__(self): '''Handler Initialisations. Obtain all references here.''' self.builder = Gtk.Builder() self.glade = "mechanig.ui" # TODO : Use os module to resolve to the full path. self.builder.add_from_file(self.glade) self.ui = ui(self.builder) self.builder.connect_signals(self) self.ui['mechanig_main'].set_resizable(False) #self.ui['nb_mechanig'].set_show_tabs(False) self.notebook = self.ui['nb_mechanig'] self.startpage = Startpage(self.ui, self.notebook) self.unitysettings = Unitysettings(self.ui) self.compizsettings = Compizsettings(self.ui) self.themesettings = Themesettings(self.ui) self.desktopsettings = Desktopsettings(self.ui) #self.box.pack_end(self.start, True, True, 0) self.notebook.append_page(self.startpage.page, None) self.notebook.append_page(self.unitysettings.page, None) self.notebook.append_page(self.compizsettings.page, None) self.notebook.append_page(self.themesettings.page, None) self.notebook.append_page(self.desktopsettings.page, None) self.ui['mechanig_main'].show_all() self.ui['mechanig_main'].connect("delete-event", Gtk.main_quit) Gtk.main()
def __init__(self): builder = gtk.Builder() builder.add_from_file(self.glade_file_path) self.HANDLER = ActionHandler(builder) handlers = { "on_label_size_allocate": self.HANDLER.label_resize, "on_tree_size_allocate": self.HANDLER.tree_resize, "on_manga_list_size_allocate": self.HANDLER.manga_list_resize, "on_chapter_activate": self.HANDLER.chapter_activate, "on_manga_activate": self.HANDLER.manga_activate } builder.connect_signals(handlers) window = builder.get_object("MangaReader") window.connect("destroy", self._destroy) window.set_title("Manga Reader") # window.set_icon_from_file("teat.png") self.MANGA_LIST = builder.get_object("MangaListData") for row in self.get_manga_list(): self.MANGA_LIST.append([row[0], row[1], row[2], row[3], row[4], row[5]]) window.show_all() manga_tree = builder.get_object("MangaTreeView") manga_tree.get_selection().select_path((0,)) self.HANDLER.manga_activate(manga_tree) builder.get_object("ChapterImages").hide() # builder.get_object("ChapterImagesTree").get_selection().set_mode(gtk.SELECTION_NONE) window.set_size_request(800, 500) gtk.main()
def run(): # CLASS NOT CURRENTLY USED # Protobuf #c = ControllerProtobuf() print "In main/maingtk. Do you really want to be here?" # Directly connected to the vision server c = VisionManager() if not c.is_connected(): print("Vision server is not accessible.") return #server = Server() # server.start("127.0.0.1", 5030) # add observer output for "server" #c.add_filter_output_observer(server.send) from gi.repository import Gtk, GObject import CapraVision.client.gtk.main GObject.threads_init() # w = CapraVision.client.gtk.main.WinFilterChain(c) #w.window.show_all() Gtk.main() # Close connection #server.stop() c.close_server()
def main(): indicator = AppIndicator.Indicator.new( APPINDICATOR_ID, os.path.abspath("./icon.svg"), AppIndicator.IndicatorCategory.SYSTEM_SERVICES ) indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE) indicator.set_menu(build_menu()) Gtk.main()
def main(): window = gtk.Window() grid = gtk.Grid() grid.set_column_homogeneous(True) grid.set_row_homogeneous(False) grid.set_column_spacing(3) grid.set_row_spacing(3) window.add(grid) button1 = gtk.Button(label="Btn 1") button2 = gtk.Button(label="Btn 2") button3 = gtk.Button(label="Btn 3") button4 = gtk.Button(label="Btn 4") button5 = gtk.Button(label="Btn 5") button6 = gtk.Button(label="Btn 6") # grid.attach(child, left, top, width, height) # child (Gtk.Widget) – the widget to add # left (int) – the column number to attach the left side of child to # top (int) – the row number to attach the top side of child to # width (int) – the number of columns that child will span # height (int) – the number of rows that child will span # SEE: http://lazka.github.io/pgi-docs/Gtk-3.0/classes/Grid.html#Gtk.Grid.attach grid.attach(button1, left=0, top=0, width=1, height=1) grid.attach(button2, left=1, top=0, width=2, height=1) grid.attach(button3, left=0, top=1, width=1, height=2) grid.attach(button4, left=1, top=1, width=2, height=1) grid.attach(button5, left=1, top=2, width=1, height=1) grid.attach(button6, left=2, top=2, width=1, height=1) window.connect("delete-event", gtk.main_quit) # ask to quit the application when the close button is clicked window.show_all() # display the window gtk.main() # GTK+ main loop
def run(self, debug=None): """ Run the main loop. """ GObject.timeout_add(50, self.select_setup) # self.select_setup() # GObject.timeout_add(500, callback) # loop = GLib.MainLoop() # loop.run() # return if debug is not None: self.debug_shell_gtk(debug) else: from gi.repository import Gtk # workaround for https://bugzilla.gnome.org/show_bug.cgi?id=622084 import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # end workaround logger.debug("Entering main loop") # main_loop = GLib.MainLoop() # main_loop.run() Gtk.main()
def main(): builder = Gtk.Builder() builder.add_from_file("interface.glade") window = builder.get_object("mainWindow") box = builder.get_object("mainBox") app = WaferDisplay() if len(sys.argv) > 1: app.loadWithArg(sys.argv[1]) app.connect('draw', app.do_draw_cb) eventbox = Gtk.EventBox() eventbox.set_above_child(True) eventbox.connect("button-press-event", app.onclick) eventbox.add(app) box.pack_end(eventbox, True, True, 0) builder.get_object("newMenu").connect('activate', app.newWaferWindow) builder.get_object("saveMenu").connect('activate', app.save) builder.get_object("saveasMenu").connect('activate', app.saveas) builder.get_object("openMenu").connect('activate', app.load) builder.get_object("quitMenu").connect('activate', destroy) builder.get_object("menuWaferProps").connect('activate', app.editWaferWindow) builder.get_object("menuCalcWedge").connect('activate', app.calcWedge) builder.get_object("menuPrint").connect('activate', app.onPrintRequest) window.connect_after('destroy', destroy) window.show_all() Gtk.main()
def run(self): print "Ao rodar" print self print dir(self) Gtk.main()
header_bar = Gtk.HeaderBar() header_bar.set_show_close_button(True) header_bar.props.title = "Some Stuff" self.set_titlebar(header_bar) audio_button = Gtk.Button() cd_icon = Gio.ThemedIcon(name="gnome-dev-cdrom-audio") image = Gtk.Image.new_from_gicon(cd_icon, Gtk.IconSize.BUTTON) audio_button.add(image) header_bar.pack_end(audio_button) box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) Gtk.StyleContext.add_class(box.get_style_context(), 'linked') left_arrow = Gtk.Button() left_arrow.add(Gtk.Arrow(Gtk.ArrowType.LEFT, Gtk.ShadowType.NONE)) box.add(left_arrow) right_arrow = Gtk.Button() right_arrow.add(Gtk.Arrow(Gtk.ArrowType.RIGHT, Gtk.ShadowType.NONE)) box.add(right_arrow) header_bar.pack_start(box) self.add(Gtk.TextView()) win = MainWindow() win.connect('delete-event', Gtk.main_quit) win.show_all() Gtk.main()
def run(self): Gtk.main()
def main(self): """Main indicator function.""" gtk.main()
def app_config(): from config_panel import ConfigPanel from gi.repository import Gtk ConfigPanel() Gtk.main()
def run(self): GObject.threads_init() Gtk.main()
def main(): c = Controller() Gtk.main()
#server_class=HTTPServer #handler_class=GP #port=8088 #server_address = ('', port) #httpd = server_class(server_address, handler_class) #print('Server running at localhost:8088...') #httpd.serve_forever() server=ThreadingHTTPServer(('', 8088), GP) print('Server running at localhost:8088...') thread=threading.Thread(target=server.serve_forever) thread.deamon = False thread.start() win = gtk.Window() win.connect("destroy", gtk.main_quit) win.set_size_request(800, 600) da = gtk.DrawingArea() da.connect("draw", expose) win.add(da) win.show_all() glib.io_add_watch(0, glib.IO_IN, stdin_handler) glib.timeout_add(30, redraw) gtk.main() print("END")
def _too_small_screen_exit(): global exit_timeout_id exit_timeout_id = GObject.timeout_add(200, _show_too_small_info) # Launch gtk+ main loop Gtk.main()
def run_sub(self): # print dir(self) # print "Lida da sub: ",len(self.sub_window.lista), self.sub_window.lista # print "Antes :", len(self.sub_window.liststoregrupo) # Aqui recebemos a liststore com os grupos selecionados e a usamos como base para: # # 1 - Gerar uma LISTA <_lista_grupo> com os <group_id> de cada grupo selecionado baseando-se na LISTSTORE<self.sub_window.lista> do GTK, passado como parâmetro # 2 - Gerar um DICT <_dict_group_hosts> (chave = <group_id>, data = lista de <host_id> dos Hosts que pertencem ao grupo) # 3 - Identificar os hosts de intersecção nos grupos passados como parâmetro na LISTA <_intersec_hosts> a partir de <_lista_grupo> # 4 - Gerar uma LISTA de LISTA<_lista_grupo_completa> para carregar na caixa de GRUPOS da sub_tela. Essa lista terá listas com : <group_id>, <group_name>, <qtd_hosts_group> # 5 - Gerar uma LISTA de LISTA <_lista_host_intersec_completa> para carregar na caixa de HOSTS da sub_tela. Essa lista terá listas com : <host_id>, <host_name>, <ip> # # Declarando _lista_grupo = [] _dict_group_hosts = {} _intersec_hosts = [] _lista_grupo_completa = [] _lista_host_itersec_completa = [] _hosts_zabbix = [ ] # lista que recebe a o resultado da pesquisa de hosts no grupo (API ZABBIX) - resultado é uma lista de dicionários entregue pela API do Zabbix _hosts = [] # lista que recebe a lista de hostid # Carregando a _lista_grupo com os group_id passados como parâmetro em self.sub_window.lista (gerando 1) for _iter_liststore in self.sub_window.lista: _lista_grupo.append( _iter_liststore[1]) # adiciona group_id a _lista_grupo _old = [] # Lista de apoio - não é base do processo # Percorrendo a LISTA <_lista_grupo>, usando-a de base para carga do DICIONARIO _dict_group_hosts e identificando os hosts de intersecção em _intersec_hosts (gerando 2 e 3) for _group_id in _lista_grupo: # percorrendo _lista_grupo _hosts_zabbix = vZapi.host.get( { "groupids": _group_id, "output": "hostid" } ) # faz a pesquisa no API do Zabbix e retorna uma lista de dicionario com os "host_id" que pertencem ao grupo print _hosts_zabbix for _host in _hosts_zabbix: # percorrendo a resposta da API Zabbix para separar os host_id e carrega-la na LISTA _hosts _hosts.append( _host['hostid'] ) # adiciona o "host_id" a LISTA _hosts para posterior carga no DICIONARIO _dict_host _dict_group_hosts[str( _group_id )] = _hosts # carrega o DICIONARIO "_dict_host" usando "str(_group_id)" como chave e a LISTA _hosts como DADO _hosts = [ ] #descarrega a LISTA _hosts para ser gerada novamente com dados de outro grupo se for o caso if len(_old) > 0: if len(_intersec_hosts) < 1: _intersec_hosts = list( set(_old).intersection( set(_dict_group_hosts[str(_group_id)]))) else: _intersec_hosts = list( set(_intersec_hosts).intersection( set(_old)).intersection( set(_dict_group_hosts[str(_group_id)]))) _old = _dict_group_hosts[str(_group_id)] # Percorrendo a LISTA _lista_grupo, pesquisa o DICIONARIO _dict_group_hosts e API ZABBIX para determinar _group_name e _qtd_hosts_group for _group_id in _lista_grupo: _group_name = vZapi.hostgroup.get({ "output": ["name"], "groupids": [_group_id] }) print _group_name _qtd_hosts_group = len(_dict_group_hosts[str(_group_id)]) print _group_id, _group_name[0]['name'], _qtd_hosts_group # Carregando os dados na TreeView de Grupo self.sub_window.liststoregrupo.append( [_group_name[0]['name'], _qtd_hosts_group]) # Percorrendo a LISTA _intersec_hosts, pesquisando na API ZABBIX o hostname e IPs (lista) if len(_intersec_hosts) > 0: print "--------------------------------------------------" for _host_id in _intersec_hosts: _host_name = vZapi.host.get({ "output": ["name"], "hostids": [_host_id] }) _host_ip = vZapi.hostinterface.get({ "hostids": _host_id, "output": ["ip"] }) _templates = vZapi.template.get({ "output": ["name"], "hostids": [_host_id] }) # _host_templates=vZapi.template.get({"output": "extend", "hostids": [_host_id]}) _host_templates = "" for _template in _templates: if len(_host_templates) < 1: _host_templates = _template["name"] else: _host_templates = _host_templates + " | " + _template[ "name"] # Captura valores dos itens que devem ser exibidos da treeviewe (no momendo 'agent.version' e 'icmpping[{IPADDRESS},,,,]') _host_itens = vZapi.item.get({ "output": ['lastvalue', 'name', 'key_'], "hostids": [_host_id], "filter": { "key_": ['agent.version', 'icmpping[{IPADDRESS},,,,]'] } }) # _host_itens=vZapi.item.get({"output": ['lastvalue', 'name', 'key_'], "hostids": [_host_id]}) # print "_host_itens..:", _host_name[0]['name'], ":", _host_itens # print _host_id, _host_name[0]['name'], _host_ip[0]['ip'], _host_templates # print "template", _host_templates _host_agentversion = _host_itens[0][ 'lastvalue'] # se mudar os itens, isso aqui deve ser mudado tbém - ATENÇÃO _host_pingvalue = _host_itens[1]['lastvalue'] # print "Versao agente:",_host_agentversion # print "Status PING :",_host_pingvalue print _host_id + ":" + _host_name[0]['name'] + ":" + _host_ip[0][ 'ip'] + ":" + _host_templates + ":" + _host_agentversion + ":" + _host_pingvalue # carrega o gráfico de status de ping na variavel que será adicionada na treeview (GdkPixbuf) if _host_pingvalue == '1': _host_pingstatus = _verde else: _host_pingstatus = _vermelho # Carregando os dados na Treeview de Hosts self.sub_window.liststorehost.append([ _host_name[0]['name'], _host_ip[0]['ip'], _host_templates, _host_agentversion, _host_pingstatus ]) print "--------------------------------------------------" # Carregando o valor adequado no LABEL _TEXTO = str( len(_intersec_hosts)) + " Hosts nos Grupos selecionados" print _TEXTO self.sub_window.info_label.set_text(_TEXTO) else: self.sub_window.info_label.set_text( "Não há Hosts que atendam o critério") print "---------------------------------------------------" print " respostas" print "---------------------------------------------------" print "1 _lista_grupo" print _lista_grupo print "2 _dict_host" print _dict_group_hosts print "3 _intersec_hosts" print _intersec_hosts Gtk.main()
def run(self, *args, **kwargs): Gtk.main()
def main(self): Gtk.main()
def wait(self): Gtk.main()
def main(root_path): """ Called at application start. Initializes application with a default project. """ # DEBUG: Direct output to log file if log file set if _log_file != None: log_print_output_to_file() print "Application version: " + editorstate.appversion # Print OS, Python version and GTK+ version try: os_release_file = open("/etc/os-release", "r") os_text = os_release_file.read() s_index = os_text.find("PRETTY_NAME=") e_index = os_text.find("\n", s_index) print "OS: " + os_text[s_index + 13:e_index - 1] except: pass print "Python", sys.version gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()) print "GTK+ version:", gtk_version editorstate.gtk_version = gtk_version try: editorstate.mlt_version = mlt.LIBMLT_VERSION except: editorstate.mlt_version = "0.0.99" # magic string for "not found" #print "SDL version:", str(editorstate.get_sdl_version()) # passing -xdg as a flag will change the user_dir location with XDG_CONFIG_HOME # For full xdg-app support all the launch processes need to add this too, currently not impl. for arg in sys.argv: if arg.lower() == "-xdg": editorstate.use_xdg = True # Create hidden folders if not present user_dir = utils.get_hidden_user_dir_path() print "User dir:", user_dir if not os.path.exists(user_dir): os.mkdir(user_dir) if not os.path.exists(user_dir + mltprofiles.USER_PROFILES_DIR): os.mkdir(user_dir + mltprofiles.USER_PROFILES_DIR) if not os.path.exists(user_dir + AUTOSAVE_DIR): os.mkdir(user_dir + AUTOSAVE_DIR) if not os.path.exists(user_dir + BATCH_DIR): os.mkdir(user_dir + BATCH_DIR) if not os.path.exists(user_dir + appconsts.AUDIO_LEVELS_DIR): os.mkdir(user_dir + appconsts.AUDIO_LEVELS_DIR) if not os.path.exists(utils.get_hidden_screenshot_dir_path()): os.mkdir(utils.get_hidden_screenshot_dir_path()) if not os.path.exists(user_dir + appconsts.GMIC_DIR): os.mkdir(user_dir + appconsts.GMIC_DIR) if not os.path.exists(user_dir + appconsts.MATCH_FRAME_DIR): os.mkdir(user_dir + appconsts.MATCH_FRAME_DIR) if not os.path.exists(user_dir + appconsts.TRIM_VIEW_DIR): os.mkdir(user_dir + appconsts.TRIM_VIEW_DIR) if not os.path.exists(user_dir + appconsts.NATRON_DIR): os.mkdir(user_dir + appconsts.NATRON_DIR) # Set paths. respaths.set_paths(root_path) # Load editor prefs and list of recent projects editorpersistance.load() if editorpersistance.prefs.theme != appconsts.LIGHT_THEME: respaths.apply_dark_theme() if editorpersistance.prefs.display_all_audio_levels == False: editorstate.display_all_audio_levels = False editorpersistance.create_thumbs_folder_if_needed(user_dir) editorpersistance.create_rendered_clips_folder_if_needed(user_dir) editorpersistance.save() # Init translations module with translations data translations.init_languages() translations.load_filters_translations() mlttransitions.init_module() # Apr-2017 - SvdB - Keyboard shortcuts shortcuts.load_shortcut_files() shortcuts.load_shortcuts() # We respaths and translations data available so we need to init in a function. workflow.init_data() # RHEL7/CentOS compatibility fix if gtk_version == "3.8.8": GObject.threads_init() # Init gtk threads Gdk.threads_init() Gdk.threads_enter() # Themes if editorpersistance.prefs.theme != appconsts.LIGHT_THEME: Gtk.Settings.get_default().set_property( "gtk-application-prefer-dark-theme", True) if editorpersistance.prefs.theme == appconsts.FLOWBLADE_THEME: gui.apply_gtk_css() # Load drag'n'drop images dnd.init() # Adjust gui parameters for smaller screens scr_w = Gdk.Screen.width() scr_h = Gdk.Screen.height() editorstate.SCREEN_WIDTH = scr_w editorstate.SCREEN_HEIGHT = scr_h print "Screen size:", scr_w, "x", scr_h print "Small height:", editorstate.screen_size_small_height() print "Small width:", editorstate.screen_size_small_width() _set_draw_params() # Refuse to run on too small screen. if scr_w < 1151 or scr_h < 767: _too_small_screen_exit() return # Splash screen if editorpersistance.prefs.display_splash_screen == True: show_splash_screen() # Init MLT framework repo = mlt.Factory().init() processutils.prepare_mlt_repo(repo) # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs. locale.setlocale(locale.LC_NUMERIC, 'C') # Check for codecs and formats on the system. mltenv.check_available_features(repo) renderconsumer.load_render_profiles() # Load filter and compositor descriptions from xml files. mltfilters.load_filters_xml(mltenv.services) mlttransitions.load_compositors_xml(mltenv.transitions) # Replace some services if better replacements available. mltfilters.replace_services(mltenv.services) # Create list of available mlt profiles. mltprofiles.load_profile_list() # Save assoc file path if found in arguments. global assoc_file_path assoc_file_path = get_assoc_file_path() # There is always a project open, so at startup we create a default project. # Set default project as the project being edited. editorstate.project = projectdata.get_default_project() check_crash = True # Audiomonitoring being available needs to be known before GUI creation. audiomonitoring.init(editorstate.project.profile) # Set trim view mode to current default value. editorstate.show_trim_view = editorpersistance.prefs.trim_view_default # Check for tools and init tools integration. gmic.test_availablity() toolnatron.init() toolsintegration.init() #toolsintegration.test() # Create player object. create_player() # Create main window and set widget handles in gui.py for more convenient reference. create_gui() # Inits widgets with project data. init_project_gui() # Inits widgets with current sequence data. init_sequence_gui() # Launch player now that data and gui exist launch_player() # Editor and modules need some more initializing. init_editor_state() # Tracks need to be recentered if window is resized. # Connect listener for this now that the tline panel size allocation is sure to be available. global window_resize_id, window_state_id window_resize_id = gui.editor_window.window.connect( "size-allocate", lambda w, e: updater.window_resized()) window_state_id = gui.editor_window.window.connect( "window-state-event", lambda w, e: updater.window_resized()) # Get existing autosave files autosave_files = get_autosave_files() # Show splash if ((editorpersistance.prefs.display_splash_screen == True) and len(autosave_files) == 0 ) and not editorstate.runtime_version_greater_then_test_version( editorpersistance.prefs.workflow_dialog_last_version_shown, editorstate.appversion): global splash_timeout_id splash_timeout_id = GLib.timeout_add(2600, destroy_splash_screen) splash_screen.show_all() appconsts.SAVEFILE_VERSION = projectdata.SAVEFILE_VERSION # THIS IS A QUESTIONABLE IDEA TO SIMPLIFY IMPORTS, NOT DRY. WHEN DOING TOOLS THAT RUN IN ANOTHER PROCESSES AND SAVE PROJECTS, THIS LINE NEEDS TO BE THERE ALSO. # Every running instance has unique autosave file which is deleted at exit set_instance_autosave_id() # Existance of autosave file hints that program was exited abnormally. if check_crash == True and len(autosave_files) > 0: if len(autosave_files) == 1: GObject.timeout_add(10, autosave_recovery_dialog) else: GObject.timeout_add(10, autosaves_many_recovery_dialog) else: start_autosave() # We prefer to monkeypatch some callbacks into some modules, usually to # maintain a simpler and/or non-circular import structure. monkeypatch_callbacks() # File in assoc_file_path is opened after very short delay. if not (check_crash == True and len(autosave_files) > 0): if assoc_file_path != None: print "Launch assoc file:", assoc_file_path global assoc_timeout_id assoc_timeout_id = GObject.timeout_add(10, open_assoc_file) # SDL 2 consumer needs to created after Gtk.main() has run enough for window to be visble #if editorstate.get_sdl_version() == editorstate.SDL_2: # needs more state considerion still # print "SDL2 timeout launch" # global sdl2_timeout_id # sdl2_timeout_id = GObject.timeout_add(1500, create_sdl_2_consumer) # In PositionNumericalEntries we are using Gtk.Entry objects in a way that works for us nicely, but is somehow "error" for Gtk, so we just kill this. Gtk.Settings.get_default().set_property("gtk-error-bell", False) # Show first run worflow info dialog if not shown for this version of application. if editorstate.runtime_version_greater_then_test_version( editorpersistance.prefs.workflow_dialog_last_version_shown, editorstate.appversion): GObject.timeout_add(500, show_worflow_info_dialog) # Launch gtk+ main loop Gtk.main() Gdk.threads_leave()
def main(self): GLib.timeout_add(1000, self.update_value) Gtk.main()
def run(self): Gtk.Widget.show_all(self) Gtk.main()
def inputhook_gtk3(): GLib.io_add_watch(sys.stdin, GLib.PRIORITY_DEFAULT, GLib.IO_IN, _main_quit) Gtk.main() return 0
def main(): conf = Config() win = MyWindow(conf) win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
def main(demoapp=None): IconviewEditApp() Gtk.main()
def mainloop(): from xl.externals.sigint import InterruptibleLoopContext with InterruptibleLoopContext(Gtk.main_quit): Gtk.main()
def main(): # TODO: Gtk.Application: https://python-gtk-3-tutorial.readthedocs.io/en/latest/application.html path = os.path.abspath(os.path.dirname(__file__)) # Load settings settings = SkyTempleSettingsStore() if sys.platform.startswith('win'): # Load theming under Windows _windows_load_theme(settings) # Solve issue #12 try: from skytemple_files.common.platform_utils.win import win_set_error_mode win_set_error_mode() except BaseException: # This really shouldn't fail, but it's not important enough to crash over pass if sys.platform.startswith('darwin'): # Load theming under macOS _macos_load_theme(settings) # The search path is wrong if SkyTemple is executed as an .app bundle if getattr(sys, 'frozen', False): path = os.path.dirname(sys.executable) itheme: Gtk.IconTheme = Gtk.IconTheme.get_default() itheme.append_search_path(os.path.abspath(icons())) itheme.append_search_path(os.path.abspath(os.path.join(data_dir(), "icons"))) itheme.append_search_path(os.path.abspath(os.path.join(get_debugger_data_dir(), "icons"))) itheme.rescan_if_needed() # Load Builder and Window builder = Gtk.Builder() builder.add_from_file(os.path.join(path, "skytemple.glade")) main_window: Window = builder.get_object("main_window") main_window.set_role("SkyTemple") GLib.set_application_name("SkyTemple") GLib.set_prgname("skytemple") # TODO: Deprecated but the only way to set the app title on GNOME...? main_window.set_wmclass("SkyTemple", "SkyTemple") # Load CSS style_provider = Gtk.CssProvider() with open(os.path.join(path, "skytemple.css"), 'rb') as f: css = f.read() style_provider.load_from_data(css) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION ) # Load async task runner thread AsyncTaskRunner.instance() # Init. core events event_manager = EventManager.instance() if settings.get_integration_discord_enabled(): try: from skytemple.core.events.impl.discord import DiscordPresence discord_listener = DiscordPresence() event_manager.register_listener(discord_listener) except BaseException: pass # Load modules Modules.load() # Load main window + controller MainController(builder, main_window, settings) main_window.present() main_window.set_icon_name('skytemple') try: Gtk.main() except (KeyboardInterrupt, SystemExit): AsyncTaskRunner.end()
def mainloop(): if Gtk.main_level() == 0: cbook._setup_new_guiapp() Gtk.main()
def main(): Gtk.main()
class mySinker_UI: def __init__(ui, py_fn=''): ui.fontDesc = Pango.FontDescription('Univers,Sans Condensed 7') ui.fontColDesc = Pango.FontDescription('Univers Condensed CE 9') ui.fontFixedDesc = Pango.FontDescription('Monospace Bold 7') grt = Gtk.ResponseType ui.rspns = dict( map( lambda s: (int(getattr(grt, s)), f"Gtk.ResponseType.{s}"), sorted(filter( lambda a: a == a.upper() and (not (callable(getattr(grt, a)))), dir(grt)), key=lambda s: int(getattr(grt, s)), reverse=True))) ui.Init(py_fn=py_fn) if __name__ == "__main__": ui.bld.connect_signals(ui.Connections()) ui.mainWindow.connect("destroy", lambda w: Gtk.main_quit()) ui.buttQuit.connect("clicked", lambda w: Gtk.main_quit()) _p = ui._p _p("Any logs appears here...\nThere's no any yet… \n") ui.buttConv.connect("clicked", ui.test) for _attr in dir(ui.logView): tatr = str(_attr) if tatr[0:2] == "tg": _p("\t%s\n" % tatr) ui.Enter() Enter = lambda ui: Gtk.main() Exit = lambda ui: Gtk.main_quit() Bind = lambda ui, w_nm, wgt=None:\ setattr(wgt, w_nm, ui.bld.get_object(w_nm)) if isinstance(wgt, Gtk.Widget)\ else setattr(ui, w_nm, ui.bld.get_object(w_nm)) def Binds(ui, s_bnds, wgt=None): for w_nm in s_bnds.split(): ui.Bind(w_nm, wgt=wgt) if __name__ == "__main__": def test(ui, butt): exampl_fn = '/examplePath/exampleFile.filter' _p = ui._p for txtslice, cTag in (("Error in file:", 2), ("'", 0), (exampl_fn, 1), ("'\n", 0)): _p(txtslice, tag=(None, 'tgFlNm', 'tg_Err')[cTag]) for txtslice, cTag in (("Error in file:", 2), ("'", 0), (exampl_fn, 1), ("'\n", 0)): _p(txtslice, tag=(None, 'fnm', 'err')[cTag]) for txtslice, cTag in (("Error in file:", 2), ("'", 0), (exampl_fn, 1), ("'\n", 0)): _p(txtslice, tag=(None, ui.tgFlNm, ui.tg_Err)[cTag]) insp_o = ui.tgFlNm _p(f"{str(insp_o)}\n") for _attr in dir(insp_o): r_attr = getattr(insp_o, _attr) tatr = str(_attr) if callable(r_attr): _p("\t") _p(f"{tatr}()", 'phr') _p(f"\n") else: _p(f"\t{tatr}\n") def Init(ui, py_fn=''): if not (py_fn): py_fn = ph.realpath(__file__) ui.runpath = py_dn = ph.dirname(py_fn) if __name__ == "__main__": py_fn = py_fn.replace('uiMySinker', 'mySinker') ui.cfg = {} ui.bld = Gtk.Builder() ui_fn = ph.join(py_dn, f"{ph.basename(py_fn).rsplit('.', 1)[0]}.ui") ui.bld.add_from_file(ui_fn) print(f"UI Filename:„{ui_fn}”") ui.Binds('mainWindow logView buttLastRel buttUnZip buttNumFix buttConv buttDiff '\ 'chkDbg buttPreferences toggWrap buttClear buttQuit '\ 'dsplZipFN dsplInFN dsplOutFN dlgOpts dlgGetFN dlgSrch') ui.mainWindow.show_all() ui.mainWindow.set_keep_above(True) global _l, _lp _l, _lp = ui._p, ui._lp ui.createTxtTags() ui.poeFilter = Gtk.FileFilter() ui.poeFilter.set_name("PoE item filter script (*.filter)") ui.poeFilter.add_pattern("*.filter") ui.poeFilterZip = Gtk.FileFilter() ui.poeFilterZip.set_name("PoE item filter pack by NeverSink (*.zip)") ui.poeFilterZip.add_pattern("*.zip") ui.txtFN = u'Use „Open” button to browse *.filter file →' for ui_attr in dDialogs.keys(): g = globals() dlg_route = dDialogs[ui_attr] setattr(ui, ui_attr, g[dlg_route](ui)) def Connections(ui): handlers = {} for ui_attr in dDialogs.keys(): handlers.update(getattr(ui, ui_attr).Connections('dg_')) for hn in (dr[3:] for dr in dir(ui) if dr[:3] == 'go_'): handlers[f"ui_{hn}"] = getattr(ui, f"go_{hn}") return handlers def createTxtTags(ui): logBuff = ui.logView.get_buffer() _B = Pango.Weight.BOLD ui.tgFlNm = logBuff.create_tag('fnm', weight=_B) ui.tgYllw = logBuff.create_tag('ylw', weight=_B) ui.tgPhrs = logBuff.create_tag('phr', weight=_B) ui.tg_Err = logBuff.create_tag('err', weight=_B) ui.tgWarn = logBuff.create_tag('wrn', weight=_B) ui.tgEnum = logBuff.create_tag('num', weight=_B) ui.tgSmrf = logBuff.create_tag('srf', weight=_B) for color_cfg, color_val in ( ('fgFlNm', 'yellow'), ('fgYllw', '#FF5'), ('fgPhrs', 'orange'), ('bgPhrs', '#002818'), ('fg_Err', 'red'), ('fgEnum', '#0F0'), ('fgWarn', '#F85'), ('fgSmrf', '#25E'), ): tag_name = color_cfg.replace('bg', 'tg').replace('fg', 'tg') color = Gdk.color_parse(color_val) prop_name = { 'bg': 'background-gdk', 'fg': 'foreground-gdk' }[color_cfg[0:2]] getattr(ui, tag_name).set_property(prop_name, color) go_Clear = lambda ui, *args: ui.logView.get_buffer().set_text('') go_Wrap = lambda ui, widget: ui.logView.set_wrap_mode( (Gtk.WrapMode.NONE, Gtk.WrapMode.WORD)[widget.get_active()]) def go_SrchLog(ui, b): sVis = not (ui.dlgSrch.is_visible()) ui.srch.dlgShow() if sVis else ui.srch.dlgHide() def go_PhraseIcons(ui, ed, icoPos, sigEvent): if icoPos == Gtk.EntryIconPosition.SECONDARY: ed.set_text('') def _p(ui, txt, tag=None, short_path=False): buff = ui.logView.get_buffer() end = buff.get_end_iter() text = hh(txt) if short_path else txt if tag and (isinstance(tag, str)): tagTab = buff.get_tag_table() tagByNm = tagTab.lookup(tag) if tagByNm: tag = tagByNm elif hasattr(ui, tag): tag = getattr(ui, tag) else: tag = None if not (isinstance(tag, Gtk.TextTag)): buff.insert(end, text) return buff.insert_with_tags(end, text, tag) def _lp(ui, ls_txt, short_path=True): for idx, txt_obj in enumerate(ls_txt): if isinstance(txt_obj, str): ui._p(txt_obj, short_path=short_path) elif isinstance(txt_obj, tuple) and len(txt_obj) == 2: ui._p(txt_obj[0], tag=txt_obj[1], short_path=short_path) else: raise TypeError(f"Unknown format in {ls_txt}[{idx}]") def restoreGeometry(ui): for ui_attr in dDialogs.keys(): dlg_cfg_nm = f"dlg{ui_attr.capitalize()}Pos" if hasattr(ui, ui_attr) and (ui.cfg[dlg_cfg_nm]): dlg_inst = getattr(ui, ui_attr) dlg_inst.pos = tuple( int(k) for k in ui.cfg[dlg_cfg_nm].split(',')) ui.setTxtWinGeometry(ui.mainWindow, ui.cfg['MainWindowGeometry']) def storeGeometry(ui): for ui_attr in dDialogs.keys(): if hasattr(ui, ui_attr): dlg_inst, dlg_cfg_nm = getattr( ui, ui_attr), f"dlg{ui_attr.capitalize()}Pos" if hasattr(dlg_inst, 'dlgHide'): dlg_inst.dlgHide() if dlg_inst.pos: x, y = dlg_inst.pos ui.cfg[dlg_cfg_nm] = f"{x:d},{y:d}" ui.cfg['MainWindowGeometry'] = ui.getTxtWinGeometry(ui.mainWindow) def getWinGeometry(ui, win): pos = win.get_position() size = win.get_size() return pos.root_x, pos.root_y, size.width, size.height def getTxtWinGeometry(ui, win): geo = ui.getWinGeometry(win) txtGeo = ','.join(map(lambda i: f"{i}", geo)) dlgName = win.get_title() _d(f"Current Window „{dlgName}” geometry: {txtGeo}\n") return txtGeo def setWinGeometry_timed(ui, win, geo): _d(f"Repositioning Window: „{win.get_title()}” to:\n") _d(f"pos: x:{geo[0]}, y:{ geo[1]}\n") _d(f"size: w:{geo[2]}, h:{geo[3]}\n") gdw = win.get_window() gdw.move_resize(*geo) return False # run only once def setWinGeometry(ui, win, geo): addIdle(ui.setWinGeometry_timed, win, geo) def setTxtWinGeometry(ui, win, txtGeo): geo = tuple(map(int, txtGeo.split(','))) if txtGeo else tuple() if len(geo) == 4: ui.setWinGeometry(win, geo) else: _d(f"Strange geo situation:{geo}\n")
def show(self): self.window.show_all() if gtk.main_level() == 0: gtk.main()
def show_window(self): self.window.show_all() Gtk.main()
def __init__(self): # Use Glade Template builder = Gtk.Builder() builder.add_from_file("template/player.glade") # Initialize Player Backend self.player = Player() self.player.cust_func = self.cust_func # Changing the custom function to use when media ends or reports error # adding gtksink to pipeline for video output self.gtksink = Gst.ElementFactory.make("gtksink") self.player.playbin.set_property("video-sink", self.gtksink) # search for the widget with id # main window window = builder.get_object("window") # buttons self.playBtn = builder.get_object("playBtn") chooserBtn = builder.get_object("chooserBtn") stopBtn = builder.get_object("stopBtn") nextBtn = builder.get_object("nextBtn") prevBtn = builder.get_object("prevBtn") # playlist self.playlistBox = builder.get_object("playlist") # headerbar self.headerBar = builder.get_object("headerBar") # PlayArea playArea = builder.get_object("playArea") playArea.add(self.gtksink.props.widget) self.gtksink.props.widget.set_hexpand(True) self.gtksink.props.widget.set_vexpand(True) # slider seeker self.seeker = builder.get_object("seeker") self.durationText = builder.get_object("duration") self.volumeBar = builder.get_object("volume") self.volumeBar.set_value(self.player.getVolume()) # icons self.playIco = builder.get_object("playIco") self.pauseIco = builder.get_object("pauseIco") # UI window.set_title("PyGObject Player") # Connect Signals Here # window signals window.connect("destroy", self.onDestroy) # button signals self.playBtn.connect("clicked", self.onPlay) nextBtn.connect("clicked", self.onNext) prevBtn.connect("clicked", self.onPrev) stopBtn.connect("clicked", self.onStop) self.volumeBar.connect("value-changed", self.changeVolume) chooserBtn.connect("clicked", self.onChooseClick) self.playlistBox.connect("row-activated", self.onSelectionActivated) self.sliderHandlerId = self.seeker.connect("value-changed", self.onSliderSeek) # used for connecting video to application (Not Used as of now) self.player.bus.enable_sync_message_emission() self.player.bus.connect("sync-message::element", self.onSyncMessage) # show window and initialize player gui window.show() Gtk.main()
def create_ui(win): win.ui_running.value = 1 win.connect("delete-event", win.on_quit) win.show_all() Gtk.main()
def test_gl_client_window(gl_client_window_class, max_window_size=(1024, 1024), pixel_depth=24, show=False): #try to render using a temporary window: draw_result = {} window = None try: x, y = -100, -100 if show: x, y = 100, 100 w, h = 250, 250 from xpra.codecs.loader import load_codec load_codec("dec_pillow") from xpra.client.window_border import WindowBorder border = WindowBorder() default_cursor_data = None noclient = FakeClient() #test with alpha, but not on win32 #because we can't do alpha on win32 with opengl metadata = typedict({b"has-alpha": not WIN32}) window = gl_client_window_class(noclient, None, None, 2**32 - 1, x, y, w, h, w, h, metadata, False, typedict({}), border, max_window_size, default_cursor_data, pixel_depth) window_backing = window._backing window_backing.idle_add = no_idle_add window_backing.timeout_add = no_timeout_add window_backing.source_remove = no_source_remove window.realize() window_backing.paint_screen = True pixel_format = "BGRX" bpp = len(pixel_format) options = typedict({"pixel_format": pixel_format}) stride = bpp * w coding = "rgb32" widget = window_backing._backing widget.realize() def paint_callback(success, message=""): log("paint_callback(%s, %s)", success, message) draw_result["success"] = success if message: draw_result["message"] = message.replace("\n", " ") log("OpenGL: testing draw on %s widget %s with %s : %s", window, widget, coding, pixel_format) pix = AtomicInteger(0x7f) REPAINT_DELAY = envint("XPRA_REPAINT_DELAY", int(show) * 16) gl_icon = get_icon_filename("opengl", ext="png") icon_data = None if os.path.exists(gl_icon): from PIL import Image img = Image.open(gl_icon) img.load() icon_w, icon_h = img.size icon_stride = icon_w * 4 noalpha = Image.new("RGB", img.size, (255, 255, 255)) noalpha.paste(img, mask=img.split()[3]) # 3 is the alpha channel buf = BytesIO() noalpha.save(buf, format="JPEG") icon_data = buf.getvalue() buf.close() icon_format = "jpeg" if not icon_data: icon_w = 32 icon_h = 32 icon_stride = icon_w * 4 icon_data = bytes([0]) * icon_stride * icon_h icon_format = "rgb32" def draw(): v = pix.increase() img_data = bytes([v % 256] * stride * h) options["flush"] = 1 window.draw_region(0, 0, w, h, coding, img_data, stride, v, options, [paint_callback]) options["flush"] = 0 mx = w // 2 - icon_w // 2 my = h // 2 - icon_h // 2 x = iround(mx * (1 + sin(v / 100))) y = iround(my * (1 + cos(v / 100))) window.draw_region(x, y, icon_w, icon_h, icon_format, icon_data, icon_stride, v, options, [paint_callback]) return REPAINT_DELAY > 0 #the paint code is actually synchronous here, #so we can check the present_fbo() result: if show: widget.show() window.show() from gi.repository import Gtk, GLib def window_close_event(*_args): Gtk.main_quit() noclient.window_close_event = window_close_event GLib.timeout_add(REPAINT_DELAY, draw) Gtk.main() else: draw() if window_backing.last_present_fbo_error: return { "success": False, "message": "failed to present FBO on screen: %s" % window_backing.last_present_fbo_error } finally: if window: window.destroy() log("test_gl_client_window(..) draw_result=%s", draw_result) return draw_result
def mainLoop(self): Gtk.main()