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 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 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 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 _parseWindow(display,win): winName = win.get_full_property(display.intern_atom('_NET_WM_NAME'), Xlib.X.AnyPropertyType) if not winName: winName=win.get_full_property(display.intern_atom('WM_NAME'), Xlib.X.AnyPropertyType) winPids=win.get_full_property(display.intern_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType) if not winPids: winPids=win.get_full_property(display.intern_atom('WM_PID'), Xlib.X.AnyPropertyType) if not winPids: winPids=win.get_full_property(display.intern_atom('STEAM_GAME'), Xlib.X.AnyPropertyType) if not winName or not winPids: return None winName=str(winName.value.decode("utf-8")) winPids=winPids.value return {"name":winName,"pids":winPids}
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 __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 _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 reset(display, win): win.set_wm_normal_hints( flags = Xutil.PWinGravity, win_gravity = X.NorthWestGravity) atom = lambda s: display.intern_atom(s) send_event(display.screen().root, win, atom("_NET_WM_STATE"), [0, atom("_NET_WM_STATE_MAXIMIZED_VERT"), atom("_NET_WM_STATE_MAXIMIZED_HORZ")]) display.flush()
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 get_active_window_id(): import Xlib import Xlib.display display = Xlib.display.Display() root = display.screen().root windowID = root.get_full_property( display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] return windowID
def _diff_window_is_open(left_path, right_path): """Return True if PyCharm is currently showing a diff window for the given paths. The search iterates over all windows managed by X and examines the properties / atoms. The window must have "jetbrains" as part of one or more classes and have "{left_path} vs {right_path}" as part of its window name. """ display = Xlib.display.Display() net_wm_name = display.intern_atom("_NET_WM_NAME") # Modern, UTF-8 wm_name = display.intern_atom("WM_NAME") # Legacy title_str = "{} vs {}".format( os.path.split(left_path)[1], os.path.split(right_path)[1]) def find_diff_window(window): for w in window.query_tree().children: if find_diff_window(w): return True else: if any(["jetbrains" in c for c in w.get_wm_class() or []]): if title_str in get_window_name(w) or '': return True return False 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 try: return find_diff_window(display.screen().root) except ( Xlib.error.XError, Xlib.error.BadWindow, UnicodeDecodeError, AttributeError, ): return False
def create_panel(width, height, left, ypos, panel_height, at_top): ''' Create a docked panel, not mapped yet @param width:int The width of the output @param height:int The height of the output @param left:int The left position of the output @param ypos:int The position of the panel in relation to either the top or bottom edge of the output @param panel_height:int The height of the panel @param at_top:bool Whether the panel is to be docked to the top of the output, otherwise to the bottom @return The window ''' global display, screen ypos = ypos if at_top else (height - ypos - panel_height) window = screen.root.create_window( left, ypos, width, panel_height, 0, Xlib.X.CopyFromParent, Xlib.X.InputOutput, Xlib.X.CopyFromParent, event_mask=get_event_mask(), colormap=Xlib.X.CopyFromParent, override_redirect=get_override_redirect()) top_ = lambda x, y, w, h: [0, 0, y + h, 0, 0, 0, 0, 0, x, x + w, 0, 0] bottom_ = lambda x, y, w, h: [0, 0, 0, y + h, 0, 0, 0, 0, 0, 0, x, x + w] window.set_wm_name('xpybar') window.set_wm_icon_name('xpybar') window.set_wm_class('bar', 'xpybar') window.set_wm_client_machine(os.uname().nodename) position = (top_ if at_top else bottom_)(left, ypos, width, panel_height) _CARD = display.intern_atom("CARDINAL") _PSTRUT = display.intern_atom("_NET_WM_STRUT_PARTIAL") _STRUT = display.intern_atom("_NET_WM_STRUT") _DESKTOP = display.intern_atom("_NET_WM_DESKTOP") _PID = display.intern_atom("_NET_WM_PID") window.change_property(_PSTRUT, _CARD, 32, position) window.change_property(_STRUT, _CARD, 32, position[:4]) window.change_property(_DESKTOP, _CARD, 32, [0xFFFFFFFF]) window.change_property(_PID, _CARD, 32, [os.getpid()]) _ATOM = display.intern_atom("ATOM") _TYPE = display.intern_atom("_NET_WM_WINDOW_TYPE") _DOCK = display.intern_atom("_NET_WM_WINDOW_TYPE_DOCK") window.change_property(_TYPE, _ATOM, 32, [_DOCK]) return window
def get_active_window_wm_name(quiet, display=Xlib.display.Display()): """Get active window's WM_CLASS""" atom = display.intern_atom('_NET_WM_NAME') current_window = display.get_input_focus().focus name = get_window_name(current_window, atom) if not quiet: print(name) if name: # (process name, class name) return str(name.decode('utf-8')) else: return ""
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 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 create_panel(width, height, left, ypos, panel_height, at_top): ''' Create a docked panel, not mapped yet @param width:int The width of the output @param height:int The height of the output @param left:int The left position of the output @param ypos:int The position of the panel in relation to either the top or bottom edge of the output @param panel_height:int The height of the panel @param at_top:bool Whether the panel is to be docked to the top of the output, otherwise to the bottom @return The window ''' global display, screen ypos = ypos if at_top else (height - ypos - panel_height) window = screen.root.create_window(left, ypos, width, panel_height, 0, Xlib.X.CopyFromParent, Xlib.X.InputOutput, Xlib.X.CopyFromParent, event_mask = get_event_mask(), colormap = Xlib.X.CopyFromParent, override_redirect = get_override_redirect()) top_ = lambda x, y, w, h : [0, 0, y + h, 0, 0, 0, 0, 0, x, x + w, 0, 0] bottom_ = lambda x, y, w, h : [0, 0, 0, y + h, 0, 0, 0, 0, 0, 0, x, x + w] window.set_wm_name('xpybar') window.set_wm_icon_name('xpybar') window.set_wm_class('bar', 'xpybar') window.set_wm_client_machine(os.uname().nodename) position = (top_ if at_top else bottom_)(left, ypos, width, panel_height) _CARD = display.intern_atom("CARDINAL") _PSTRUT = display.intern_atom("_NET_WM_STRUT_PARTIAL") _STRUT = display.intern_atom("_NET_WM_STRUT") _DESKTOP = display.intern_atom("_NET_WM_DESKTOP") _PID = display.intern_atom("_NET_WM_PID") window.change_property(_PSTRUT, _CARD, 32, position) window.change_property(_STRUT, _CARD, 32, position[:4]) window.change_property(_DESKTOP, _CARD, 32, [0xFFFFFFFF]) window.change_property(_PID, _CARD, 32, [os.getpid()]) _ATOM = display.intern_atom("ATOM") _TYPE = display.intern_atom("_NET_WM_WINDOW_TYPE") _DOCK = display.intern_atom("_NET_WM_WINDOW_TYPE_DOCK") window.change_property(_TYPE, _ATOM, 32, [_DOCK]) return window
def getWindowIds(processId): root = screen.root; tree = root.query_tree(); wins = tree.children; atom = display.intern_atom("_NET_WM_PID", 1); # recursively searches the window tree # for the one that has a desired pid result = set() for win in wins: result |= _processWindow(win, atom, processId) return result
def main(): args = parse_args() ckb = CKBPipe(args.ckb_pipe) display = Xlib.display.Display() atom = display.intern_atom('_NET_CURRENT_DESKTOP', True) window = display.screen().root highlight_current_workspace(ckb, window, atom) window.change_attributes(event_mask=X.PropertyChangeMask) while True: ev = display.next_event() if ev.type == X.PropertyNotify and ev.state == X.PropertyNewValue and ev.window == window and ev.atom == atom: highlight_current_workspace(ckb, window, atom)
def get_active_window_id_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] except Xlib.error.XError: #simplify dealing with BadWindow window_id = None return window_id
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 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 get_selection(): display = Xlib.display.Display() xsel_data_atom = display.intern_atom("XSEL_DATA") screen = display.screen() w = screen.root.create_window(0, 0, 2, 2, 0, screen.root_depth) w.convert_selection(Xlib.Xatom.PRIMARY, Xlib.Xatom.STRING, xsel_data_atom, Xlib.X.CurrentTime) while True: e = display.next_event() if e.type == Xlib.X.SelectionNotify: break assert e.property == xsel_data_atom assert e.target == Xlib.Xatom.STRING reply = w.get_full_property(xsel_data_atom, Xlib.X.AnyPropertyType) return reply.value
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 set_active_window_by_pointer(): ''' Function to set window as active based on where the mouse pointer is located ''' import Xlib from Xlib.display import Display from Xlib import X display = Display() root = display.screen().root window = root.query_pointer().child window.set_input_focus(X.RevertToParent, X.CurrentTime) window.configure(stack_mode=X.Above) display.sync() # get active window NET_ACTIVE_WINDOW = display.intern_atom('_NET_ACTIVE_WINDOW') try: window_id = root.get_full_property(NET_ACTIVE_WINDOW, Xlib.X.AnyPropertyType).value[0] except Xlib.error.XError: #simplify dealing with BadWindow window_id = None return window_id
def get_x_selection(): import Xlib.display # from the python X library, http://python-xlib.sf.net/ import Xlib.X import Xlib.Xatom display = Xlib.display.Display() xsel_data_atom = display.intern_atom("XSEL_DATA") screen = display.screen() w = screen.root.create_window(0, 0, 2, 2, 0, screen.root_depth) w.convert_selection(Xlib.Xatom.PRIMARY, # selection Xlib.Xatom.STRING, # target xsel_data_atom, # property Xlib.X.CurrentTime) # time while True: e = display.next_event() if e.type == Xlib.X.SelectionNotify: break assert e.property == xsel_data_atom assert e.target == Xlib.Xatom.STRING reply = w.get_full_property(xsel_data_atom, Xlib.X.AnyPropertyType) return reply.value
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}
from time import time import Xlib, Xlib.display NUM_NAMES = 500 NAMES = ['NAME%d' % i for i in xrange(NUM_NAMES)] atoms = [] display = Xlib.display.Display() begin = time() for name in NAMES: atoms.append(display.intern_atom(name)) end = time() print 'Elapsed time: %f' % (end - begin)
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)
root = screen.root window = root.create_window( 0, 0, 800, 600, 0, screen.root_depth, window_class=Xlib.X.InputOutput, visual=Xlib.X.CopyFromParent, colormap=Xlib.X.CopyFromParent, event_mask=( Xlib.X.ExposureMask |Xlib.X.ButtonPressMask |Xlib.X.ButtonReleaseMask |Xlib.X.EnterWindowMask ) ) _WIN_STATE = display.intern_atom("_WIN_STATE") _MOTIF_WM_HINTS = display.intern_atom("_MOTIF_WM_HINTS") window.set_wm_name("PyPanel") window.set_wm_class("pypanel","PyPanel") window.set_wm_hints(flags=(Xlib.Xutil.InputHint|Xlib.Xutil.StateHint), input=0, initial_state=1) window.set_wm_normal_hints(flags=(Xlib.Xutil.PPosition|Xlib.Xutil.PMaxSize|Xlib.Xutil.PMinSize), min_width=800, min_height=600, max_width=800, max_height=600) window.change_property(_WIN_STATE,Xlib.Xatom.CARDINAL,32,[1]) window.change_property(_MOTIF_WM_HINTS, _MOTIF_WM_HINTS, 32, [0x2, 0x0, 0x0, 0x0, 0x0]) #window.change_property(self._DESKTOP, Xatom.CARDINAL, 32, [0xffffffffL]) #window.change_property(dsp.intern_atom("_NET_WM_WINDOW_TYPE"), #Xatom.ATOM, 32, [dsp.intern_atom("_NET_WM_WINDOW_TYPE_DOCK")])
def get_prop(window, prop_name): return window.get_full_property(display.intern_atom(prop_name), Xlib.X.AnyPropertyType).value
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 win_is_hidden = (display.intern_atom("_NET_WM_STATE_MINIMIZED") in win_state or display.intern_atom("_NET_WM_STATE_HIDDEN") in win_state) win_instance, win_class = win_handle.get_wm_class() win_name = win_handle.get_wm_name() if win_is_hidden or win_class in ignore_classes or win_name in ignore_names: continue # Don't process these win_geometry = win_handle.get_geometry() # It's more reliable to translate the upper left of this window into # root-based coords than to use the x and y returned by get_geometry win_coords = win_handle.translate_coords(root, 0, 0) x = -1 * win_coords.x
#!/usr/bin/env python import Xlib.display display = Xlib.display.Display() display.intern_atom('_NET_WM_STATE_HIDDEN', False)
def resize_this(): 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()
#! /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_active_window(root, display): _net_active_window = display.intern_atom('_NET_ACTIVE_WINDOW') return root.get_full_property(_net_active_window, Xlib.X.AnyPropertyType).value[0]
def sendViaClipboard(blobs, record = None, txtselections = defSelections, ui=ui_null()): """ Send a list of blobs via the clipboard (using X selections, cut buffers are not yet supported) in sequence. Typically the PRIMARY and/or SECONDARY selections are used for middle click and shift+insert pasting, while the CLIPBOARD selection is often used by Ctrl+V pasting. Raises an XFailConnection exception if connecting to the X DISPLAY failed. """ global Xlib, X, Xatom, Xerror if Xlib is None: ui.status('Initialising python-Xlib, stand by...') ui.mainloop.draw_screen() try: from Xlib import X, Xatom, error as Xerror import Xlib.display except ImportError: ui.status('Error importing python-Xlib, X clipboard integration unavailable') return # Can't do this in the function definition - it seems that a .remove() # affects the default. That would be expected if it were assigned as a # reference to the default list, but even happens when the [:] syntax is # used to copy the list. I guess that must be an unexpected side effect of # the function definition only excuting once when the file is loaded? txtselections = txtselections[:] selections = txtselections[:] def findClientWindow(window, ui): """ walk up the tree looking for a client window """ def get_wm_client_leader(window): d = window.get_full_property(Xatom.WM_CLIENT_LEADER, Xatom.WINDOW) if d is None or d.format != 32 or len(d.value) < 1: return None else: cls = window.display.get_resource_class('window', type(window)) return cls(window.display, d.value[0]) host = window.get_wm_client_machine() while True: comm = window.get_full_property(Xatom.WM_COMMAND, Xatom.STRING) name = window.get_wm_name() # Nokia N900 uses _NET_WM_NAME instead of WM_NAME: netname = window.get_full_property(Xatom._NET_WM_NAME, Xatom.UTF8_STRING) leadercomm = None # Only one top-level window for a given client has WM_COMMAND. Find the # leader top-level window (if we are looking at a top-level window) and # check it's WM_COMMAND property. # # I don't see a requirement in the ICCCM that the client leader # necessarily be the window with the WM_COMMAND property, it may end up # being necessary to iterate all the windows with the same # WM_CLIENT_LEADER to find the one window that has the WM_COMMAND. leader = get_wm_client_leader(window) if leader is not None and leader != window: leadercomm = leader.get_full_property(Xatom.WM_COMMAND, Xatom.STRING) requestor = name or netname or comm or leadercomm if hasattr(requestor, 'value'): requestor = requestor.value if requestor: break resp = window.query_tree() root = resp.root; parent = resp.parent if parent == root: return ('<unknown>', host) window = parent return (requestor, host) def handleSelectionRequest(e, field, record, ui): global _prev_requestor if ((e.time != X.CurrentTime and e.time < timestamp) or # Timestamp out of bounds (e.selection not in selections) or # Requesting a different selection (e.owner.id != win.id)): # We aren't the owner return _refuseSelectionRequest(e) if (e.target in (Xatom.STRING, Xatom.TEXT)): (requestor, host) = findClientWindow(e.requestor, ui) if requestor.lower() in blacklist or any([ pattern.match(requestor) for pattern in blacklist_re ]): if requestor != _prev_requestor: ui.status("Ignoring request from %s@%s"%(requestor, host), append=True) _prev_requestor = requestor return _refuseSelectionRequest(e) ui.status("Sent %s for '%s' via %s to %s@%s"%(field.upper(), record, display.get_atom_name(e.selection), requestor, host), append=True) oldmask = e.requestor.get_attributes().your_event_mask e.requestor.change_attributes(event_mask = oldmask | X.PropertyChangeMask) _sendSelection(blob, Xatom.STRING, 8, e, ui) return True elif (e.target == Xatom.TIMESTAMP): _sendSelection([timestamp], Xatom.TIMESTAMP, 32, e, ui) elif (e.target == Xatom.TARGETS): _sendSelection([Xatom.TARGETS, Xatom.TIMESTAMP, Xatom.TEXT, Xatom.STRING], Xatom.ATOM, 32, e, ui) else: return _refuseSelectionRequest(e) return False # Opening the display prints 'Xlib.protocol.request.QueryExtension' to # stdout, so temporarily redirect it: ui.status('Connecting to display, stand by...') ui.mainloop.draw_screen() import sys, StringIO saved_stdout = sys.stdout sys.stdout = StringIO.StringIO() try: display = Xlib.display.Display() except Xerror.DisplayError: raise XFailConnection() finally: sys.stdout = saved_stdout screen = display.screen() win = screen.root.create_window(0,0,1,1,0,0) Xatom.TEXT = display.intern_atom('TEXT', True) Xatom.TARGETS = display.intern_atom('TARGETS', True) Xatom.TIMESTAMP = display.intern_atom('TIMESTAMP', True) Xatom.WM_CLIENT_LEADER = display.intern_atom('WM_CLIENT_LEADER', True) Xatom._NET_WM_NAME = display.intern_atom('_NET_WM_NAME', True) Xatom.UTF8_STRING = display.intern_atom('UTF8_STRING', True) ui_fds = ui.mainloop.screen.get_input_descriptors() if ui_fds is None: ui_fds = [] select_fds = set([display] + ui_fds) try: old = ui_tty.set_cbreak() # Set unbuffered IO (if not already) ui.status('') for (field, blob) in blobs: ui.status("Ready to send %s for '%s' via %s... (enter skips, escape cancels)"%(field.upper(),record,str(txtselections)), append=True) ui.mainloop.draw_screen() awaitingCompletion = [] timestamp = _ownSelections(display, win, selections) timeout = None skip = False while 1: if skip and awaitingCompletion == []: break while True: try: (readable, ign, ign) = select.select(select_fds, [], [], timeout) except select.error as e: if e.args[0] == 4: continue # Interrupted system call raise break if not readable and awaitingCompletion == []: break for fd in readable: if fd == sys.stdin.fileno(): char = sys.stdin.read(1) if char == '\n': skip = True elif char == '\x1b': return elif fd in ui_fds: # This is a hack to redraw the screen - we really should # restructure all this so as not to block instead: ui.mainloop.event_loop._loop() if fd == display: while display.pending_events(): e = display.next_event() if e.type == X.SelectionRequest: if handleSelectionRequest(e, field, record, ui): # Don't break immediately, transfer will not have finished. # Wait until the property has been deleted by the requestor awaitingCompletion.append((e.requestor, e.property)) elif e.type == X.PropertyNotify: if (e.window, e.atom) in awaitingCompletion \ and e.state == 1: # Deleted awaitingCompletion.remove((e.window, e.atom)) # Some programs, such as firefox (when pasting with # shift+insert), don't expect the selection to change suddenly # and behave badly if it does, so wait a moment before ending: timeout = 0.01 elif e.type == X.SelectionClear: if e.time == X.CurrentTime or e.time >= timestamp: # If we lost CLIPBOARD (explicit copy) or no longer control any selection, abort: name = display.get_atom_name(e.atom) selections.remove(e.atom) txtselections.remove(name) if name == 'CLIPBOARD' or not selections: # If transfer is in progress it should be allowed to complete: if awaitingCompletion == []: return timeout = 0.01 else: ui.status("Lost control of %s, still ready to send %s via %s..."%(name, field.upper() ,str(txtselections)), append=True) ui.mainloop.draw_screen() ui.mainloop.draw_screen() finally: ui_tty.restore_cbreak(old) win.destroy() display.close() # I may have introduced a bug while adding the urwid loop # stuff here - the clipboard selection remained grabbed # after destroying the window. This worked around it since # I can't see what is wrong. ui.status('Clipboard Cleared', append=True)
import logging from pybar.lib.dzenparser import Dzen2HTMLFormatter from PyQt5.QtCore import Qt, QRect, pyqtSignal from PyQt5.QtWidgets import QWidget, QVBoxLayout from PyQt5.QtWebKitWidgets import QWebView, QWebPage import Xlib.display try: import urlparse except: import urllib.parse as urlparse display = Xlib.display.Display() root = display.screen().root atom_strut = display.intern_atom("_NET_WM_STRUT") atom_strut_partial = display.intern_atom("_NET_WM_STRUT_PARTIAL") atom_cardinal = display.intern_atom('CARDINAL') atom_net_system_tray = display.intern_atom( "_NET_SYSTEM_TRAY_S%d" % display.get_default_screen()) atom_manager = display.intern_atom("MANAGER") atom_tray_opcode = display.intern_atom("_NET_SYSTEM_TRAY_OPCODE") atom_net_wm_pid = display.intern_atom("_NET_WM_PID") FGCOLOR = "#FFFFFF" BGCOLOR = "#1B1D1E" iconpath = os.path.abspath(os.path.dirname(__file__)) + "/icons" class Bar:
from typing import Optional import logging import Xlib import Xlib.display from Xlib.xobject.drawable import Window from Xlib import X, Xatom import psutil logger = logging.getLogger(__name__) display = Xlib.display.Display() screen = display.screen() NET_WM_NAME = display.intern_atom("_NET_WM_NAME") UTF8_STRING = display.intern_atom("UTF8_STRING") def _get_current_window_id() -> Optional[int]: atom = display.get_atom("_NET_ACTIVE_WINDOW") window_prop = screen.root.get_full_property(atom, X.AnyPropertyType) if window_prop is None: logger.warning("window_prop was None") return None # window_prop may contain more than one value, but it seems that it's always the first we want. # The second has in my attempts always been 0 or rubbish. window_id = window_prop.value[0] return window_id if window_id != 0 else None
#!/usr/bin/python # code from: # - https://unix.stackexchange.com/questions/5999/setting-the-window-dimensions-of-a-running-application # deps: # - sudo apt-get install -y python-xlib import Xlib import Xlib.display WIDTH, HEIGHT = 840, 480 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) window.configure(width = WIDTH, height = HEIGHT) display.sync()
def __init__(self, output, width, height, xpos, ypos, left, top, font = None, background = None, foreground = None, event_mask = None, override_redirect = True): ''' Constructor @param output:int The index of the output within the screen as printed by xrandr, except primary is first @param width:int The width of the menu @param height:int The height of the menu @param xpos:int The position of the menu in relation the either the left or right edge of the output @param ypos:int The position of the menu in relation the either the top or bottom edge of the output @param left:int Whether the menu is positioned relative to the left of the output, otherwise to the right @param top:int Whether the menu is positioned relative to the top of the output, otherwise to the bottom @param font:str? The default font, `None` for the default @param background:(red:int, green:int, blue:int)? The default background, `None` for the default @param foreground:(red:int, green:int, blue:int)? The default foreground, `None` for the default @param event:int? Mask of events that should be caught, `None` for the default @param override_redirect:bool Whether override_redirect should be set ''' import os import Xlib.display, Xlib.Xatom, Xlib.ext.randr, Xlib.X if not Menu.methods_set: Menu.map = Bar.map Menu.unmap = Bar.unmap Menu.text_width = Bar.text_width Menu.draw_text = Bar.draw_text Menu.draw_coloured_text = Bar.draw_coloured_text Menu.draw_coloured_splitted_text = Bar.draw_coloured_splitted_text Menu.create_colour = Bar.create_colour Menu.create_font = Bar.create_font Menu.change_colour = Bar.change_colour Menu.change_font = Bar.change_font Menu.clear_rectangle = Bar.clear_rectangle Menu.clear = Bar.clear Menu.invalidate = Bar.invalidate Menu.coloured_length = Bar.coloured_length Menu.methods_set = True if event_mask is None: event_mask = ( Xlib.X.StructureNotifyMask | Xlib.X.ButtonPressMask | Xlib.X.ButtonReleaseMask | Xlib.X.ExposureMask | Xlib.X.KeyPress | Xlib.X.KeyRelease | Xlib.X.MotionNotify | Xlib.X.EnterNotify | Xlib.X.LeaveNotify ) if font is None: font = FONT if background is None: background = BACKGROUND if foreground is None: foreground = FOREGROUND [self.width, self.height, self.left, self.top] = outputs[output][:4] [self.ypos, self.panel_height, self.at_top] = [ypos, height, top] self.left += xpos if left else (self.width - xpos - width) self.top += ypos if top else (self.height - ypos - height) self.width = width self.window = screen.root.create_window(self.left, self.top, self.width, self.panel_height, 0, Xlib.X.CopyFromParent, Xlib.X.InputOutput, Xlib.X.CopyFromParent, event_mask = event_mask, colormap = Xlib.X.CopyFromParent, override_redirect = override_redirect) self.window.set_wm_name('xpybar') self.window.set_wm_icon_name('xpybar') self.window.set_wm_class('menu', 'xpybar') self.window.set_wm_client_machine(os.uname().nodename) _CARD = display.intern_atom("CARDINAL") _DESKTOP = display.intern_atom("_NET_WM_DESKTOP") _PID = display.intern_atom("_NET_WM_PID") self.window.change_property(_DESKTOP, _CARD, 32, [0xFFFFFFFF]) self.window.change_property(_PID, _CARD, 32, [os.getpid()]) _ATOM = display.intern_atom("ATOM") _TYPE = display.intern_atom("_NET_WM_WINDOW_TYPE") _NORMAL = display.intern_atom("_NET_WM_WINDOW_TYPE_NORMAL") self.window.change_property(_TYPE, _ATOM, 32, [_NORMAL]) self.gc = self.window.create_gc() self.cmap = self.window.get_attributes().colormap self.cmap_cache = {} self.background = self.create_colour(*background) self.foreground = self.create_colour(*foreground) (self.font, self.font_metrics, self.font_height) = self.create_font(font) self.font_width = self.text_width('X') self.palette = [0x000000, 0xCD656C, 0x32A679, 0xCCAD47, 0x2495BE, 0xA46EB0, 0x00A09F, 0xD8D8D8] self.palette += [0x555555, 0xEB5E6A, 0x0EC287, 0xF2CA38, 0x00ACE0, 0xC473D1, 0x00C3C7, 0xEEEEEE] self.palette = [((p >> 16) & 255, (p >> 8) & 255, p & 255) for p in self.palette] self.palette = [self.create_colour(*p) for p in self.palette]
def __init__(self, output, width, height, xpos, ypos, left, top, font=None, background=None, foreground=None, event_mask=None, override_redirect=True): ''' Constructor @param output:int The index of the output within the screen as printed by xrandr, except primary is first @param width:int The width of the menu @param height:int The height of the menu @param xpos:int The position of the menu in relation the either the left or right edge of the output @param ypos:int The position of the menu in relation the either the top or bottom edge of the output @param left:int Whether the menu is positioned relative to the left of the output, otherwise to the right @param top:int Whether the menu is positioned relative to the top of the output, otherwise to the bottom @param font:str? The default font, `None` for the default @param background:(red:int, green:int, blue:int)? The default background, `None` for the default @param foreground:(red:int, green:int, blue:int)? The default foreground, `None` for the default @param event:int? Mask of events that should be caught, `None` for the default @param override_redirect:bool Whether override_redirect should be set ''' import os import Xlib.display, Xlib.Xatom, Xlib.ext.randr, Xlib.X if not Menu.methods_set: Menu.map = Bar.map Menu.unmap = Bar.unmap Menu.text_width = Bar.text_width Menu.draw_text = Bar.draw_text Menu.draw_coloured_text = Bar.draw_coloured_text Menu.draw_coloured_splitted_text = Bar.draw_coloured_splitted_text Menu.create_colour = Bar.create_colour Menu.create_font = Bar.create_font Menu.change_colour = Bar.change_colour Menu.change_font = Bar.change_font Menu.clear_rectangle = Bar.clear_rectangle Menu.clear = Bar.clear Menu.invalidate = Bar.invalidate Menu.coloured_length = Bar.coloured_length Menu.methods_set = True if event_mask is None: event_mask = (Xlib.X.StructureNotifyMask | Xlib.X.ButtonPressMask | Xlib.X.ButtonReleaseMask | Xlib.X.ExposureMask | Xlib.X.KeyPress | Xlib.X.KeyRelease | Xlib.X.MotionNotify | Xlib.X.EnterNotify | Xlib.X.LeaveNotify) if font is None: font = FONT if background is None: background = BACKGROUND if foreground is None: foreground = FOREGROUND [self.width, self.height, self.left, self.top] = outputs[output][:4] [self.ypos, self.panel_height, self.at_top] = [ypos, height, top] self.left += xpos if left else (self.width - xpos - width) self.top += ypos if top else (self.height - ypos - height) self.width = width self.window = screen.root.create_window( self.left, self.top, self.width, self.panel_height, 0, Xlib.X.CopyFromParent, Xlib.X.InputOutput, Xlib.X.CopyFromParent, event_mask=event_mask, colormap=Xlib.X.CopyFromParent, override_redirect=override_redirect) self.window.set_wm_name('xpybar') self.window.set_wm_icon_name('xpybar') self.window.set_wm_class('menu', 'xpybar') self.window.set_wm_client_machine(os.uname().nodename) _CARD = display.intern_atom("CARDINAL") _DESKTOP = display.intern_atom("_NET_WM_DESKTOP") _PID = display.intern_atom("_NET_WM_PID") self.window.change_property(_DESKTOP, _CARD, 32, [0xFFFFFFFF]) self.window.change_property(_PID, _CARD, 32, [os.getpid()]) _ATOM = display.intern_atom("ATOM") _TYPE = display.intern_atom("_NET_WM_WINDOW_TYPE") _NORMAL = display.intern_atom("_NET_WM_WINDOW_TYPE_NORMAL") self.window.change_property(_TYPE, _ATOM, 32, [_NORMAL]) self.gc = self.window.create_gc() self.cmap = self.window.get_attributes().colormap self.cmap_cache = {} self.background = self.create_colour(*background) self.foreground = self.create_colour(*foreground) (self.font, self.font_metrics, self.font_height) = self.create_font(font) self.font_width = self.text_width('X') self.palette = [ 0x000000, 0xCD656C, 0x32A679, 0xCCAD47, 0x2495BE, 0xA46EB0, 0x00A09F, 0xD8D8D8 ] self.palette += [ 0x555555, 0xEB5E6A, 0x0EC287, 0xF2CA38, 0x00ACE0, 0xC473D1, 0x00C3C7, 0xEEEEEE ] self.palette = [((p >> 16) & 255, (p >> 8) & 255, p & 255) for p in self.palette] self.palette = [self.create_colour(*p) for p in self.palette]