def __init__(self): # initialize GTK Gtk.init(sys.argv) # initialize GStreamer Gst.init(sys.argv) self.state = Gst.State.NULL self.duration = Gst.CLOCK_TIME_NONE self.playbin = Gst.ElementFactory.make("playbin", "playbin") if not self.playbin: print("ERROR: Could not create playbin.") sys.exit(1) # set up URI self.playbin.set_property( "uri", "http://docs.gstreamer.com/media/sintel_trailer-480p.webm") # connect to interesting signals in playbin self.playbin.connect("video-tags-changed", self.on_tags_changed) self.playbin.connect("audio-tags-changed", self.on_tags_changed) self.playbin.connect("text-tags-changed", self.on_tags_changed) # create the GUI self.build_ui() # instruct the bus to emit signals for each received message # and connect to the interesting signals bus = self.playbin.get_bus() bus.add_signal_watch() bus.connect("message::error", self.on_error) bus.connect("message::eos", self.on_eos) bus.connect("message::state-changed", self.on_state_changed) bus.connect("message::application", self.on_application_message)
def run_main(args=sys.argv): Gtk.init() converter = ConverterWindow() for path in args[1:]: if os.path.isfile(path): converter.add_level(path) converter.refresh_levels_view() Gtk.main()
def main(argv): # No arg list, pass out help if len(argv) == 0: printHelp() sys.exit(2) buff = 20 try: opts, args = getopt.getopt(argv,"hudlrb:v") except getopt.GetoptError as err: printHelp() sys.exit(2) direction = "" verbose = False for opt, arg in opts: if opt == "-h": printHelp() sys.exit() elif opt == "-u": direction = "UP" elif opt == "-d": direction = "DOWN" elif opt == "-l": direction = "LEFT" elif opt == "-r": direction = "RIGHT" elif opt == "-b": buff = int(arg) elif opt == "-v": verbose = True # Grab window list and geo Gtk.init([]) # necessary if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation window_list = screen.get_windows() active_window = screen.get_active_window() workspace_id = screen.get_active_workspace().get_number() if len(window_list) > 0: window = findWindow( direction, window_list, workspace_id, active_window, buff, verbose ) else: print( "Empty window list!" ) sys.exit(2) if window != None: now = GdkX11.x11_get_server_time(Gdk.get_default_root_window()) window.activate(now) window = None screen = None Wnck.shutdown()
def run(self, args): Gtk.init (args) try: self.builder = Gtk.Builder () self.builder.add_from_file ("diagram.ui") btn = self.builder.get_object("btnGoBack") btn.connect("clicked", self.loadSplash) btn = self.builder.get_object("btnNew") btn.connect("clicked", self.loadNewView) btn = self.builder.get_object("btnCreateDocument") btn.connect("clicked", self.newDocument) # Load Templates self.templateStore = Gtk.ListStore(str, str, GdkPixbuf.Pixbuf) self.templateIconView = self.builder.get_object("iconviewTemplates") self.templateIconView.set_model(self.templateStore) self.templateIconView.set_text_column(0) self.templateIconView.set_pixbuf_column(2) self.templateIconView.connect("selection-changed", self.templateSelectedChanged) global doctypes for doc in doctypes: self.templateStore.append([ doctypes[doc].title, doc, GdkPixbuf.Pixbuf.new_from_file(doctypes[doc].image) ]) # Document UI Setup self.xSheets = self.builder.get_object("sheets") self.xSheets.connect("switch-page", self.changeSheet) l = Gtk.Image() l.set_from_stock("gtk-add", Gtk.IconSize.MENU) c = Gtk.Label("Nothing to see here") l.show() c.show() self.xSheets.insert_page(c, l, -1) self.toolsView = self.builder.get_object("ivTools") self.shapeStore = Gtk.ListStore(str, str, GdkPixbuf.Pixbuf) self.toolsView.set_model(self.shapeStore) self.toolsView.set_text_column(0) self.toolsView.set_pixbuf_column(2) self.toolsView.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY) self.toolsView.drag_source_add_text_targets() self.toolsView.connect("drag-data-get", self.shapeDragData ) self.window = self.builder.get_object ("window") self.window.show_all () prop = self.builder.get_object("boxProperties") prop.hide() self.window.connect("destroy",Gtk.main_quit) self.loadSplash() Gtk.main () except Exception as e: print "Could not load UI: ", e, sys.exc_info() traceback.print_exc()
def main(argv): Gtk.init() GLib.set_prgname(PRGNAME) GLib.set_application_name(PRGTITLE) indicator = ModeIndicator() indicator.build_menu() Gtk.main() return 0
def __init__(self, title): self.title = title Gtk.init([]) # necessary only if not using a Gtk.main() loop self.window_handle = [] self.window_handle.append(self.linux_get_windows_bytitle(self.title)) w = self.window_handle[0]
def test_client_initialization(self): find.data_path_append('data/client') os.environ['KING_PHISHER_GLADE_FILE'] = 'KingPhisherClient.glade' self.assertTrue(isinstance(gui_utilities.which_glade(os.environ['KING_PHISHER_GLADE_FILE']), (str, unicode))) try: Gtk.init(sys.argv) main_window = KingPhisherClient() main_window.set_position(Gtk.WindowPosition.CENTER) except Exception as error: self.fail("failed to initialize KingPhisherClient (error: {0})".format(error.__class__.__name__))
def __init__(self, *args, **kwds): self.move_queue = Queue() GObject.threads_init() Gdk.threads_init() Gtk.init(sys.argv) Gdk.threads_enter() super(HumanClient, self).__init__(*args, **kwds) Gdk.threads_leave()
def main(): Gtk.init() window = Gtk.Window() window.set_default_size(500, 500) swin = Gtk.ScrolledWindow() swin.add(view) window.add(swin) window.connect("destroy", close) window.show_all() Gtk.main()
def __init__(self, app_id): """Init the client with given imgur application id. :param app_id imgur application id """ Client.__init__(self, app_id) # Initialize libnotify Gtk.init() if not Notify.init(__appname__): self._show_message("error", "unable to initialize libnotify")
def main(): Gtk.init() view = WebKit2.WebView() view.load_uri("http://google.com") window = Gtk.Window() window.add(view) window.connect("destroy", close) window.show_all() Gtk.main()
def __init__(self): Gtk.init([]) Gst.init([]) width, height = 1280, 720 self.aspect = width/height self.gl_init = False self.meshes = {} self.cairo_texture_id = None pipeline = Gst.Pipeline() src = Gst.ElementFactory.make("videotestsrc", None) sink = Gst.ElementFactory.make("glimagesink", None) if not sink or not src: print("GL elements not available.") exit() self.shaders = {} caps = Gst.Caps.from_string("video/x-raw, width=%d, height=%d" % (width, height)) cf = Gst.ElementFactory.make("capsfilter") cf.set_property("caps", caps) pipeline.add(src, cf, sink) src.link(cf) cf.link(sink) window = Gtk.Window() window.connect("delete-event", self.window_closed, pipeline) window.set_default_size(width, height) window.set_title("Hello Cairo, OpenGL and GLSink!") sink.connect("client-draw", self.draw) sink.connect("client-reshape", self.reshape) drawing_area = Gtk.DrawingArea() drawing_area.set_double_buffered(True) window.add(drawing_area) window.show_all() xid = drawing_area.get_window().get_xid() sink.set_window_handle(xid) if pipeline.set_state(Gst.State.PLAYING) == Gst.StateChangeReturn.FAILURE: pipeline.set_state(Gst.State.NULL) else: Gtk.main()
def main(self): Gtk.init(sys.argv) window = Gtk.Window() window.resize(1000, 800) window.set_title("Webkit tests window") # Window's title window.move(100, 100) window.connect('destroy', lambda x: Gtk.main_quit()) # Connect signal 'destroy' #window.set_decorated(False) self.screen = window.get_screen() self.visual = self.screen.get_rgba_visual() if self.visual and self.screen.is_composited(): window.set_visual(self.visual) window.set_app_paintable(True) window.connect("draw", area_draw) box = Gtk.VBox() box.set_margin_top(30) box.set_margin_bottom(30) box.set_margin_left(30) box.set_margin_right(30) make_transparent(box) window.add(box) folder = '/d/Pics/Wallpapers/Favorites/' images = sorted(os.path.join(folder, f) for f in os.listdir(folder) if f.endswith('.jpg')) self.current = images[100] self.web_view = WebKit.WebView() self.web_view.set_transparent(True) make_transparent(self.web_view) self.web_view.set_can_focus(True) self.web_view.load_string("<html><body style='background: rgba(0, 0, 0, 0); color: white;'><img id='i' src='data:image/png;base64," + b64(self.current) + "'/></body></html>", "text/html", "UTF-8", "file://" + os.path.dirname(__file__) + "/") self.scroll = Gtk.ScrolledWindow() self.scroll.add_with_viewport(self.web_view) make_transparent(self.scroll.get_child()) box.add(self.scroll) window.show_all() def go(*args): self.current = images[(images.index(self.current) + 1) % len(images)] nextt = b64(self.current) self.web_view.execute_script("document.getElementById('i').setAttribute('src', 'data:image/png;base64," + nextt + "')") # self.web_view.execute_script("document.getElementById('i').setAttribute('src', '" + self.current + "')") window.connect('button-press-event', go) Gtk.main() # Start the application
def get_code(self, login_hint): s=string.lowercase + string.uppercase + string.digits state = ''.join(random.sample(s,10)) args = { "response_type": "code", "client_id": self.client_id, "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", "prompt": "consent", #"scope": "openid email https://mail.google.com/", "scope": self.scope, "state": state, "login_hint": login_hint } code_url= "%s?%s" % (self.auth_endpoint, urllib.urlencode(args)) saveout = os.dup(1) os.close(1) os.open(os.devnull, os.O_RDWR) saveout2 = os.dup(2) os.close(2) os.open(os.devnull, os.O_RDWR) try: browser().open(code_url, 1, True) finally: os.dup2(saveout, 1) os.dup2(saveout2, 2) now = time.time() code = None while True: # Look for the state and code in the window title output = subprocess.check_output("xwininfo -root -tree".split()) m = re.search("state=%s.code=([^ ]+)" % state, output) if m: code = m.group(1) break if time.time() - now > 120: raise GGError(_("Timeout getting OAuth authentication")) time.sleep(0.1) Gtk.init([]) screen = Wnck.Screen.get_default() screen.force_update() for win in screen.get_windows(): if re.search(state, win.get_name()): win.close(time.time()) return code
def main(): Gtk.init() win = Gtk.Window() win.connect('destroy', Gtk.main_quit) win.show() hwnd = ctypes.WinDLL('libgdk-3-0.dll').gdk_win32_window_get_handle( hash(win.get_window())) winmmtaskbar.create_buttons(hwnd, "Previous", "Play", "Pause", "Next", callback, hwnd) Gtk.main()
def main (): global valid if len(sys.argv) != 3: print "Usage: %s inputFile outputFile" %sys.argv[0] sys.exit (1) ifile = codecs.open (sys.argv[1], 'r', encoding='utf-8') words = ifile.readlines () ifile.close () with codecs.open (sys.argv[2], 'r', encoding='utf-8') as ofile: for line in (l.strip() for l in ofile): valid.append (line) valid.sort () existings = { x : True for x in valid } #ofile = codecs.open (sys.argv[2], 'a', encoding='utf-8') model = Gtk.ListStore (int, str, str) for k, iline in enumerate(l.strip() for l in words): if iline in existings: model.append ([k, iline, Gtk.STOCK_OK]) else: model.append ([k, iline, None]) treeview = Gtk.TreeView (model) renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn("#", renderer, text=0) treeview.append_column(column) renderer = Gtk.CellRendererPixbuf () column = Gtk.TreeViewColumn ("Status", renderer,icon_name=2) #column.set_sizing (Gtk.TreeViewColumnSizing.FIXED) treeview.append_column(column) renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn("Word", renderer, text=1) treeview.append_column(column) scroll = Gtk.ScrolledWindow () scroll.add (treeview) window = Gtk.Window () window.add (scroll) window.set_default_size (400, 600) window.set_border_width (5) window.show_all () window.connect ("delete-event", on_quit, None) treeview.connect ("row-activated", on_row_activated, model) Gtk.init (sys.argv) Gtk.main ()
def main(): """Entry point of chrandr.""" try: current_version = pkg_resources.get_distribution('chrandr').version except pkg_resources.DistributionNotFound: current_version = 'dev' # command line arguments parser = argparse.ArgumentParser( description="Change screen configuration." ) parser.add_argument('--version', action='version', version="%(prog)s " + current_version) parser.add_argument('--verbose', help="verbose output messages", action='store_true') parser.add_argument('--config', help="set the configuration file") args = parser.parse_args() # configure logging _configure_logging(args) logger = logging.getLogger(__name__) # restore default signal handler on SIGINT # see also : https://bugzilla.gnome.org/show_bug.cgi?id=622084 signal.signal(signal.SIGINT, signal.SIG_DFL) if args.config is None: config_filename = chrandr.config.DEFAULT_CONFIGURATION_FILENAME if not os.path.exists(config_filename): logger.info("Create default configuration file: %s", config_filename) try: chrandr.config.create_default_configuration(config_filename) except Exception as e: logger.error("Failed to create default configuration", exc_info=True) sys.stderr.write(sys.argv[0] + ": Failed to create the configuration file : " + str(e) + "\n") sys.exit(1) else: config_filename = os.path.expanduser(args.config) config = ChrandrConfig(config_filename) try: config.load() except FileNotFoundError as e: sys.stderr.write(sys.argv[0] + ": Failed to open the configuration file : " + str(e) + "\n") sys.exit(1) # initialize GTK, create and open the window Gtk.init() ui = ChRandrSimpleUI(config) # first refresh of availables configurations GObject.idle_add(lambda ui:ui.on_click_refresh(), ui) ui.window.show_all() Gtk.main()
def __init__(self, argv): """ Initialize the application. Call methods that initialize application stage, style and global sound effects player. :param: argv application arguments """ super().__init__() Gtk.init(sys.argv) Clutter.init(sys.argv) self._configure() self._initialize_style() self._initialize_window(argv) self._initialize_sound_effects_player()
def find_spotify_window(self): "Libwnck list of currently open windows." Gtk.init([]) # Get the current screen. screen = Wnck.Screen.get_default() # recommended per Wnck documentation screen.force_update() # Object list of windows in screen. windows = screen.get_windows() # Return the Spotify window or an empty list. return [win.get_icon_name() for win in windows\ if len(windows) and "Spotify" in win.get_application().get_name()]
def __init__(self, options): self.storepath=os.path.expanduser(options.storepath) self.conn = sqlite3.connect(self.storepath) self.dbcursor = self.conn.cursor() self.initialise_database() self.records = [] self.lastsave = datetime.now() Gtk.init([]) # necessary if not using a Gtk.main() loop self.screen = Wnck.Screen.get_default() self.screen.force_update() # recommended per Wnck documentation self.cur_win = 'Unknown window' self.set_current_window()
def selectCharacterWindow(window_to_select): """Select the characters window.""" Gtk.init([]) # necessary only if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation # loop all windows for window in screen.get_windows(): if window.get_name() == window_to_select: print ' - Getting window %s info' % window_to_select window.get(window.get_xid()) print ' - Activating window %s' % window_to_select window.activate(int(time.time())) print ' - Setting window %s fullscreen' % window_to_select window.set_fullscreen(True) # clean up Wnck (saves resources, check documentation) window = None screen = None Wnck.shutdown()
def run_browser(): from gi.repository import Gtk, Gdk, WebKit Gtk.init(sys.argv) #self.ebview.go_back() #self.webview.goforward() win = Gtk.Window() scrolled_window = Gtk.ScrolledWindow() webview = WebKit.WebView() scrolled_window.add(webview) win.add(scrolled_window) win.set_title('MULTSUM') win.connect("delete-event", Gtk.main_quit) #self.webview.show() #scrolled_window.show() win.show_all() webview.load_uri('http://localhost:%s/'%(str(port_number))) win.resize(1000, 800) #browser = Browser() Gtk.main()
def __init__(self): Gtk.init(sys.argv) # Set up plot self.plot = Plot(self) # Load UI from glade file and set up signals self.ui = Gtk.Builder() self.ui.add_from_file(self.UI_FILE) self.window_main = self.ui.get_object("window_main") self.window_main.show_all() self.window_main.connect("delete-event", self.quit) self.window_main.connect("destroy", self.quit) self.btn_quit = self.ui.get_object("btn_quit") self.btn_quit.connect("clicked", self.quit) self.lbl_status = self.ui.get_object("lbl_status") self.box_buoys = self.ui.get_object("box_buoys") # Load buoys for b in buoys: bw = BuoyWidget(self, b) self.buoywidgets.append(bw) self.box_buoys.pack_start(bw.frame, True, True, 3) self.currentbuoy = self.buoywidgets[0] self.currentbuoy.sw_monitor.set_active(True) self.sw_plot = self.ui.get_object("sw_plot") self.sw_plot.connect("notify::active", self.sw_plot_active) # Thread for GTK self.gtkt = Thread(target=self.gtktl)
def main(): for opt in sys.argv[1:]: if opt in ('-h', '--help'): usage() return 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 #g_thread_init has been deprecated since version 2.32 if GLib.check_version(2, 32, 0): GObject.threads_init() Gdk.threads_init() Gtk.init(None) config.init(); agent.app = Hotot() Gdk.threads_enter() Gtk.main() Gdk.threads_leave()
def __init__(self): self.debugger = MiDebugger() self.startup_info = StartupInfo() self.main_window = MainWindow(self) Gtk.init()
def import_gtk3(): gi_gtk() from gi.repository import Gtk #@UnresolvedImport try_import_GdkX11() Gtk.init() return Gtk
def main(self): Gtk.init(sys.argv) window = Gtk.Window() window.resize(800, 600) window.set_title("Webkit tests window") # Window's title window.move(100, 100) window.connect('destroy', lambda x: Gtk.main_quit()) # Connect signal 'destroy' #window.set_decorated(False) self.screen = window.get_screen() self.visual = self.screen.get_rgba_visual() if self.visual and self.screen.is_composited(): window.set_visual(self.visual) window.set_app_paintable(True) window.connect("draw", area_draw) box = Gtk.VBox() box.set_margin_top(30) box.set_margin_bottom(30) box.set_margin_left(30) box.set_margin_right(30) make_transparent(box) window.add(box) folder = '/d/Pics/Wallpapers/' images = sorted(os.path.join(folder, f) for f in os.listdir(folder) if f.endswith('.jpg')) self.current = images[0] self.image = Gtk.Image() pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(self.current, 800, 600, True) self.image.set_from_pixbuf(pixbuf) self.web_view = WebKit.WebView() self.web_view.set_transparent(True) make_transparent(self.web_view) self.web_view.set_can_focus(True) def f(mimetype, uri, param, data): # Things crash here because Python GTK bindings do not support GHashTable return self.image self.web_view.connect('create-plugin-widget', f) self.web_view.load_string( "<html><body style='background: rgba(0, 0, 0, 0); color: white;'>" "<object type='image/x-image' src='current-image'/>" "</body></html>", "text/html", "UTF-8", "file://" + os.path.dirname(__file__) + "/") box.add(self.web_view) window.show_all() # # def go(*args): # self.current = images[(images.index(self.current) + 1) % len(images)] # pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(self.current, 800, 600, True) # self.image.set_from_pixbuf(pixbuf) # nextt = b64(self.current) # self.web_view.execute_script("document.getElementById('i').setAttribute('src', 'data:image/png;base64," + nextt + "')") # # self.web_view.execute_script("document.getElementById('i').setAttribute('src', '" + self.current + "')") # # window.connect('button-press-event', go) Gtk.main() # Start the application
WebKit.WebPolicyDecision.ignore(decision) webbrowser.open(uri) self.setButtons() return False def quit(self,*args): if standalone: Gtk.main_quit() else: self.window.destroy() if __name__ == "__main__": path=os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))) os.chdir(path) standalone = True docs = None if len(sys.argv) > 1: docs = sys.argv[1] if not docs.startswith('http'): docs = os.path.abspath(docs) docs = 'file://'+docs title = 'Help Browser' elif 'viewdocs' in sys.argv[0]: docs = 'file://'+os.path.abspath('htmldocs/index.html') title = 'Help Viewer' if docs: Gtk.init() b = browserDoc(winicon=True,wintitle=title, input=docs, home_uri=docs) Gtk.main()
def main(self): Gtk.init(sys.argv) window = Gtk.Window() window.resize(800, 600) window.set_title("Webkit tests window") # Window's title window.move(100, 100) window.connect('destroy', lambda x: Gtk.main_quit()) # Connect signal 'destroy' #window.set_decorated(False) self.screen = window.get_screen() self.visual = self.screen.get_rgba_visual() if self.visual and self.screen.is_composited(): window.set_visual(self.visual) window.set_app_paintable(True) window.connect("draw", area_draw) box = Gtk.VBox() box.set_margin_top(30) box.set_margin_bottom(30) box.set_margin_left(30) box.set_margin_right(30) make_transparent(box) window.add(box) folder = '/d/Pics/Wallpapers/' images = sorted( os.path.join(folder, f) for f in os.listdir(folder) if f.endswith('.jpg')) self.current = images[0] self.image = Gtk.Image() pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale( self.current, 800, 600, True) self.image.set_from_pixbuf(pixbuf) self.web_view = WebKit.WebView() self.web_view.set_transparent(True) make_transparent(self.web_view) self.web_view.set_can_focus(True) def f( mimetype, uri, param, data ): # Things crash here because Python GTK bindings do not support GHashTable return self.image self.web_view.connect('create-plugin-widget', f) self.web_view.load_string( "<html><body style='background: rgba(0, 0, 0, 0); color: white;'>" "<object type='image/x-image' src='current-image'/>" "</body></html>", "text/html", "UTF-8", "file://" + os.path.dirname(__file__) + "/") box.add(self.web_view) window.show_all() # # def go(*args): # self.current = images[(images.index(self.current) + 1) % len(images)] # pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(self.current, 800, 600, True) # self.image.set_from_pixbuf(pixbuf) # nextt = b64(self.current) # self.web_view.execute_script("document.getElementById('i').setAttribute('src', 'data:image/png;base64," + nextt + "')") # # self.web_view.execute_script("document.getElementById('i').setAttribute('src', '" + self.current + "')") # # window.connect('button-press-event', go) Gtk.main() # Start the application
def getActiveWindow_Linux(): try: import wnck except ImportError: if DEBUG is not None: print("wnck is not installed") wnck = None if wnck is not None: #TRY WITH WNCK screen = wnck.screen_get_default() # Recommended per wnck documentation screen.force_update() window = screen.get_active_window() if window is not None: return psutil.Process(window.get_pid()).name() else: try: import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk, Wnck G = "Installed" except ImportError: if DEBUG is not None: print("gi.repository not installed") G = None if G is not None: #TRY WITH GTK WNCK # Necessary if not using a Gtk.main() loop Gtk.init([]) screen = Wnck.Screen.get_default() # Recommended per Wnck documentation screen.force_update() active_window = screen.get_active_window() pid = active_window.get_pid() return psutil.Process(pid).name() else: try: from ewmh import EWMH ewmh = EWMH() except ImportError: if DEBUG is not None: print("EWMH not installed") ewmh = None if ewmh is not None: #TRY WITH EXTENDED XLib win = ewmh.getActiveWindow() return psutil.Process(ewmh.getWmPid(win)).name() else: try: import Xlib.display X = "Installed" except ImportError: X = None if X is not None: #TRY WITH Xlib (different result) display = Xlib.display.Display() window = display.get_input_focus().focus pid = window.get_wm_pid wmname = window.get_wm_name() wmclass = window.get_wm_class() if wmclass is None and wmname is None: window = window.query_tree().parent wmname = window.get_wm_name() return wmname #If nothing happened return None
#!/usr/bin/env python3 import sys import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk from os.path import abspath from signal import signal, SIGINT, SIG_DFL from htmlDE import settings from htmlDE.pluginmanager import load_plugins from htmlDE.windows import BackgroundWindow, PanelWindow if __name__ == "__main__": Gtk.init(sys.argv) settings.setup() for window in settings.windows: window.show_all() signal(SIGINT, SIG_DFL) Gtk.main()
#!/usr/bin/env python3 """Entrypoint for UI.""" import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GLib from . import settings from .css import get_css_provider from .file import init_tlp_file_config from .mainui import create_main_box, store_window_size, window_key_events, close_main_window Gtk.init() Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), get_css_provider(), Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION ) # Set window properties GLib.set_prgname('tlp-ui') Gdk.set_program_class('Tlp-UI') # Apply custom scalable icons to icon theme Gtk.IconTheme().get_default().append_search_path(settings.icondir + 'themeable') def main() -> None: """Initiate main window with all sub elements.""" # init configuration settings init_tlp_file_config()
#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') gi.require_version('Wnck', '3.0') from gi.repository import GLib, Gtk, Wnck def on_window_opened(screen, window): if window.get_class_group_name() == 'Mousepad': #https://lazka.github.io/pgi-docs/index.html#Wnck-3.0/classes/Window.html#Wnck.Window.move_to_workspace #https://lazka.github.io/pgi-docs/index.html#Wnck-3.0/classes/Screen.html#Wnck.Screen.get_workspace window.move_to_workspace(window.get_screen().get_workspace(0)) loop.quit() # https://lazka.github.io/pgi-docs/index.html#GLib-2.0/classes/MainLoop.html#GLib.MainLoop.quit if __name__ == '__main__': # https://lazka.github.io/pgi-docs/index.html#Gtk-3.0/functions.html#Gtk.init # https://lazka.github.io/pgi-docs/index.html#Gdk-3.0/functions.html#Gdk.init Gtk.init(None); screen = Wnck.Screen.get_default() # https://lazka.github.io/pgi-docs/index.html#Wnck-3.0/classes/Screen.html#Wnck.Screen.get_default screen.connect('window-opened', on_window_opened) # https://lazka.github.io/pgi-docs/index.html#Wnck-3.0/classes/Screen.html#Wnck.Screen.signals.window_opened loop = GLib.MainLoop(None) # https://lazka.github.io/pgi-docs/index.html#GLib-2.0/classes/MainLoop.html#GLib.MainLoop loop.run()
if 'PlayerState' in data: state = data['PlayerState'] self.log.info("PlayerState: %s", state) if state == "Stopped": self._stop_timer() elif state == "Playing": self._start_timer() elif state == "Paused": pass if interface == "org.gnome.ShairportSync": if "Active" in data: if data["Active"]: self.log.info("device connected") self._initialize_display() else: self.log.info("device disconnected") self._clear_display() if (__name__ == "__main__"): Gtk.init(None) client = ShairportSyncClient() signal.signal(signal.SIGINT, lambda *args: client.quit()) Gtk.main()
if self.gst_state == Gst.State.PAUSED: pad = self.gst_src.emit('get-video-pad', 0) response = pad.get_current_caps().get_structure(0).get_fraction( 'framerate') self.framerate = float(response[1]) / float(response[2]) if self.gst_state == Gst.State.PLAYING: self.update_video_margin() def on_sync_message(self, bus, message): struct = message.get_structure() if not struct: return message_name = struct.get_name() if message_name == 'prepare-window-handle': message.src.set_property('force-aspect-ratio', True) message.src.set_window_handle(self.video_window_xid) if __name__ == '__main__': GObject.threads_init() Gtk.init(sys.argv) Gst.init(sys.argv) # Gst.debug_set_active(True) # Gst.debug_set_default_threshold(3) Main() Gtk.main()
class Window(Wnck.Window): def __init__(self): super().__init__() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): screen = None Wnck.shutdown() def getName(self): return self.get_name() def getGeometry(self): return self.get_geometry() def setGeometry(self, x, y): self.set_geometry('+{}+{}'.format(x, y)) def center(self): self.setPosition(100, 200) Gtk.init([]) screen = Wnck.Screen.get_default() screen.force_update() wnd = screen.get_active_window() wnd.__class__ = Window
def __init__(self): # initialize GTK Gtk.init(sys.argv) # initialize GStreamer Gst.init(sys.argv) self.state = Gst.State.NULL self.duration = Gst.CLOCK_TIME_NONE self.playbin = Gst.ElementFactory.make("playbin", "playbin") if not self.playbin: print("ERROR: Could not create playbin.") sys.exit(1) # set up URI self.playbin.set_property( "uri", "file:///Users/kemal/WorkSpace/Videowall Development/media/pixar.mp4") # aşağıdaki kod ile bin içerisine time overlay ekledik. bin = Gst.Bin.new("my-bin") timeoverlay = Gst.ElementFactory.make("timeoverlay") timeoverlay.set_property("text", "GNUTV") timeoverlay.set_property("font-desc", "normal 24") bin.add(timeoverlay) # # # timeoverlay_pad = timeoverlay.get_static_pad("video_sink") # timeoverlay_ghostpad = Gst.GhostPad.new("sink_1", timeoverlay_pad) # bin.add_pad(timeoverlay_ghostpad) queue = Gst.ElementFactory.make("queue") bin.add(queue) timeoverlay_pad = queue.get_static_pad("sink") timeoverlay_ghostpad = Gst.GhostPad.new("sink", timeoverlay_pad) bin.add_pad(timeoverlay_ghostpad) videoscale = Gst.ElementFactory.make("videoscale") videoscale.set_property("method", 1) bin.add(videoscale) # videoscale_pad = videoscale.get_static_pad("sink") # videoscale_ghostpad = Gst.GhostPad.new("sink_2", videoscale_pad) # bin.add_pad(videoscale_ghostpad) caps = Gst.Caps.from_string("video/x-raw, width=3840, height=2160") filter = Gst.ElementFactory.make("capsfilter", "filter") filter.set_property("caps", caps) bin.add(filter) videobox = Gst.ElementFactory.make("videobox") videobox.set_property("bottom", 1080) videobox.set_property("top", 0) videobox.set_property("left", 100) videobox.set_property("right", 1920) bin.add(videobox) # filter_pad = filter.get_static_pad("sink") # filter_ghostpad = Gst.GhostPad.new("sink_3", filter_pad) # bin.add_pad(filter_ghostpad) conv = Gst.ElementFactory.make("videoconvert", "conv") bin.add(conv) # conv_pad = conv.get_static_pad("sink") # conv_ghostpad = Gst.GhostPad.new("sink_4", conv_pad) # bin.add_pad(conv_ghostpad) videosink = Gst.ElementFactory.make("autovideosink") bin.add(videosink) queue.link(videoscale) videoscale.link(filter) filter.link(videobox) videobox.link(conv) conv.link(timeoverlay) timeoverlay.link(videosink) self.playbin.set_property("video-sink", bin) # # self.bin = Gst.Bin.new("my-bin") # videoscale = Gst.ElementFactory.make("videoscale") # videoscale.set_property("method", 1) # pad = videoscale.get_static_pad("sink") # ghostpad = Gst.GhostPad.new("sink", pad) # self.bin.add_pad(ghostpad) # caps = Gst.Caps.from_string("video/x-raw, width=720") # filter = Gst.ElementFactory.make("capsfilter", "filter") # filter.set_property("caps", caps) # textoverlay = Gst.ElementFactory.make('textoverlay') # textoverlay.set_property("text", "GNUTV") # textoverlay.set_property("font-desc", "normal 14") # # TypeError: object of type `GstTextOverlay' does not have property `halign' # # textoverlay.set_property("halign", "right") # # TypeError: object of type `GstTextOverlay' does not have property `valign' # # textoverlay.set_property("valign", "top") # conv = Gst.ElementFactory.make("videoconvert", "conv") # videosink = Gst.ElementFactory.make("autovideosink") # # self.bin.add(videoscale) # self.bin.add(filter) # self.bin.add(textoverlay) # self.bin.add(conv) # self.bin.add(videosink) # # videoscale.link(filter) # filter.link(textoverlay) # textoverlay.link(conv) # conv.link(videosink) # self.playbin.set_property("video-sink", self.bin) # connect to interesting signals in playbin self.playbin.connect("video-tags-changed", self.on_tags_changed) self.playbin.connect("audio-tags-changed", self.on_tags_changed) self.playbin.connect("text-tags-changed", self.on_tags_changed) # create the GUI self.build_ui() # instruct the bus to emit signals for each received message # and connect to the interesting signals bus = self.playbin.get_bus() bus.add_signal_watch() bus.connect("message::error", self.on_error) bus.connect("message::eos", self.on_eos) bus.connect("message::state-changed", self.on_state_changed) bus.connect("message::application", self.on_application_message)
def run(self): signal.signal(signal.SIGINT, signal.SIG_DFL) Gtk.init(sys.argv) window = self._prepare_window() self.wnck_wrapper = WnckWrapper(avoid=window).startup() Gtk.main()
def __init__(self, argv, descriptor): Gtk.init(sys.argv) super().__init__(argv, descriptor)
def __init__(self, crawler=None, file=''): Gtk.init() self.crawler = crawler self.file = file self.builder = self.build_ui() self.selected_links = None
self.compImg.set_from_pixbuf(self.compositePixbuf) self.compWin.set_title("New Composite Image") self.compWin.show_all() def source_file_set(self, widget): try: self.srcPixbuf = GdkPixbuf.Pixbuf.new_from_file(widget.get_filename()) self.srcImg.set_from_pixbuf(self.srcPixbuf) self.srcWin.set_title("SOURCE IMAGE: %dx%d" % (self.srcPixbuf.get_width(), self.srcPixbuf.get_height())) self.builder.get_object("dest_width").set_text(str(self.srcPixbuf.get_width())) self.builder.get_object("dest_height").set_text(str(self.srcPixbuf.get_height())) self.srcWin.move(self.mainWin.get_position()[0] + self.mainWin.get_size()[0], self.mainWin.get_position()[1]) self.srcWin.show_all() except GLib.GError as e: print >>sys.stderr, e.message def dest_file_set(self, widget): try: self.destPixbuf = GdkPixbuf.Pixbuf.new_from_file(widget.get_filename()) self.destImg.set_from_pixbuf(self.destPixbuf) self.destWin.set_title("DESTINATION IMAGE: %dx%d" % (self.destPixbuf.get_width(), self.destPixbuf.get_height())) self.destWin.move(self.mainWin.get_position()[0], self.mainWin.get_position()[1] + self.mainWin.get_size()[1]) self.destWin.show_all() except GLib.GError as e: print >>sys.stderr, e.message if __name__ == '__main__': Gtk.init(None); ui = CompositeUI() Gtk.main()
def main(): Gtk.init() VolctlApp() Gtk.main()
def get_active_window_title(): """ https://stackoverflow.com/a/36419702/858958 Get the currently active window. Returns ------- string : Name of the currently active window. """ import sys active_window_name = None if sys.platform in ['linux', 'linux2']: # Alternatives: http://unix.stackexchange.com/q/38867/4784 try: import wnck except ImportError: logging.info("wnck not installed") wnck = None if wnck is not None: screen = wnck.screen_get_default() screen.force_update() window = screen.get_active_window() if window is not None: pid = window.get_pid() with open("/proc/{pid}/cmdline".format(pid=pid)) as f: active_window_name = f.read() else: import gi gi.require_version('Gtk', '3.0') try: from gi.repository import Gtk, Wnck gi = "Installed" except ImportError: logging.info("gi.repository not installed") gi = None if gi is not None: Gtk.init([]) # necessary if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation active_window = screen.get_active_window() pid = active_window.get_pid() with open("/proc/{pid}/cmdline".format(pid=pid)) as f: active_window_name = f.read() elif sys.platform in ['Windows', 'win32', 'cygwin']: # http://stackoverflow.com/a/608814/562769 import win32gui window = win32gui.GetForegroundWindow() active_window_name = win32gui.GetWindowText(window) elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: # http://stackoverflow.com/a/373310/562769 from AppKit import NSWorkspace active_window_name = (NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName']) else: print("sys.platform={platform} is unknown. Please report.".format( platform=sys.platform)) print(sys.version) exit() return active_window_name
def getActiveWindow(sleep_time=0): """ Get the currently active window. Arguments: sleep_time: int:- initial sleep time of function Returns ------- active_software_name: String-: Name of the currently active software. active_window_name: String-: Name of the currently active window. active_window_bbox: [x1,y1,x2,y2]-: (x1,y2) ->top left point, (x2,y2)-> bottom right point of active window. """ time.sleep(sleep_time) active_software_name = None active_window_name = None active_window_bbox = None if sys.platform in ['linux', 'linux2']: CustomException( "sys.platform={platform} is unknown. Please report.".format( platform=sys.platform)) # Alternatives: http://unix.stackexchange.com/q/38867/4784 try: import wnck except ImportError: wnck = None if wnck is not None: screen = wnck.screen_get_default() screen.force_update() window = screen.get_active_window() if window is not None: pid = window.get_pid() with open("/proc/{pid}/cmdline".format(pid=pid)) as f: active_window_name = f.read() else: try: from gi.repository import Gtk, Wnck gi = "Installed" except ImportError: logging.info("gi.repository not installed") gi = None if gi is not None: Gtk.init([]) # necessary if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation active_window = screen.get_active_window() pid = active_window.get_pid() with open("/proc/{pid}/cmdline".format(pid=pid)) as f: active_window_name = f.read() elif sys.platform in ['Windows', 'win32', 'cygwin']: # http://stackoverflow.com/a/608814/562769,https://stackoverflow.com/questions/14394513/win32gui-get-the-current-active-application-name import win32gui import win32process # pip install wmi import pythoncom pythoncom.CoInitialize() def get_app_name(hwnd): c = wmi.WMI() """Get applicatin filename given hwnd.""" try: _, pid = win32process.GetWindowThreadProcessId(hwnd) for p in c.query( 'SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)): exe = p.Name break return exe except: return None window = win32gui.GetForegroundWindow() active_software_name = get_app_name(window) try: active_window_bbox = win32gui.GetWindowRect(window) except pywintypes.error: print("1400, invalid window handle") active_window_bbox = None active_window_name = win32gui.GetWindowText(window) # window = win32gui.GetForegroundWindow() # active_software_name = get_app_name(window) # active_window_bbox = win32gui.GetWindowRect(window) # active_window_name = win32gui.GetWindowText(window) elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: # http://stackoverflow.com/a/373310/562769 from AppKit import NSWorkspace from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID curr_app = NSWorkspace.sharedWorkspace().frontmostApplication() curr_pid = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationProcessIdentifier'] curr_app_name = curr_app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) for window in windowList: pid = window['kCGWindowOwnerPID'] windowNumber = window['kCGWindowNumber'] ownerName = window['kCGWindowOwnerName'] geometry = window['kCGWindowBounds'] windowTitle = window.get('kCGWindowName', u'Unknown') if curr_pid == pid: # print("%s - %s (PID: %d, WID: %d): %s" % (ownerName, windowTitle.encode('ascii','ignore'), pid, windowNumber, geometry)) active_software_name = ownerName active_window_name = windowTitle.encode('ascii', 'ignore') active_window_bbox = [ geometry['X'], geometry['Y'], geometry['X'] + geometry['Width'], geometry['Y'] + geometry['Height'] ] else: CustomException( "sys.platform={platform} is unknown. Please report.".format( platform=sys.platform)) # print("Active software name: %s" % str(active_software_name)) # print("Active window name: %s" % str(active_window_name)) # print("Active window bbox: ", active_window_bbox) return active_software_name, active_window_name, active_window_bbox
from gi.repository import Gtk, Wnck Gtk.init([]) # necessary only if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation visibility = False # loop all windows for window in screen.get_windows(): if window.get_name() == 'Guake!': visibility = True # clean up Wnck (saves resources, check documentation) window = None screen = None Wnck.shutdown() print visibility
def main(self): Gtk.init(sys.argv) window = Gtk.Window() window.resize(1000, 800) window.set_title("Webkit tests window") # Window's title window.move(100, 100) window.connect('destroy', lambda x: Gtk.main_quit()) # Connect signal 'destroy' #window.set_decorated(False) self.screen = window.get_screen() self.visual = self.screen.get_rgba_visual() if self.visual and self.screen.is_composited(): window.set_visual(self.visual) window.set_app_paintable(True) window.connect("draw", area_draw) box = Gtk.VBox() box.set_margin_top(30) box.set_margin_bottom(30) box.set_margin_left(30) box.set_margin_right(30) make_transparent(box) window.add(box) folder = '/d/Pics/Wallpapers/Favorites/' images = sorted( os.path.join(folder, f) for f in os.listdir(folder) if f.endswith('.jpg')) self.current = images[100] self.web_view = WebKit.WebView() self.web_view.set_transparent(True) make_transparent(self.web_view) self.web_view.set_can_focus(True) self.web_view.load_string( "<html><body style='background: rgba(0, 0, 0, 0); color: white;'><img id='i' src='data:image/png;base64," + b64(self.current) + "'/></body></html>", "text/html", "UTF-8", "file://" + os.path.dirname(__file__) + "/") self.scroll = Gtk.ScrolledWindow() self.scroll.add_with_viewport(self.web_view) make_transparent(self.scroll.get_child()) box.add(self.scroll) window.show_all() def go(*args): self.current = images[(images.index(self.current) + 1) % len(images)] nextt = b64(self.current) self.web_view.execute_script( "document.getElementById('i').setAttribute('src', 'data:image/png;base64," + nextt + "')") # self.web_view.execute_script("document.getElementById('i').setAttribute('src', '" + self.current + "')") window.connect('button-press-event', go) Gtk.main() # Start the application
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gi try: gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') except Exception as e: print(e) exit(1) from gi.repository import Gtk from gi.repository import Gst import sys import os Gtk.init(None) Gst.init(None) class VideoSnapShooter(): def __init__(self, videofilename): descr = 'uridecodebin uri=file://%s ! videoconvert ! videoscale !\ gdkpixbufsink name=sink' % (videofilename) self.pipeline = Gst.parse_launch(descr) self.sink = self.pipeline.get_by_name('sink') ret = self.pipeline.set_state(Gst.State.PAUSED) if ret == Gst.StateChangeReturn.FAILURE: print('failed to play the file (1)\n') elif ret == Gst.StateChangeReturn.NO_PREROLL: print('live sources not supported yet\n') ret = self.pipeline.get_state(5 * Gst.SECOND)
def get_active_window(systemProcesses): """ Get the currently active window. Returns ------- string : Name of the currently active window. """ import sys active_window_name = None parent = "" windowTitle = None if sys.platform in ['linux', 'linux2']: # Alternatives: http://unix.stackexchange.com/q/38867/4784 try: import wnck except ImportError: logging.info("wnck not installed") wnck = None if wnck is not None: screen = wnck.screen_get_default() screen.force_update() window = screen.get_active_window() if window is not None: pid = window.get_pid() with open("/proc/{pid}/cmdline".format(pid=pid)) as f: active_window_name = f.read() else: try: from gi.repository import Gtk, Wnck gi = "Installed" except ImportError: logging.info("gi.repository not installed") gi = None if gi is not None: Gtk.init([]) # necessary if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation active_window = screen.get_active_window() pid = active_window.get_pid() with open("/proc/{pid}/cmdline".format(pid=pid)) as f: active_window_name = f.read() elif sys.platform in ['Windows', 'win32', 'cygwin']: # http://stackoverflow.com/a/608814/562769 import win32gui window = win32gui.GetForegroundWindow() active_window_name = win32gui.GetWindowText(window) ## See if we can get the application name too ##try: ## parent = win32gui.GetParent(window) ##except win32api.error: ## parent = "Unknown" ##print( "Parent is " + str(parent)) ## Get parent procs = wmi.WMI().Win32_Process() ##pycwnd = win32gui.GetForegroundWindow() tid, pid = win32process.GetWindowThreadProcessId(window) ## Check process in hashmap parent = "Unknown" if pid in systemProcesses: print("Found process in dict - Exec is " + systemProcesses[pid] + "\n") parent = systemProcesses[pid] else: #print("Adding process to dict\n") for proc in procs: if proc.ProcessId == pid: print('pid' + str(pid)) print('exec' + proc.ExecutablePath) print('title' + win32gui.GetWindowText(window)) parent = proc.ExecutablePath systemProcesses[pid] = parent print("Parent is " + str(parent)) elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: # http://stackoverflow.com/a/373310/562769 from AppKit import NSWorkspace from Quartz import (CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID) active_window_name = (NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName']) try: if sys.platform == "darwin": app = NSWorkspace.sharedWorkspace().frontmostApplication() active_app_name = app.localizedName() #print("Active App(NEW) %s" % str(active_app_name) ) #print("Active App(OLD) %s" % str(active_window_name) ) options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo( options, kCGNullWindowID) windowTitle = 'Unknown' for window in windowList: windowNumber = window['kCGWindowNumber'] ownerName = window['kCGWindowOwnerName'] # geometry = window['kCGWindowBounds'] windowTitle = window.get('kCGWindowName', 'Unknown') #print("window:title %s" % str(windowTitle) ) ##if windowTitle and ( ownerName == active_app_name): if windowTitle and (ownerName == active_window_name): # logging.debug( # 'ownerName=%s, windowName=%s, x=%s, y=%s, ' # 'width=%s, height=%s' # % (window['kCGWindowOwnerName'], # window.get('kCGWindowName', u'Unknown'), # geometry['X'], # geometry['Y'], # geometry['Width'], # geometry['Height'])) #print("app %s" % str(active_window_name ) ) #print(windowTitle ) break return active_window_name + " : " + windowTitle ## return _review_active_info(active_app_name, windowTitle) except: logging.error('Unexpected error: %s' % sys.exc_info()[0]) logging.error('error line number: %s' % sys.exc_traceback.tb_lineno) return 'Unknown', 'Unknown' else: print(("sys.platform={platform} is unknown. Please report.".format( platform=sys.platform))) print((sys.version)) ## Match the category ## TODO: Need to use RE here ; Here is a snippet ## if re.search('mandy', 'Mandy Pande', re.IGNORECASE): value = 0 activityCategory = "default" for i in set(category.keys()): print("next category is " + i) #if (parent.find(i)): if (re.search(i, parent, re.IGNORECASE)): activityCategory = i value = category[i] print("Category is " + i + " with value " + str(value)) break ## Do we have active directory associated with this category? if activityCategory in activityDictionary: print("There are more activities associated with category: " + activityCategory) ## Checking if this title matches any? categoryActivities = activityDictionary[activityCategory] for j in set(categoryActivities.keys()): print("next activity is " + j) if (re.search(j, active_window_name, re.IGNORECASE)): value = categoryActivities[j] print("Activity " + j + " of Category " + activityCategory + " has value " + str(value)) break return active_window_name + " : " + parent
# check min-version minGst = (1, 5) minPy = (3, 0) Gst.init([]) if Gst.version() < minGst: raise Exception("GStreamer version", Gst.version(), 'is too old, at least', minGst, 'is required') if sys.version_info < minPy: raise Exception("Python version", sys.version_info, 'is too old, at least', minPy, 'is required') # init GObject & Co. before importing local classes GObject.threads_init() Gdk.init([]) Gtk.init([]) # import local classes from lib.args import Args from lib.config import Config from lib.ui import Ui from lib.loghandler import LogHandler import lib.connection as Connection # main class class Voctogui(object): def __init__(self): self.log = logging.getLogger('Voctogui') # Uf a UI-File was specified on the Command-Line, load it
def main(): Gdk.init([]) Gtk.init([]) Gst.init([]) global ARGS ARGS = build_parser().parse_args() # load means and stds from stat.txt with open(ARGS.statFile, 'r') as f: gNetworkMean = f.readline().split() gNetworkStd = f.readline().split() for i in range(3): gNetworkMean[i] = 255 * float(gNetworkMean[i]) gNetworkStd[i] = 1 / (255 * float(gNetworkStd[i])) # Load categories from categories.txt gNetworkCategories = [] with open(ARGS.category, 'r') as f: for line in f: cat = line.split('\n')[0] if cat != 'classes': gNetworkCategories.append(cat) f.close() print('Number of categories:', len(gNetworkCategories)) # the camera source string for USB cameras. They will be /dev/video0, /dev/video1, etc. # for this sample we will open the first camera (/dev/video0) cam_src_str = "v4l2src device=/dev/video" + ARGS.source app_launch_str = "\ videoscale ! video/x-raw, width=%s, height=%s ! \ videoconvert ! video/x-raw, format=%s ! \ appsink name=%s max-buffers=1 drop=true enable-last-sample=true" % (NETWORK_IMAGE_WIDTH, NETWORK_IMAGE_HEIGHT, NETWORK_IMAGE_FORMAT, GST_APP_NAME) # build GUI window = Gtk.Window() window.connect("delete-event", window_closed, gstPipeline) WINDOW_WIDTH = ARGS.win_size[0] WINDOW_HEIGHT = ARGS.win_size[1] window.set_default_size(WINDOW_WIDTH, WINDOW_HEIGHT) window.set_title("CLEAN WATER AI") box = Gtk.Box() box.set_spacing(5) box.set_orientation(Gtk.Orientation.VERTICAL) window.add(box) box.pack_start(gDrawAreaSink, True, True, 0) gResultLabel = Gtk.Label() box.pack_start(gResultLabel, False, True, 0) window.show_all() window.realize() gstPipeline.get_by_name(GST_VIEW_NAME).set_window_handle( gDrawAreaSink.get_window().get_xid()) # Set up the network and plugin plugin, input_shape, input_blob, output_blob, exec_net = setup_network() #Initialize input and output threads to pass images to the # MVNC device and to read results from the inferences made on thos images. gCallback = put_output start_thread(exec_net,input_blob, output_blob) if gstPipeline.set_state(Gst.State.PLAYING) == Gst.StateChangeReturn.FAILURE: gstPipeline.set_state(Gst.State.NULL) else: # export GST_DEBUG_DUMP_DOT_DIR=/tmp/ Gst.debug_bin_to_dot_file( gstPipeline, Gst.DebugGraphDetails.ALL, 'playing-pipeline') Gtk.main() Gst.debug_bin_to_dot_file( gstPipeline, Gst.DebugGraphDetails.ALL, 'shutting-down-pipeline') gstPipeline.set_state(Gst.State.NULL) print("exiting main loop") # close the device del exec_net del plugin if __name__ == '__main__': sys.exit(main() or 0)