Search is not available for this dataset
text
stringlengths
75
104k
def getobjectinfo(self, window_name, object_name): """ Get object properties. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: list of properties @rtype: list """ try: obj_info = self._get_object_map(window_name, object_name, wait_for_object=False) except atomac._a11y.ErrorInvalidUIElement: # During the test, when the window closed and reopened # ErrorInvalidUIElement exception will be thrown self._windows = {} # Call the method again, after updating apps obj_info = self._get_object_map(window_name, object_name, wait_for_object=False) props = [] if obj_info: for obj_prop in obj_info.keys(): if not obj_info[obj_prop] or obj_prop == "obj": # Don't add object handle to the list continue props.append(obj_prop) return props
def getobjectproperty(self, window_name, object_name, prop): """ Get object property value. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param prop: property name. @type prop: string @return: property @rtype: string """ try: obj_info = self._get_object_map(window_name, object_name, wait_for_object=False) except atomac._a11y.ErrorInvalidUIElement: # During the test, when the window closed and reopened # ErrorInvalidUIElement exception will be thrown self._windows = {} # Call the method again, after updating apps obj_info = self._get_object_map(window_name, object_name, wait_for_object=False) if obj_info and prop != "obj" and prop in obj_info: if prop == "class": # ldtp_class_type are compatible with Linux and Windows class name # If defined class name exist return that, # else return as it is return ldtp_class_type.get(obj_info[prop], obj_info[prop]) else: return obj_info[prop] raise LdtpServerException('Unknown property "%s" in %s' % \ (prop, object_name))
def getchild(self, window_name, child_name='', role='', parent=''): """ Gets the list of object available in the window, which matches component name or role name or both. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param child_name: Child name to search for. @type child_name: string @param role: role name to search for, or an empty string for wildcard. @type role: string @param parent: parent name to search for, or an empty string for wildcard. @type role: string @return: list of matched children names @rtype: list """ matches = [] if role: role = re.sub(' ', '_', role) self._windows = {} if parent and (child_name or role): _window_handle, _window_name = \ self._get_window_handle(window_name)[0:2] if not _window_handle: raise LdtpServerException('Unable to find window "%s"' % \ window_name) appmap = self._get_appmap(_window_handle, _window_name) obj = self._get_object_map(window_name, parent) def _get_all_children_under_obj(obj, child_list): if role and obj['class'] == role: child_list.append(obj['label']) elif child_name and self._match_name_to_appmap(child_name, obj): child_list.append(obj['label']) if obj: children = obj['children'] if not children: return child_list for child in children.split(): return _get_all_children_under_obj( \ appmap[child], child_list) matches = _get_all_children_under_obj(obj, []) if not matches: if child_name: _name = 'name "%s" ' % child_name if role: _role = 'role "%s" ' % role if parent: _parent = 'parent "%s"' % parent exception = 'Could not find a child %s%s%s' % (_name, _role, _parent) raise LdtpServerException(exception) return matches _window_handle, _window_name = \ self._get_window_handle(window_name)[0:2] if not _window_handle: raise LdtpServerException('Unable to find window "%s"' % \ window_name) appmap = self._get_appmap(_window_handle, _window_name) for name in appmap.keys(): obj = appmap[name] # When only role arg is passed if role and not child_name and obj['class'] == role: matches.append(name) # When parent and child_name arg is passed if parent and child_name and not role and \ self._match_name_to_appmap(parent, obj): matches.append(name) # When only child_name arg is passed if child_name and not role and \ self._match_name_to_appmap(child_name, obj): return name matches.append(name) # When role and child_name args are passed if role and child_name and obj['class'] == role and \ self._match_name_to_appmap(child_name, obj): matches.append(name) if not matches: _name = '' _role = '' _parent = '' if child_name: _name = 'name "%s" ' % child_name if role: _role = 'role "%s" ' % role if parent: _parent = 'parent "%s"' % parent exception = 'Could not find a child %s%s%s' % (_name, _role, _parent) raise LdtpServerException(exception) return matches
def launchapp(self, cmd, args=[], delay=0, env=1, lang="C"): """ Launch application. @param cmd: Command line string to execute. @type cmd: string @param args: Arguments to the application @type args: list @param delay: Delay after the application is launched @type delay: int @param env: GNOME accessibility environment to be set or not @type env: int @param lang: Application language to be used @type lang: string @return: 1 on success @rtype: integer @raise LdtpServerException: When command fails """ try: atomac.NativeUIElement.launchAppByBundleId(cmd) return 1 except RuntimeError: if atomac.NativeUIElement.launchAppByBundlePath(cmd, args): # Let us wait so that the application launches try: time.sleep(int(delay)) except ValueError: time.sleep(5) return 1 else: raise LdtpServerException(u"Unable to find app '%s'" % cmd)
def activatewindow(self, window_name): """ Activate window. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: 1 on success. @rtype: integer """ window_handle = self._get_window_handle(window_name) self._grabfocus(window_handle) return 1
def click(self, window_name, object_name): """ Click item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) size = self._getobjectsize(object_handle) self._grabfocus(object_handle) self.wait(0.5) # If object doesn't support Press, trying clicking with the object # coordinates, where size=(x, y, width, height) # click on center of the widget # Noticed this issue on clicking AXImage # click('Instruments*', 'Automation') self.generatemouseevent(size[0] + size[2] / 2, size[1] + size[3] / 2, "b1c") return 1
def getallstates(self, window_name, object_name): """ Get all states of given object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: list of string on success. @rtype: list """ object_handle = self._get_object_handle(window_name, object_name) _obj_states = [] if object_handle.AXEnabled: _obj_states.append("enabled") if object_handle.AXFocused: _obj_states.append("focused") else: try: if object_handle.AXFocused: _obj_states.append("focusable") except: pass if re.match("AXCheckBox", object_handle.AXRole, re.M | re.U | re.L) or \ re.match("AXRadioButton", object_handle.AXRole, re.M | re.U | re.L): if object_handle.AXValue: _obj_states.append("checked") return _obj_states
def hasstate(self, window_name, object_name, state, guiTimeOut=0): """ has state @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @type window_name: string @param state: State of the current object. @type object_name: string @param guiTimeOut: Wait timeout in seconds @type guiTimeOut: integer @return: 1 on success. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if state == "enabled": return int(object_handle.AXEnabled) elif state == "focused": return int(object_handle.AXFocused) elif state == "focusable": return int(object_handle.AXFocused) elif state == "checked": if re.match("AXCheckBox", object_handle.AXRole, re.M | re.U | re.L) or \ re.match("AXRadioButton", object_handle.AXRole, re.M | re.U | re.L): if object_handle.AXValue: return 1 except: pass return 0
def getobjectsize(self, window_name, object_name=None): """ Get object size @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: x, y, width, height on success. @rtype: list """ if not object_name: handle, name, app = self._get_window_handle(window_name) else: handle = self._get_object_handle(window_name, object_name) return self._getobjectsize(handle)
def grabfocus(self, window_name, object_name=None): """ Grab focus. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ if not object_name: handle, name, app = self._get_window_handle(window_name) else: handle = self._get_object_handle(window_name, object_name) return self._grabfocus(handle)
def guiexist(self, window_name, object_name=None): """ Checks whether a window or component exists. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ try: self._windows = {} if not object_name: handle, name, app = self._get_window_handle(window_name, False) else: handle = self._get_object_handle(window_name, object_name, wait_for_object=False, force_remap=True) # If window and/or object exist, exception will not be thrown # blindly return 1 return 1 except LdtpServerException: pass return 0
def waittillguiexist(self, window_name, object_name='', guiTimeOut=30, state=''): """ Wait till a window or component exists. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param guiTimeOut: Wait timeout in seconds @type guiTimeOut: integer @param state: Object state used only when object_name is provided. @type object_name: string @return: 1 if GUI was found, 0 if not. @rtype: integer """ timeout = 0 while timeout < guiTimeOut: if self.guiexist(window_name, object_name): return 1 # Wait 1 second before retrying time.sleep(1) timeout += 1 # Object and/or window doesn't appear within the timeout period return 0
def waittillguinotexist(self, window_name, object_name='', guiTimeOut=30): """ Wait till a window does not exist. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param guiTimeOut: Wait timeout in seconds @type guiTimeOut: integer @return: 1 if GUI has gone away, 0 if not. @rtype: integer """ timeout = 0 while timeout < guiTimeOut: if not self.guiexist(window_name, object_name): return 1 # Wait 1 second before retrying time.sleep(1) timeout += 1 # Object and/or window still appears within the timeout period return 0
def objectexist(self, window_name, object_name): """ Checks whether a window or component exists. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 if GUI was found, 0 if not. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) return 1 except LdtpServerException: return 0
def stateenabled(self, window_name, object_name): """ Check whether an object state is enabled or not @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success 0 on failure. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if object_handle.AXEnabled: return 1 except LdtpServerException: pass return 0
def check(self, window_name, object_name): """ Check item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ # FIXME: Check for object type object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) if object_handle.AXValue == 1: # Already checked return 1 # AXPress doesn't work with Instruments # So did the following work around self._grabfocus(object_handle) x, y, width, height = self._getobjectsize(object_handle) # Mouse left click on the object # Note: x + width/2, y + height / 2 doesn't work self.generatemouseevent(x + width / 2, y + height / 2, "b1c") return 1
def verifycheck(self, window_name, object_name): """ Verify check item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success 0 on failure. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name, wait_for_object=False) if object_handle.AXValue == 1: return 1 except LdtpServerException: pass return 0
def getaccesskey(self, window_name, object_name): """ Get access key of given object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: access key in string format on success, else LdtpExecutionError on failure. @rtype: string """ # Used http://www.danrodney.com/mac/ as reference for # mapping keys with specific control # In Mac noticed (in accessibility inspector) only menu had access keys # so, get the menu_handle of given object and # return the access key menu_handle = self._get_menu_handle(window_name, object_name) key = menu_handle.AXMenuItemCmdChar modifiers = menu_handle.AXMenuItemCmdModifiers glpyh = menu_handle.AXMenuItemCmdGlyph virtual_key = menu_handle.AXMenuItemCmdVirtualKey modifiers_type = "" if modifiers == 0: modifiers_type = "<command>" elif modifiers == 1: modifiers_type = "<shift><command>" elif modifiers == 2: modifiers_type = "<option><command>" elif modifiers == 3: modifiers_type = "<option><shift><command>" elif modifiers == 4: modifiers_type = "<ctrl><command>" elif modifiers == 6: modifiers_type = "<ctrl><option><command>" # Scroll up if virtual_key == 115 and glpyh == 102: modifiers = "<option>" key = "<cursor_left>" # Scroll down elif virtual_key == 119 and glpyh == 105: modifiers = "<option>" key = "<right>" # Page up elif virtual_key == 116 and glpyh == 98: modifiers = "<option>" key = "<up>" # Page down elif virtual_key == 121 and glpyh == 107: modifiers = "<option>" key = "<down>" # Line up elif virtual_key == 126 and glpyh == 104: key = "<up>" # Line down elif virtual_key == 125 and glpyh == 106: key = "<down>" # Noticed in Google Chrome navigating next tab elif virtual_key == 124 and glpyh == 101: key = "<right>" # Noticed in Google Chrome navigating previous tab elif virtual_key == 123 and glpyh == 100: key = "<left>" # List application in a window to Force Quit elif virtual_key == 53 and glpyh == 27: key = "<escape>" # FIXME: # * Instruments Menu View->Run Browser # modifiers==12 virtual_key==48 glpyh==2 # * Terminal Menu Edit->Start Dictation # fn fn - glpyh==148 modifiers==24 # * Menu Chrome->Clear Browsing Data in Google Chrome # virtual_key==51 glpyh==23 [Delete Left (like Backspace on a PC)] if not key: raise LdtpServerException("No access key associated") return modifiers_type + key
def paste(cls): """Get the clipboard data ('Paste'). Returns: Data (string) retrieved or None if empty. Exceptions from AppKit will be handled by caller. """ pb = AppKit.NSPasteboard.generalPasteboard() # If we allow for multiple data types (e.g. a list of data types) # we will have to add a condition to check just the first in the # list of datatypes) data = pb.stringForType_(cls.STRING) return data
def copy(cls, data): """Set the clipboard data ('Copy'). Parameters: data to set (string) Optional: datatype if it's not a string Returns: True / False on successful copy, Any exception raised (like passes the NSPasteboardCommunicationError) should be caught by the caller. """ pp = pprint.PrettyPrinter() copy_data = 'Data to copy (put in pasteboard): %s' logging.debug(copy_data % pp.pformat(data)) # Clear the pasteboard first: cleared = cls.clearAll() if not cleared: logging.warning('Clipboard could not clear properly') return False # Prepare to write the data # If we just use writeObjects the sequence to write to the clipboard is # a) Call clearContents() # b) Call writeObjects() with a list of objects to write to the # clipboard if not isinstance(data, types.ListType): data = [data] pb = AppKit.NSPasteboard.generalPasteboard() pb_set_ok = pb.writeObjects_(data) return bool(pb_set_ok)
def clearContents(cls): """Clear contents of general pasteboard. Future enhancement can include specifying which clipboard to clear Returns: True on success; caller should expect to catch exceptions, probably from AppKit (ValueError) """ log_msg = 'Request to clear contents of pasteboard: general' logging.debug(log_msg) pb = AppKit.NSPasteboard.generalPasteboard() pb.clearContents() return True
def isEmpty(cls, datatype=None): """Method to test if the general pasteboard is empty or not with respect to the type of object you want. Parameters: datatype (defaults to strings) Returns: Boolean True (empty) / False (has contents); Raises exception (passes any raised up) """ if not datatype: datatype = AppKit.NSString if not isinstance(datatype, types.ListType): datatype = [datatype] pp = pprint.PrettyPrinter() logging.debug('Desired datatypes: %s' % pp.pformat(datatype)) opt_dict = {} logging.debug('Results filter is: %s' % pp.pformat(opt_dict)) try: log_msg = 'Request to verify pasteboard is empty' logging.debug(log_msg) pb = AppKit.NSPasteboard.generalPasteboard() # canReadObjectForClasses_options_() seems to return an int (> 0 if # True) # Need to negate to get the sense we want (True if can not read the # data type from the pasteboard) its_empty = not bool(pb.canReadObjectForClasses_options_(datatype, opt_dict)) except ValueError as error: logging.error(error) raise return bool(its_empty)
def _ldtpize_accessible(self, acc): """ Get LDTP format accessibile name @param acc: Accessible handle @type acc: object @return: object type, stripped object name (associated / direct), associated label @rtype: tuple """ actual_role = self._get_role(acc) label = self._get_title(acc) if re.match("AXWindow", actual_role, re.M | re.U | re.L): # Strip space and new line from window title strip = r"( |\n)" else: # Strip space, colon, dot, underscore and new line from # all other object types strip = r"( |:|\.|_|\n)" if label: # Return the role type (if, not in the know list of roles, # return ukn - unknown), strip the above characters from name # also return labely_by string label = re.sub(strip, u"", label) role = abbreviated_roles.get(actual_role, "ukn") if self._ldtp_debug and role == "ukn": print(actual_role, acc) return role, label
def _glob_match(self, pattern, string): """ Match given string, by escaping regex characters """ # regex flags Multi-line, Unicode, Locale return bool(re.match(fnmatch.translate(pattern), string, re.M | re.U | re.L))
def selectmenuitem(self, window_name, object_name): """ Select (click) a menu item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ menu_handle = self._get_menu_handle(window_name, object_name) if not menu_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) menu_handle.Press() return 1
def doesmenuitemexist(self, window_name, object_name): """ Check a menu item exist. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @param strict_hierarchy: Mandate menu hierarchy if set to True @type object_name: boolean @return: 1 on success. @rtype: integer """ try: menu_handle = self._get_menu_handle(window_name, object_name, False) return 1 except LdtpServerException: return 0
def menuitemenabled(self, window_name, object_name): """ Verify a menu item is enabled @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ try: menu_handle = self._get_menu_handle(window_name, object_name, False) if menu_handle.AXEnabled: return 1 except LdtpServerException: pass return 0
def listsubmenus(self, window_name, object_name): """ List children of menu item @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: menu item in list on success. @rtype: list """ menu_handle = self._get_menu_handle(window_name, object_name) role, label = self._ldtpize_accessible(menu_handle) menu_clicked = False try: if not menu_handle.AXChildren: menu_clicked = True try: menu_handle.Press() self.wait(1) except atomac._a11y.ErrorCannotComplete: pass if not menu_handle.AXChildren: raise LdtpServerException(u"Unable to find children under menu %s" % \ label) children = menu_handle.AXChildren[0] sub_menus = [] for current_menu in children.AXChildren: role, label = self._ldtpize_accessible(current_menu) if not label: # All splitters have empty label continue sub_menus.append(u"%s%s" % (role, label)) finally: if menu_clicked: menu_handle.Cancel() return sub_menus
def verifymenucheck(self, window_name, object_name): """ Verify a menu item is checked @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ try: menu_handle = self._get_menu_handle(window_name, object_name, False) try: if menu_handle.AXMenuItemMarkChar: # Checked return 1 except atomac._a11y.Error: pass except LdtpServerException: pass return 0
def menucheck(self, window_name, object_name): """ Check (click) a menu item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu heirarchy @type object_name: string @return: 1 on success. @rtype: integer """ menu_handle = self._get_menu_handle(window_name, object_name) if not menu_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) try: if menu_handle.AXMenuItemMarkChar: # Already checked return 1 except atomac._a11y.Error: pass menu_handle.Press() return 1
def _getRunningApps(cls): """Get a list of the running applications.""" def runLoopAndExit(): AppHelper.stopEventLoop() AppHelper.callLater(1, runLoopAndExit) AppHelper.runConsoleEventLoop() # Get a list of running applications ws = AppKit.NSWorkspace.sharedWorkspace() apps = ws.runningApplications() return apps
def getFrontmostApp(cls): """Get the current frontmost application. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list apps = cls._getRunningApps() for app in apps: pid = app.processIdentifier() ref = cls.getAppRefByPid(pid) try: if ref.AXFrontmost: return ref except (_a11y.ErrorUnsupported, _a11y.ErrorCannotComplete, _a11y.ErrorAPIDisabled, _a11y.ErrorNotImplemented): # Some applications do not have an explicit GUI # and so will not have an AXFrontmost attribute # Trying to read attributes from Google Chrome Helper returns # ErrorAPIDisabled for some reason - opened radar bug 12837995 pass raise ValueError('No GUI application found.')
def getAnyAppWithWindow(cls): """Get a random app that has windows. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list apps = cls._getRunningApps() for app in apps: pid = app.processIdentifier() ref = cls.getAppRefByPid(pid) if hasattr(ref, 'windows') and len(ref.windows()) > 0: return ref raise ValueError('No GUI application found.')
def launchAppByBundleId(bundleID): """Launch the application with the specified bundle ID""" # NSWorkspaceLaunchAllowingClassicStartup does nothing on any # modern system that doesn't have the classic environment installed. # Encountered a bug when passing 0 for no options on 10.6 PyObjC. ws = AppKit.NSWorkspace.sharedWorkspace() # Sorry about the length of the following line r = ws.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_( bundleID, AppKit.NSWorkspaceLaunchAllowingClassicStartup, AppKit.NSAppleEventDescriptor.nullDescriptor(), None) # On 10.6, this returns a tuple - first element bool result, second is # a number. Let's use the bool result. if not r[0]: raise RuntimeError('Error launching specified application.')
def launchAppByBundlePath(bundlePath, arguments=None): """Launch app with a given bundle path. Return True if succeed. """ if arguments is None: arguments = [] bundleUrl = NSURL.fileURLWithPath_(bundlePath) workspace = AppKit.NSWorkspace.sharedWorkspace() arguments_strings = list(map(lambda a: NSString.stringWithString_(str(a)), arguments)) arguments = NSDictionary.dictionaryWithDictionary_({ AppKit.NSWorkspaceLaunchConfigurationArguments: NSArray.arrayWithArray_( arguments_strings) }) return workspace.launchApplicationAtURL_options_configuration_error_( bundleUrl, AppKit.NSWorkspaceLaunchAllowingClassicStartup, arguments, None)
def terminateAppByBundleId(bundleID): """Terminate app with a given bundle ID. Requires 10.6. Return True if succeed. """ ra = AppKit.NSRunningApplication if getattr(ra, "runningApplicationsWithBundleIdentifier_"): appList = ra.runningApplicationsWithBundleIdentifier_(bundleID) if appList and len(appList) > 0: app = appList[0] return app and app.terminate() and True or False return False
def _postQueuedEvents(self, interval=0.01): """Private method to post queued events (e.g. Quartz events). Each event in queue is a tuple (event call, args to event call). """ while len(self.eventList) > 0: (nextEvent, args) = self.eventList.popleft() nextEvent(*args) time.sleep(interval)
def _queueEvent(self, event, args): """Private method to queue events to run. Each event in queue is a tuple (event call, args to event call). """ if not hasattr(self, 'eventList'): self.eventList = deque([(event, args)]) return self.eventList.append((event, args))
def _addKeyToQueue(self, keychr, modFlags=0, globally=False): """Add keypress to queue. Parameters: key character or constant referring to a non-alpha-numeric key (e.g. RETURN or TAB) modifiers global or app specific Returns: None or raise ValueError exception. """ # Awkward, but makes modifier-key-only combinations possible # (since sendKeyWithModifiers() calls this) if not keychr: return if not hasattr(self, 'keyboard'): self.keyboard = AXKeyboard.loadKeyboard() if keychr in self.keyboard['upperSymbols'] and not modFlags: self._sendKeyWithModifiers(keychr, [AXKeyCodeConstants.SHIFT], globally) return if keychr.isupper() and not modFlags: self._sendKeyWithModifiers( keychr.lower(), [AXKeyCodeConstants.SHIFT], globally ) return if keychr not in self.keyboard: self._clearEventQueue() raise ValueError('Key %s not found in keyboard layout' % keychr) # Press the key keyDown = Quartz.CGEventCreateKeyboardEvent(None, self.keyboard[keychr], True) # Release the key keyUp = Quartz.CGEventCreateKeyboardEvent(None, self.keyboard[keychr], False) # Set modflags on keyDown (default None): Quartz.CGEventSetFlags(keyDown, modFlags) # Set modflags on keyUp: Quartz.CGEventSetFlags(keyUp, modFlags) # Post the event to the given app if not globally: # To direct output to the correct application need the PSN (macOS <=10.10) or PID(macOS > 10.10): macVer, _, _ = platform.mac_ver() macVer = int(macVer.split('.')[1]) if macVer > 10: appPid = self._getPid() self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyDown)) self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyUp)) else: appPsn = self._getPsnForPid(self._getPid()) self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyDown)) self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyUp)) else: self._queueEvent(Quartz.CGEventPost, (0, keyDown)) self._queueEvent(Quartz.CGEventPost, (0, keyUp))
def _sendKey(self, keychr, modFlags=0, globally=False): """Send one character with no modifiers. Parameters: key character or constant referring to a non-alpha-numeric key (e.g. RETURN or TAB) modifier flags, global or app specific Returns: None or raise ValueError exception """ escapedChrs = { '\n': AXKeyCodeConstants.RETURN, '\r': AXKeyCodeConstants.RETURN, '\t': AXKeyCodeConstants.TAB, } if keychr in escapedChrs: keychr = escapedChrs[keychr] self._addKeyToQueue(keychr, modFlags, globally=globally) self._postQueuedEvents()
def _pressModifiers(self, modifiers, pressed=True, globally=False): """Press given modifiers (provided in list form). Parameters: modifiers list, global or app specific Optional: keypressed state (default is True (down)) Returns: Unsigned int representing flags to set """ if not isinstance(modifiers, list): raise TypeError('Please provide modifiers in list form') if not hasattr(self, 'keyboard'): self.keyboard = AXKeyboard.loadKeyboard() modFlags = 0 # Press given modifiers for nextMod in modifiers: if nextMod not in self.keyboard: errStr = 'Key %s not found in keyboard layout' self._clearEventQueue() raise ValueError(errStr % self.keyboard[nextMod]) modEvent = Quartz.CGEventCreateKeyboardEvent( Quartz.CGEventSourceCreate(0), self.keyboard[nextMod], pressed ) if not pressed: # Clear the modflags: Quartz.CGEventSetFlags(modEvent, 0) if globally: self._queueEvent(Quartz.CGEventPost, (0, modEvent)) else: # To direct output to the correct application need the PSN (macOS <=10.10) or PID(macOS > 10.10): macVer, _, _ = platform.mac_ver() macVer = int(macVer.split('.')[1]) if macVer > 10: appPid = self._getPid() self._queueEvent(Quartz.CGEventPostToPid, (appPid, modEvent)) else: appPsn = self._getPsnForPid(self._getPid()) self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, modEvent)) # Add the modifier flags modFlags += AXKeyboard.modKeyFlagConstants[nextMod] return modFlags
def _holdModifierKeys(self, modifiers): """Hold given modifier keys (provided in list form). Parameters: modifiers list Returns: Unsigned int representing flags to set """ modFlags = self._pressModifiers(modifiers) # Post the queued keypresses: self._postQueuedEvents() return modFlags
def _releaseModifiers(self, modifiers, globally=False): """Release given modifiers (provided in list form). Parameters: modifiers list Returns: None """ # Release them in reverse order from pressing them: modifiers.reverse() modFlags = self._pressModifiers(modifiers, pressed=False, globally=globally) return modFlags
def _releaseModifierKeys(self, modifiers): """Release given modifier keys (provided in list form). Parameters: modifiers list Returns: Unsigned int representing flags to set """ modFlags = self._releaseModifiers(modifiers) # Post the queued keypresses: self._postQueuedEvents() return modFlags
def _isSingleCharacter(keychr): """Check whether given keyboard character is a single character. Parameters: key character which will be checked. Returns: True when given key character is a single character. """ if not keychr: return False # Regular character case. if len(keychr) == 1: return True # Tagged character case. return keychr.count('<') == 1 and keychr.count('>') == 1 and \ keychr[0] == '<' and keychr[-1] == '>'
def _sendKeyWithModifiers(self, keychr, modifiers, globally=False): """Send one character with the given modifiers pressed. Parameters: key character, list of modifiers, global or app specific Returns: None or raise ValueError exception """ if not self._isSingleCharacter(keychr): raise ValueError('Please provide only one character to send') if not hasattr(self, 'keyboard'): self.keyboard = AXKeyboard.loadKeyboard() modFlags = self._pressModifiers(modifiers, globally=globally) # Press the non-modifier key self._sendKey(keychr, modFlags, globally=globally) # Release the modifiers self._releaseModifiers(modifiers, globally=globally) # Post the queued keypresses: self._postQueuedEvents()
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1, dest_coord=None): """Private method to handle generic mouse button clicking. Parameters: coord (x, y) to click, mouseButton (e.g., kCGMouseButtonLeft), modFlags set (int) Optional: clickCount (default 1; set to 2 for double-click; 3 for triple-click on host) Returns: None """ # For now allow only left and right mouse buttons: mouseButtons = { Quartz.kCGMouseButtonLeft: 'LeftMouse', Quartz.kCGMouseButtonRight: 'RightMouse', } if mouseButton not in mouseButtons: raise ValueError('Mouse button given not recognized') eventButtonDown = getattr(Quartz, 'kCGEvent%sDown' % mouseButtons[mouseButton]) eventButtonUp = getattr(Quartz, 'kCGEvent%sUp' % mouseButtons[mouseButton]) eventButtonDragged = getattr(Quartz, 'kCGEvent%sDragged' % mouseButtons[ mouseButton]) # Press the button buttonDown = Quartz.CGEventCreateMouseEvent(None, eventButtonDown, coord, mouseButton) # Set modflags (default None) on button down: Quartz.CGEventSetFlags(buttonDown, modFlags) # Set the click count on button down: Quartz.CGEventSetIntegerValueField(buttonDown, Quartz.kCGMouseEventClickState, int(clickCount)) if dest_coord: # Drag and release the button buttonDragged = Quartz.CGEventCreateMouseEvent(None, eventButtonDragged, dest_coord, mouseButton) # Set modflags on the button dragged: Quartz.CGEventSetFlags(buttonDragged, modFlags) buttonUp = Quartz.CGEventCreateMouseEvent(None, eventButtonUp, dest_coord, mouseButton) else: # Release the button buttonUp = Quartz.CGEventCreateMouseEvent(None, eventButtonUp, coord, mouseButton) # Set modflags on the button up: Quartz.CGEventSetFlags(buttonUp, modFlags) # Set the click count on button up: Quartz.CGEventSetIntegerValueField(buttonUp, Quartz.kCGMouseEventClickState, int(clickCount)) # Queue the events self._queueEvent(Quartz.CGEventPost, (Quartz.kCGSessionEventTap, buttonDown)) if dest_coord: self._queueEvent(Quartz.CGEventPost, (Quartz.kCGHIDEventTap, buttonDragged)) self._queueEvent(Quartz.CGEventPost, (Quartz.kCGSessionEventTap, buttonUp))
def _leftMouseDragged(self, stopCoord, strCoord, speed): """Private method to handle generic mouse left button dragging and dropping. Parameters: stopCoord(x,y) drop point Optional: strCoord (x, y) drag point, default (0,0) get current mouse position speed (int) 1 to unlimit, simulate mouse moving action from some special requirement Returns: None """ # To direct output to the correct application need the PSN: appPid = self._getPid() # Get current position as start point if strCoord not given if strCoord == (0, 0): loc = AppKit.NSEvent.mouseLocation() strCoord = (loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y) # To direct output to the correct application need the PSN: appPid = self._getPid() # Press left button down pressLeftButton = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDown, strCoord, Quartz.kCGMouseButtonLeft ) # Queue the events Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, pressLeftButton) # Wait for reponse of system, a fuzzy icon appears time.sleep(5) # Simulate mouse moving speed, k is slope speed = round(1 / float(speed), 2) xmoved = stopCoord[0] - strCoord[0] ymoved = stopCoord[1] - strCoord[1] if ymoved == 0: raise ValueError('Not support horizontal moving') else: k = abs(ymoved / xmoved) if xmoved != 0: for xpos in range(int(abs(xmoved))): if xmoved > 0 and ymoved > 0: currcoord = (strCoord[0] + xpos, strCoord[1] + xpos * k) elif xmoved > 0 and ymoved < 0: currcoord = (strCoord[0] + xpos, strCoord[1] - xpos * k) elif xmoved < 0 and ymoved < 0: currcoord = (strCoord[0] - xpos, strCoord[1] - xpos * k) elif xmoved < 0 and ymoved > 0: currcoord = (strCoord[0] - xpos, strCoord[1] + xpos * k) # Drag with left button dragLeftButton = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDragged, currcoord, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, dragLeftButton) # Wait for reponse of system time.sleep(speed) else: raise ValueError('Not support vertical moving') upLeftButton = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseUp, stopCoord, Quartz.kCGMouseButtonLeft ) # Wait for reponse of system, a plus icon appears time.sleep(5) # Up left button up Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, upLeftButton)
def _waitFor(self, timeout, notification, **kwargs): """Wait for a particular UI event to occur; this can be built upon in NativeUIElement for specific convenience methods. """ callback = self._matchOther retelem = None callbackArgs = None callbackKwargs = None # Allow customization of the callback, though by default use the basic # _match() method if 'callback' in kwargs: callback = kwargs['callback'] del kwargs['callback'] # Deal with these only if callback is provided: if 'args' in kwargs: if not isinstance(kwargs['args'], tuple): errStr = 'Notification callback args not given as a tuple' raise TypeError(errStr) # If args are given, notification will pass back the returned # element in the first positional arg callbackArgs = kwargs['args'] del kwargs['args'] if 'kwargs' in kwargs: if not isinstance(kwargs['kwargs'], dict): errStr = 'Notification callback kwargs not given as a dict' raise TypeError(errStr) callbackKwargs = kwargs['kwargs'] del kwargs['kwargs'] # If kwargs are not given as a dictionary but individually listed # need to update the callbackKwargs dict with the remaining items in # kwargs if kwargs: if callbackKwargs: callbackKwargs.update(kwargs) else: callbackKwargs = kwargs else: callbackArgs = (retelem,) # Pass the kwargs to the default callback callbackKwargs = kwargs return self._setNotification(timeout, notification, callback, callbackArgs, callbackKwargs)
def waitForFocusToMatchCriteria(self, timeout=10, **kwargs): """Convenience method to wait for focused element to change (to element matching kwargs criteria). Returns: Element or None """ def _matchFocused(retelem, **kwargs): return retelem if retelem._match(**kwargs) else None retelem = None return self._waitFor(timeout, 'AXFocusedUIElementChanged', callback=_matchFocused, args=(retelem,), **kwargs)
def _getActions(self): """Retrieve a list of actions supported by the object.""" actions = _a11y.AXUIElement._getActions(self) # strip leading AX from actions - help distinguish them from attributes return [action[2:] for action in actions]
def _performAction(self, action): """Perform the specified action.""" try: _a11y.AXUIElement._performAction(self, 'AX%s' % action) except _a11y.ErrorUnsupported as e: sierra_ver = '10.12' if mac_ver()[0] < sierra_ver: raise e else: pass
def _generateChildren(self): """Generator which yields all AXChildren of the object.""" try: children = self.AXChildren except _a11y.Error: return if children: for child in children: yield child
def _generateChildrenR(self, target=None): """Generator which recursively yields all AXChildren of the object.""" if target is None: target = self try: children = target.AXChildren except _a11y.Error: return if children: for child in children: yield child for c in self._generateChildrenR(child): yield c
def _match(self, **kwargs): """Method which indicates if the object matches specified criteria. Match accepts criteria as kwargs and looks them up on attributes. Actual matching is performed with fnmatch, so shell-like wildcards work within match strings. Examples: obj._match(AXTitle='Terminal*') obj._match(AXRole='TextField', AXRoleDescription='search text field') """ for k in kwargs.keys(): try: val = getattr(self, k) except _a11y.Error: return False # Not all values may be strings (e.g. size, position) if sys.version_info[:2] <= (2, 6): if isinstance(val, basestring): if not fnmatch.fnmatch(unicode(val), kwargs[k]): return False else: if val != kwargs[k]: return False elif sys.version_info[0] == 3: if isinstance(val, str): if not fnmatch.fnmatch(val, str(kwargs[k])): return False else: if val != kwargs[k]: return False else: if isinstance(val, str) or isinstance(val, unicode): if not fnmatch.fnmatch(val, kwargs[k]): return False else: if val != kwargs[k]: return False return True
def _matchOther(self, obj, **kwargs): """Perform _match but on another object, not self.""" if obj is not None: # Need to check that the returned UI element wasn't destroyed first: if self._findFirstR(**kwargs): return obj._match(**kwargs) return False
def _generateFind(self, **kwargs): """Generator which yields matches on AXChildren.""" for needle in self._generateChildren(): if needle._match(**kwargs): yield needle
def _generateFindR(self, **kwargs): """Generator which yields matches on AXChildren and their children.""" for needle in self._generateChildrenR(): if needle._match(**kwargs): yield needle
def _findAll(self, **kwargs): """Return a list of all children that match the specified criteria.""" result = [] for item in self._generateFind(**kwargs): result.append(item) return result
def _findAllR(self, **kwargs): """Return a list of all children (recursively) that match the specified criteria. """ result = [] for item in self._generateFindR(**kwargs): result.append(item) return result
def _getApplication(self): """Get the base application UIElement. If the UIElement is a child of the application, it will try to get the AXParent until it reaches the top application level element. """ app = self while True: try: app = app.AXParent except _a11y.ErrorUnsupported: break return app
def _menuItem(self, menuitem, *args): """Return the specified menu item. Example - refer to items by name: app._menuItem(app.AXMenuBar, 'File', 'New').Press() app._menuItem(app.AXMenuBar, 'Edit', 'Insert', 'Line Break').Press() Refer to items by index: app._menuitem(app.AXMenuBar, 1, 0).Press() Refer to items by mix-n-match: app._menuitem(app.AXMenuBar, 1, 'About TextEdit').Press() """ self._activate() for item in args: # If the item has an AXMenu as a child, navigate into it. # This seems like a silly abstraction added by apple's a11y api. if menuitem.AXChildren[0].AXRole == 'AXMenu': menuitem = menuitem.AXChildren[0] # Find AXMenuBarItems and AXMenuItems using a handy wildcard role = 'AXMenu*Item' try: menuitem = menuitem.AXChildren[int(item)] except ValueError: menuitem = menuitem.findFirst(AXRole='AXMenu*Item', AXTitle=item) return menuitem
def _activate(self): """Activate the application (bringing menus and windows forward).""" ra = AppKit.NSRunningApplication app = ra.runningApplicationWithProcessIdentifier_( self._getPid()) # NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps # == 3 - PyObjC in 10.6 does not expose these constants though so I have # to use the int instead of the symbolic names app.activateWithOptions_(3)
def _getBundleId(self): """Return the bundle ID of the application.""" ra = AppKit.NSRunningApplication app = ra.runningApplicationWithProcessIdentifier_( self._getPid()) return app.bundleIdentifier()
def menuItem(self, *args): """Return the specified menu item. Example - refer to items by name: app.menuItem('File', 'New').Press() app.menuItem('Edit', 'Insert', 'Line Break').Press() Refer to items by index: app.menuitem(1, 0).Press() Refer to items by mix-n-match: app.menuitem(1, 'About TextEdit').Press() """ menuitem = self._getApplication().AXMenuBar return self._menuItem(menuitem, *args)
def popUpItem(self, *args): """Return the specified item in a pop up menu.""" self.Press() time.sleep(.5) return self._menuItem(self, *args)
def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5): """Drag the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, dest_coord=dest_coord) self._postQueuedEvents(interval=interval)
def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5): """Double-click and drag the left mouse button without modifiers pressed. Parameters: coordinates to double-click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, dest_coord=dest_coord) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, dest_coord=dest_coord, clickCount=2) self._postQueuedEvents(interval=interval)
def clickMouseButtonLeft(self, coord, interval=None): """Click the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) if interval: self._postQueuedEvents(interval=interval) else: self._postQueuedEvents()
def clickMouseButtonRight(self, coord): """Click the right mouse button without modifiers pressed. Parameters: coordinates to click on scren (tuple (x, y)) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags) self._postQueuedEvents()
def clickMouseButtonLeftWithMods(self, coord, modifiers, interval=None): """Click the left mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) (e.g. [SHIFT] or [COMMAND, SHIFT] (assuming you've first used from pyatom.AXKeyCodeConstants import *)) Returns: None """ modFlags = self._pressModifiers(modifiers) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) self._releaseModifiers(modifiers) if interval: self._postQueuedEvents(interval=interval) else: self._postQueuedEvents()
def clickMouseButtonRightWithMods(self, coord, modifiers): """Click the right mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) Returns: None """ modFlags = self._pressModifiers(modifiers) self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags) self._releaseModifiers(modifiers) self._postQueuedEvents()
def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1): """Click the left mouse button and drag object. Parameters: stopCoord, the position of dragging stopped strCoord, the position of dragging started (0,0) will get current position speed is mouse moving speed, 0 to unlimited Returns: None """ self._leftMouseDragged(stopCoord, strCoord, speed)
def doubleClickMouse(self, coord): """Double-click primary mouse button. Parameters: coordinates to click (assume primary is left button) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) # This is a kludge: # If directed towards a Fusion VM the clickCount gets ignored and this # will be seen as a single click, so in sequence this will be a double- # click # Otherwise to a host app only this second one will count as a double- # click self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, clickCount=2) self._postQueuedEvents()
def doubleMouseButtonLeftWithMods(self, coord, modifiers): """Click the left mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) Returns: None """ modFlags = self._pressModifiers(modifiers) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, clickCount=2) self._releaseModifiers(modifiers) self._postQueuedEvents()
def tripleClickMouse(self, coord): """Triple-click primary mouse button. Parameters: coordinates to click (assume primary is left button) Returns: None """ # Note above re: double-clicks applies to triple-clicks modFlags = 0 for i in range(2): self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, clickCount=3) self._postQueuedEvents()
def waitFor(self, timeout, notification, **kwargs): """Generic wait for a UI event that matches the specified criteria to occur. For customization of the callback, use keyword args labeled 'callback', 'args', and 'kwargs' for the callback fn, callback args, and callback kwargs, respectively. Also note that on return, the observer-returned UI element will be included in the first argument if 'args' are given. Note also that if the UI element is destroyed, callback should not use it, otherwise the function will hang. """ return self._waitFor(timeout, notification, **kwargs)
def waitForCreation(self, timeout=10, notification='AXCreated'): """Convenience method to wait for creation of some UI element. Returns: The element created """ callback = AXCallbacks.returnElemCallback retelem = None args = (retelem,) return self.waitFor(timeout, notification, callback=callback, args=args)
def waitForWindowToDisappear(self, winName, timeout=10): """Convenience method to wait for a window with the given name to disappear. Returns: Boolean """ callback = AXCallbacks.elemDisappearedCallback retelem = None args = (retelem, self) # For some reason for the AXUIElementDestroyed notification to fire, # we need to have a reference to it first win = self.findFirst(AXRole='AXWindow', AXTitle=winName) return self.waitFor(timeout, 'AXUIElementDestroyed', callback=callback, args=args, AXRole='AXWindow', AXTitle=winName)
def waitForValueToChange(self, timeout=10): """Convenience method to wait for value attribute of given element to change. Some types of elements (e.g. menu items) have their titles change, so this will not work for those. This seems to work best if you set the notification at the application level. Returns: Element or None """ # Want to identify that the element whose value changes matches this # object's. Unique identifiers considered include role and position # This seems to work best if you set the notification at the application # level callback = AXCallbacks.returnElemCallback retelem = None return self.waitFor(timeout, 'AXValueChanged', callback=callback, args=(retelem,))
def waitForFocusToChange(self, newFocusedElem, timeout=10): """Convenience method to wait for focused element to change (to new element given). Returns: Boolean """ return self.waitFor(timeout, 'AXFocusedUIElementChanged', AXRole=newFocusedElem.AXRole, AXPosition=newFocusedElem.AXPosition)
def waitForFocusedWindowToChange(self, nextWinName, timeout=10): """Convenience method to wait for focused window to change Returns: Boolean """ callback = AXCallbacks.returnElemCallback retelem = None return self.waitFor(timeout, 'AXFocusedWindowChanged', AXTitle=nextWinName)
def _convenienceMatch(self, role, attr, match): """Method used by role based convenience functions to find a match""" kwargs = {} # If the user supplied some text to search for, # supply that in the kwargs if match: kwargs[attr] = match return self.findAll(AXRole=role, **kwargs)
def _convenienceMatchR(self, role, attr, match): """Method used by role based convenience functions to find a match""" kwargs = {} # If the user supplied some text to search for, # supply that in the kwargs if match: kwargs[attr] = match return self.findAllR(AXRole=role, **kwargs)
def imagecapture(self, window_name=None, x=0, y=0, width=None, height=None): """ Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: int @param y: y co-ordinate value @type y: int @param width: width co-ordinate value @type width: int @param height: height co-ordinate value @type height: int @return: screenshot with base64 encoded for the client @rtype: string """ if x or y or (width and width != -1) or (height and height != -1): raise LdtpServerException("Not implemented") if window_name: handle, name, app = self._get_window_handle(window_name) try: self._grabfocus(handle) except: pass rect = self._getobjectsize(handle) screenshot = CGWindowListCreateImage(NSMakeRect(rect[0], rect[1], rect[2], rect[3]), 1, 0, 0) else: screenshot = CGWindowListCreateImage(CGRectInfinite, 1, 0, 0) image = CIImage.imageWithCGImage_(screenshot) bitmapRep = NSBitmapImageRep.alloc().initWithCIImage_(image) blob = bitmapRep.representationUsingType_properties_(NSPNGFileType, None) tmpFile = tempfile.mktemp('.png', 'ldtpd_') blob.writeToFile_atomically_(tmpFile, False) rv = b64encode(open(tmpFile).read()) os.remove(tmpFile) return rv
def startlog(filename, overwrite=True): """ @param filename: Start logging on the specified file @type filename: string @param overwrite: Overwrite or append False - Append log to an existing file True - Write log to a new file. If file already exist, then erase existing file content and start log @type overwrite: boolean @return: 1 on success and 0 on error @rtype: integer """ if not filename: return 0 if overwrite: # Create new file, by overwriting existing file _mode = 'w' else: # Append existing file _mode = 'a' global _file_logger # Create logging file handler _file_logger = logging.FileHandler(os.path.expanduser(filename), _mode) # Log 'Levelname: Messages', eg: 'ERROR: Logged message' _formatter = logging.Formatter('%(levelname)-8s: %(message)s') _file_logger.setFormatter(_formatter) logger.addHandler(_file_logger) if _ldtp_debug: # On debug, change the default log level to DEBUG _file_logger.setLevel(logging.DEBUG) else: # else log in case of ERROR level and above _file_logger.setLevel(logging.ERROR) return 1
def removecallback(window_name): """ Remove registered callback on window create @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer """ if window_name in _pollEvents._callback: del _pollEvents._callback[window_name] return _remote_removecallback(window_name)
def callAfter(func, *args, **kwargs): """call a function on the main thread (async)""" pool = NSAutoreleasePool.alloc().init() obj = PyObjCAppHelperCaller_wrap.alloc().initWithArgs_((func, args, kwargs)) obj.callAfter_(None) del obj del pool
def callLater(delay, func, *args, **kwargs): """call a function on the main thread after a delay (async)""" pool = NSAutoreleasePool.alloc().init() obj = PyObjCAppHelperCaller_wrap.alloc().initWithArgs_((func, args, kwargs)) obj.callLater_(delay) del obj del pool
def stopEventLoop(): """ Stop the current event loop if possible returns True if it expects that it was successful, False otherwise """ stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper() if stopper is None: if NSApp() is not None: NSApp().terminate_(None) return True return False NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, stopper, 'performStop:', None, False) return True
def runEventLoop(argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain): """Run the event loop, ask the user if we should continue if an exception is caught. Use this function instead of NSApplicationMain(). """ if argv is None: argv = sys.argv if pdb is None: pdb = 'USE_PDB' in os.environ if pdb: from PyObjCTools import Debugging Debugging.installVerboseExceptionHandler() # bring it to the front, starting from terminal # often won't activator = PyObjCAppHelperApplicationActivator_wrap.alloc().init() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( activator, 'activateNow:', NSApplicationDidFinishLaunchingNotification, None, ) else: Debugging = None if installInterrupt is None and pdb: installInterrupt = True if unexpectedErrorAlert is None: unexpectedErrorAlert = unexpectedErrorAlertPdb runLoop = NSRunLoop.currentRunLoop() stopper = PyObjCAppHelperRunLoopStopper_wrap.alloc().init() PyObjCAppHelperRunLoopStopper_wrap.addRunLoopStopper_toRunLoop_(stopper, runLoop) firstRun = NSApp() is None try: while stopper.shouldRun(): try: if firstRun: firstRun = False if installInterrupt: installMachInterrupt() main(argv) else: NSApp().run() except RAISETHESE: traceback.print_exc() break except: exctype, e, tb = sys.exc_info() objc_exception = False if isinstance(e, objc.error): NSLog("%@", str(e)) elif not unexpectedErrorAlert(): NSLog("%@", "An exception has occured:") traceback.print_exc() sys.exit(0) else: NSLog("%@", "An exception has occured:") traceback.print_exc() else: break finally: if Debugging is not None: Debugging.removeExceptionHandler() PyObjCAppHelperRunLoopStopper_wrap.removeRunLoopStopperFromRunLoop_(runLoop)
def keypress(self, data): """ Press key. NOTE: keyrelease should be called @param data: data to type. @type data: string @return: 1 on success. @rtype: integer """ try: window = self._get_front_most_window() except (IndexError,): window = self._get_any_window() key_press_action = KeyPressAction(window, data) return 1
def keyrelease(self, data): """ Release key. NOTE: keypress should be called before this @param data: data to type. @type data: string @return: 1 on success. @rtype: integer """ try: window = self._get_front_most_window() except (IndexError,): window = self._get_any_window() key_release_action = KeyReleaseAction(window, data) return 1
def enterstring(self, window_name, object_name='', data=''): """ Type string sequence. @param window_name: Window name to focus on, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to focus on, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param data: data to type. @type data: string @return: 1 on success. @rtype: integer """ if not object_name and not data: return self.generatekeyevent(window_name) else: object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) self._grabfocus(object_handle) object_handle.sendKeys(data) return 1
def gettextvalue(self, window_name, object_name, startPosition=0, endPosition=0): """ Get text value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param startPosition: Starting position of text to fetch @type: startPosition: int @param endPosition: Ending position of text to fetch @type: endPosition: int @return: text on success. @rtype: string """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) return object_handle.AXValue
def inserttext(self, window_name, object_name, position, data): """ Insert string sequence in given position. @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param position: position where text has to be entered. @type data: int @param data: data to type. @type data: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) existing_data = object_handle.AXValue size = len(existing_data) if position < 0: position = 0 if position > size: position = size object_handle.AXValue = existing_data[:position] + data + \ existing_data[position:] return 1
def verifypartialmatch(self, window_name, object_name, partial_text): """ Verify partial text @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param partial_text: Partial text to match @type object_name: string @return: 1 on success. @rtype: integer """ try: if re.search(fnmatch.translate(partial_text), self.gettextvalue(window_name, object_name)): return 1 except: pass return 0
def verifysettext(self, window_name, object_name, text): """ Verify text is set correctly @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param text: text to match @type object_name: string @return: 1 on success. @rtype: integer """ try: return int(re.match(fnmatch.translate(text), self.gettextvalue(window_name, object_name))) except: return 0
def istextstateenabled(self, window_name, object_name): """ Verifies text state enabled or not @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success 0 on failure. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if object_handle.AXEnabled: return 1 except LdtpServerException: pass return 0
def getcharcount(self, window_name, object_name): """ Get character count @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) return object_handle.AXNumberOfCharacters