def __init__(self): self.sct = mss() display = Xlib.display.Display() root = display.screen().root windowIDs = root.get_full_property(display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = display.create_resource_object('window', windowID) name = window.get_wm_name() # Title if 'Dolphin 5.0 |' in str(name): geometry = window.get_geometry() self.width = geometry.__getattr__('width') self.height = geometry.__getattr__('height') self.x = 0 self.y = 0 tree = window.query_tree() parent = tree.__getattr__('parent') while parent is not 0: geometry = parent.get_geometry() self.x += geometry.__getattr__('x') self.y += geometry.__getattr__('y') parent_tree = parent.query_tree() parent = parent_tree.__getattr__('parent')
def create_lookup_table(windows, workspaces = False): '''Create a lookup table from the given list of windows/workspaces. The returned dict is in the format window title → X window id. ''' lookup = {} display = Xlib.display.Display() for window in windows: name = window.get('name') id_ = window.get('window') urgent = window.get('urgent') if id_ is None: # this is not an X window, ignore it. continue if name.startswith("i3bar for output"): # this is an i3bar, ignore it. continue if not workspaces: # collect window's class name and instance name using Xlib window_ = display.create_resource_object('window', id_) # create readable title, including urgency flag, window's class and instance name win_str = '%s%s %s %s' % ("[*] " if urgent else "", string.ljust('[' + window.get('output') + ']', 15, ' ') if workspaces else '', name, "" if workspaces else ' :: %s | %s ' % (window_.get_wm_class()[0], window_.get_wm_class()[1])) lookup[win_str] = id_ return lookup
def get_window_by_gtk_application_id_xlib(gtk_application_id): ''' Function to get window using the gtk_application_id from NET_WM ''' import Xlib import Xlib.display display = Xlib.display.Display() root = display.screen().root NET_CLIENT_LIST = display.intern_atom('_NET_CLIENT_LIST') GTK_APPLICATION_ID = display.intern_atom('_GTK_APPLICATION_ID') root.change_attributes(event_mask=Xlib.X.FocusChangeMask) try: window_id = root.get_full_property(NET_CLIENT_LIST, Xlib.X.AnyPropertyType).value for id in window_id: window = display.create_resource_object('window', id) window.change_attributes(event_mask=Xlib.X.PropertyChangeMask) if window.get_full_property(GTK_APPLICATION_ID, 0): if window.get_full_property( GTK_APPLICATION_ID, 0).value.decode("utf-8") == gtk_application_id: break except Xlib.error.XError: #simplify dealing with BadWindow window = None return window
def _is_active_window_fullscreen(self, display): root = display.screen().root net_active_window = display.intern_atom('_NET_ACTIVE_WINDOW') net_wm_state = display.intern_atom('_NET_WM_STATE') net_wm_state_fullscreen = display.intern_atom( '_NET_WM_STATE_FULLSCREEN') active_win_id = root.get_full_property(net_active_window, Xlib.X.AnyPropertyType) if not active_win_id: return False active_win_id = active_win_id.value[0] active_win = display.create_resource_object('window', active_win_id) wm_state = active_win.get_full_property(net_wm_state, Xlib.X.AnyPropertyType) if not wm_state: return False wm_state = wm_state.value return net_wm_state_fullscreen in wm_state
def setAsBar(self): self.setWindowFlags(Qt.FramelessWindowHint) self.setWindowFlags(Qt.X11BypassWindowManagerHint) self.setGeometry( QRect(self._xpos, self._ypos, self._width, self._height)) x11window = display.create_resource_object('window', int(self.winId())) _ATOM = display.intern_atom("ATOM") _TYPE = display.intern_atom("_NET_WM_WINDOW_TYPE") _DOCK = display.intern_atom("_NET_WM_WINDOW_TYPE_DOCK") x11window.change_property(_TYPE, _ATOM, 32, [_DOCK]) if self._ypos < 100: x11window.change_property(atom_strut_partial, atom_cardinal, 32, [ 0, 0, self._height, 0, 0, 0, 0, 0, self._xpos, self._xpos + self._width, 0, 0 ]) x11window.change_property(atom_strut, atom_cardinal, 32, [0, 0, self._height, 0]) else: # bottom x11window.change_property(atom_strut_partial, atom_cardinal, 32, [ 0, 0, 0, self._height, 0, 0, 0, 0, self._xpos, self._xpos + self._width, self._ypos, self._ypos + self._height ]) x11window.change_property(atom_strut, atom_cardinal, 32, [0, 0, 0, self._height]) display.sync()
def ImageCapture(self, rectangle, hwnd): x, y, w, h = rectangle if w <= 0 or h <= 0 or hwnd == 0 or hwnd is None: return None if self.last_hwnd != hwnd: self.last_hwnd = hwnd self.cached_win = None if self.cached_win is None: display = Xlib.display.Display() self.cached_win = display.create_resource_object("window", hwnd) try: geom = self.cached_win.get_geometry() except Exception: # Xlib.error.BadDrawable raise x, y, w, h = self.check_geometry(geom, (x, y, w, h)) try: raw = self.cached_win.get_image(x, y, w, h, X.ZPixmap, 0xFFFFFFFF) except Xlib.error.BadMatch: raise # note that we actually want to support a BGR and RGB Image # for the return type eventually, since BGR is double the speed # this isn't implemented in windows yet either. # if useRGB: return Image.frombytes("RGB", (w, h), raw.data, "raw", "BGRX")
def send_event(client_id, keystate, shiftstate, keycode): display = Xlib.display.Display() Xlib_root_window = display.screen().root window = display.create_resource_object('window', client_id) if keystate == 2: XEVENT = Xlib.protocol.event.KeyPress elif keystate == 3: XEVENT = Xlib.protocol.event.KeyRelease else: raise event = XEVENT(time=int(time.time()), root=Xlib_root_window, window=window, same_screen=0, child=Xlib.X.NONE, root_x=0, root_y=0, event_x=0, event_y=0, state=shiftstate, detail=keycode) display.sync() p = window.send_event(event, propagate=False) display.sync() display.close() return True
def get_active_window(): window_id = root.get_full_property(NET_ACTIVE_WINDOW, X.AnyPropertyType).value[0] focus_changed = (window_id != last_seen['xid']) last_seen['xid'] = window_id return display.create_resource_object('window', window_id), focus_changed
def update_strut(self): display = Xlib.display.Display() window = display.create_resource_object("window", self.get_window().get_xid()) window.change_property( display.intern_atom("_NET_WM_STRUT"), display.intern_atom("CARDINAL"), 32, [0, 0, 0, self.headerbar.get_allocated_height()]) display.sync()
def get_window_name(window_id): """Return window title if one can be found or None.""" for atom in (net_wm_name, wm_name): window_obj = display.create_resource_object("window", window_id) name_str = window_obj.get_full_property(atom, 0).value if isinstance(name_str, bytes): return name_str.decode("latin1", "replace") return name_str
def _get_window_name(root, display): _net_wm_name = display.intern_atom('_NET_WM_NAME') try: window_obj = display.create_resource_object('window', root) window_name = window_obj.get_full_property(_net_wm_name, 0).value except Xlib.error.XError: window_name = None return window_name
def window_obj(wid): """Simplify dealing with BadWindow (make it either valid or None)""" window_obj = None if wid: try: window_obj = display.create_resource_object('window', wid) except Xlib.error.XError: pass yield window_obj
def getWindowName(self): display = Xlib.display.Display() root = display.screen().root windowID = root.get_full_property( display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', windowID) return window.get_wm_class()[1]
def get_active_window(): windowID = root.get_full_property( display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', windowID) parent = window while window.id != root.id: window, parent = window.query_tree().parent, window return parent
def fetch_wid(self): sleep(0.1) xwininfo = subprocess.Popen(" ".join( ['xwininfo', '-name', self.name, '|', 'grep', '"Window id"']), shell=True, stdout=subprocess.PIPE) for line in xwininfo.stdout: self.wid = line.decode("utf-8").strip().split(" ")[3] if self.wid: self.xlib = display.create_resource_object('window', int(self.wid, 16))
def getWinByClick(): winId=XDO.select_window_with_click() if winId: display = Xlib.display.Display() win=display.create_resource_object("window",winId) winObj=_parseWindow(display,win) out=[] for i in winObj["pids"]: out.append(i) return out return []
def __update_focus_cb(self, command, sync=False): # Check FocusIn/FocusOut events if self.focus: focus_in = None focus_out = None for i in range(display.pending_events()): event = display.next_event() if event.type == Xlib.X.FocusIn: focus_in = event.window elif event.type == Xlib.X.FocusOut: focus_out = event.window if focus_in == self.focus: if focus_out != self.focus: # This is ugly workaround, but necessary to avoid a # problem that the language bar doesn't appear after # moving to other workspace in Ubuntu Unity desktop. # If old version of ibus.el which doesn't define # `ibus-redo-focus-in-cb' is running on Emacs, the # following message will just be ignored and take no effect. print_command('ibus_redo_focus_in_cb') if sync: print_command(command, focus_in.id) return True # Main part focus = self.display.get_input_focus().focus try: # get_input_focus() may return an integer 0 that query_tree() # causes AttributeError when X session is going to logout. tree = focus.query_tree() # In Ubuntu's Unity desktop, get_input_focus() often returns root # window incorrectly after changing workspace. if focus != tree.root: if not (focus.get_wm_class() or focus.get_wm_name()): focus = tree.parent if focus != self.focus or sync: print_command(command, focus.id) focus.change_attributes(event_mask=Xlib.X.FocusChangeMask) self.focus = focus return True except AttributeError: if sync: print_command(command, 0) return True # Fallback atom = display.get_atom("_NET_ACTIVE_WINDOW", True) focus_id = tree.root.get_property(atom, Xlib.Xatom.WINDOW, 0, 1).value[0] focus = display.create_resource_object("window", focus_id) if focus != self.focus or sync: print_command(command, focus_id) focus.change_attributes(event_mask=Xlib.X.FocusChangeMask) self.focus = focus return True
def __init__(self, window_id): self.id = window_id self.x = None self.y = None self.width = None self.title = "" self.wm_class = "" self.xlib = display.create_resource_object('window', int(window_id, 16)) self.is_moving = False self.fetch_geometry() self.fetch_props() self.bar = Bar(self)
def update(): global current_window_id, current_window window_id = _check_current_window_id() if current_window_id is None or not window_id == current_window_id: window = display.create_resource_object('window', window_id) window.change_attributes(event_mask=Xlib.X.PropertyChangeMask) current_window = window current_window_id = window_id print("Current window: {0}".format(get_focused_window_name())) event = display.next_event()
def find_xid(display, title): root = display.screen().root window_ids = root.get_full_property( display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value for window_id in window_ids: window = display.create_resource_object('window', window_id) name = window.get_full_property(display.intern_atom('_NET_WM_NAME'), Xlib.X.AnyPropertyType).value if title in name: return window_id return None
def resize_grace( ): windowIDs = root.get_full_property(display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = display.create_resource_object('window', windowID) name = window.get_wm_name() # Title pid = window.get_full_property(display.intern_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType) # PID #print pid #print windowID #print name if "Grace" in name: #print name window.configure(width = WIDTH, height = HEIGHT) # for whatever reason, width and height are backwards but i don't care display.sync()
def fetch_wid(self): sleep(0.1) xwininfo = subprocess.Popen( " ".join([ 'xwininfo', '-name', self.name, '|', 'grep', '"Window id"' ]), shell=True, stdout=subprocess.PIPE ) for line in xwininfo.stdout: self.wid = line.decode("utf-8").strip().split(" ")[3] if self.wid: self.xlib = display.create_resource_object('window', int(self.wid, 16))
def update_tab_geometry_hints(self): ''' copy the WM_NORMAL_HINTS properties of rxvt window to the rxvt tab so it stays within the rxvt resizing requirements resizing might not be smooth anymore if this is called ''' rxvt_socket = self.rxvt_socket display = Xlib.display.Display() xlib_window = display.create_resource_object('window', self.plugged.get_xid()) hints = xlib_window.get_wm_normal_hints() geometry = Gdk.Geometry() geometry.base_width = hints.base_width geometry.base_height = hints.base_height geometry.width_inc = hints.width_inc geometry.height_inc = hints.height_inc geom_mask = Gdk.WindowHints(0) geom_mask |= Gdk.WindowHints.BASE_SIZE geom_mask |= Gdk.WindowHints.RESIZE_INC rxvt_socket.get_toplevel().set_geometry_hints(rxvt_socket, geometry, geom_mask)
def getActiveWindow(): active_window_name = None try: if sys.platform in ['linux', 'linux2']: windowID = root.get_full_property( display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', windowID) return window.get_wm_class()[0] elif sys.platform in ['Windows', 'win32', 'cygwin']: window = win32gui.GetForegroundWindow() active_window_name = win32gui.GetWindowText(window) elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: active_window_name = (NSWorkspace.sharedWorkspace(). activeApplication()['NSApplicationName']) except: print("Could not get active window: ", sys.exc_info()[0]) return active_window_name
def get_active_window_xlib(): ''' Function to get active window ''' import Xlib import Xlib.display display = Xlib.display.Display() root = display.screen().root NET_ACTIVE_WINDOW = display.intern_atom('_NET_ACTIVE_WINDOW') root.change_attributes(event_mask=Xlib.X.FocusChangeMask) try: window_id = root.get_full_property(NET_ACTIVE_WINDOW, Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', window_id) except Xlib.error.XError: #simplify dealing with BadWindow window = None return window
def getWindowIDFromString(self, window_name): root = display.screen().root windowIDs = root.get_full_property( display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = display.create_resource_object('window', windowID) if window_name in window.get_wm_name(): window_width = window.get_geometry().width window_heigth = window.get_geometry().height raw = window.get_image(0, 0, window_width, window_heigth, X.ZPixmap, 0xffffffff) image = Image.frombytes("RGB", (window_width, window_heigth), raw.data, "raw", "BGRX") image.show()
def openWindow(): global window, WIDTH, HEIGHT, display, LEFT, TOP os.system('clear') # Open the browser os.system('firefox "https://agar.io" -new-window -private &') sleep(2) # Get display display = Xlib.display.Display() root = display.screen().root # Get the x windows ID of the browser windowID = root.get_full_property( display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', windowID) window.configure(width=WIDTH, height=HEIGHT) display.sync() LEFT, TOP = window.get_geometry().x, window.get_geometry().y
def on_gdk_event(self, event): ''' events are also created when the urxvt plugged window closes, this handler disconnects itself when it recieves the event ''' try: if event.type == Gdk.EventType.CONFIGURE: self.update_tab_geometry_hints() elif event.type == Gdk.EventType.PROPERTY_NOTIFY: if event.state == Gdk.PropertyState.NEW_VALUE: if event.atom.name() == '_NET_WM_NAME': #window name change event, set tab title display = Xlib.display.Display() xlib_window = display.create_resource_object('window', self.plugged.get_xid()) title = xlib_window.get_wm_name() self.shell_title = title self.shell_set_title(title) except Xlib.error.BadWindow: #the plug window has now closed itself (there are no events indicating this, so catch the exception instead) gdk_events.remove_event_listener(self.event_listener_id) self.close()
def on_gdk_event(self, event): ''' events are also created when the urxvt plugged window closes, this handler disconnects itself when it recieves the event ''' try: if event.type == Gdk.EventType.CONFIGURE: self.update_tab_geometry_hints() elif event.type == Gdk.EventType.PROPERTY_NOTIFY: if event.state == Gdk.PropertyState.NEW_VALUE: if event.atom.name() == '_NET_WM_NAME': #window name change event, set tab title display = Xlib.display.Display() xlib_window = display.create_resource_object( 'window', self.plugged.get_xid()) title = xlib_window.get_wm_name() self.shell_title = title self.shell_set_title(title) except Xlib.error.BadWindow: #the plug window has now closed itself (there are no events indicating this, so catch the exception instead) gdk_events.remove_event_listener(self.event_listener_id) self.close()
def get_active_window_wm_class(): ''' Function to get active window ''' import Xlib import Xlib.display display = Xlib.display.Display() root = display.screen().root NET_ACTIVE_WINDOW = display.intern_atom('_NET_ACTIVE_WINDOW') WM_CLASS = display.intern_atom('WM_CLASS') root.change_attributes(event_mask=Xlib.X.FocusChangeMask) try: window_id = root.get_full_property(NET_ACTIVE_WINDOW, Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', window_id) try: return window.get_full_property(WM_CLASS, 0).value.replace( b'\x00', b' ').decode("utf-8").lower() except: return None except Xlib.error.XError: #simplify dealing with BadWindow return None
def getCurrentViewableOpenedWins(self): root = display.screen().root windowNames = [] windowIDs = root.get_full_property( display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = display.create_resource_object('window', windowID) name = window.get_wm_name() # Title try: data = name.decode() except AttributeError: prop = window.get_full_property( display.intern_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType) windowNames.append(name) continue return windowNames
def setAsBar(self): self.setWindowFlags(Qt.FramelessWindowHint) self.setWindowFlags(Qt.X11BypassWindowManagerHint) self.setGeometry(QRect(self._xpos, self._ypos, self._width, self._height)) x11window = display.create_resource_object('window', int(self.winId())) if self._ypos < 100: x11window.change_property(atom_strut_partial, atom_cardinal, 32, [0, 0, self._height, 0, 0, 0, 0, 0, self._xpos, self._xpos + self._width, 0, 0]) x11window.change_property(atom_strut, atom_cardinal, 32, [0, 0, self._height, 0]) else: # bottom x11window.change_property(atom_strut_partial, atom_cardinal, 32, [0, 0, 0, self._height, 0, 0, 0, 0, self._xpos, self._xpos + self._width, self._ypos, self._ypos + self._height]) x11window.change_property(atom_strut, atom_cardinal, 32, [ 0, 0, 0, self._height]) display.sync()
def get_geometry(): '''Should return the position and size of the openrave viewer.''' display = Xlib.display.Display() root = display.screen().root # List of all window ids wids = root.get_full_property(display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value # Finding the openrave window by window name for wid in wids: window = display.create_resource_object('window', wid) # NOTE: if any of the windows have non-ascii chars in the # name, e.g. certain web page titles, then this will crash. name = window.get_wm_name() if 'OpenRAVE' in name: or_window = window # Need the parent: https://stackoverflow.com/a/12854004 parent = or_window.query_tree().parent geom = window.get_geometry() x, y = geom.x, geom.y translated_data = window.translate_coords(root, x, y) x = -1 * translated_data.x y = -1 * translated_data.y width, height = geom.width, geom.height return {'top': y, 'left': x, 'width': width, 'height': height}
def _get_window(window_id: int) -> Window: return display.create_resource_object('window', window_id)
#! /usr/bin/env python # -*- coding: utf-8 -*- import Xlib import Xlib.display display = Xlib.display.Display() root = display.screen().root windowIDs = root.get_full_property(display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = display.create_resource_object('window', windowID) name = window.get_wm_name() # Title pid = window.get_full_property(display.intern_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType) # PID s = str(pid).split('[') if len(s)>1: s2=s[1].split('L]')[0] print s2
def get_window(windowid=None): #window = display.get_input_focus()._data["focus"]; if windowid is None: windowid = get_window_id() window = display.create_resource_object('window', windowid) return window
gl.glUniform2f(cursor_pos_loc, cursor_posx, WINDOW_HEIGHT - cursor_posy) def main(): if not glfw_init_routine(): return if not gl_init_routine(): return # Main event loop while not glfw.window_should_close(window): update_surface() render() glfw.swap_buffers(window) mark_blob() do_input() glfw.poll_events() gl_deinit_routine() glfw.terminate() if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: python demo.py X11_WINDOW_ID") exit(0) dest_window = display.create_resource_object('window', int(sys.argv[1], 0)) main()
def get_prop(window, prop_name): return window.get_full_property(display.intern_atom(prop_name), Xlib.X.AnyPropertyType).value try: # xwininfo blocks until the user clicks on a window. xwininfo = subprocess.Popen("xwininfo", stdout=subprocess.PIPE, shell=True, bufsize=-1) ret = xwininfo.wait() target_win_info = xwininfo.stdout.read()[:-1] if ret != 0: raise subprocess.CalledProcessError(ret, "xwininfo", target_win_info) target_win_id = re.search('Window id: ([0-9a-fx]+)', target_win_info).group(1) target_win_id = int(target_win_id, 16) except: target_win_id = get_prop(root, "_NET_ACTIVE_WINDOW")[0] target_win_handle = display.create_resource_object("window", target_win_id) target_win_frame = get_prop(target_win_handle, "_NET_FRAME_EXTENTS") client_list_stacking = get_prop(root, "_NET_CLIENT_LIST_STACKING") win_list = [] for win_id in reversed(client_list_stacking): if win_id == target_win_id: continue win_handle = display.create_resource_object("window", win_id) win_state = get_prop(win_handle, "_NET_WM_STATE") win_is_maximized = (display.intern_atom("_NET_WM_STATE_MAXIMIZED_VERT") in win_state and display.intern_atom("_NET_WM_STATE_MAXIMIZED_HORZ") in win_state or display.intern_atom("_NET_WM_STATE_FULLSCREEN") in win_state) if win_is_maximized: break # ignore all windows beneath a maximized one
import time import Xlib import Xlib.display while True: display = Xlib.display.Display() root = display.screen().root windowID = root.get_full_property( display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] window = display.create_resource_object('window', windowID) try: print window.get_wm_name() except: print 'something wrong buddy' pass time.sleep(10)