PKrN;patomacos/AXCallbacks.py# Copyright (c) 2010 VMware, Inc. All Rights Reserved. # This file is part of ATOMac. # ATOMac is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the Free # Software Foundation version 2 and no later version. # ATOMac is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 # for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin # St, Fifth Floor, Boston, MA 02110-1301 USA. import fnmatch def elemDisappearedCallback(retelem, obj, **kwargs): """Callback for checking if a UI element is no longer onscreen. kwargs should contains some unique set of identifier (e.g. title/value, role) Returns: Boolean """ return not obj.findFirstR(**kwargs) def returnElemCallback(retelem): """Callback for when a sheet appears. Returns: element returned by observer callback """ return retelem def match(obj, **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: match(obj, AXTitle='Terminal*') match(obj, AXRole='TextField', AXRoleDescription='search text field') """ for k in kwargs.keys(): try: val = getattr(obj, k) except AttributeError: return False # Not all values may be strings (e.g. size, position) if isinstance(val, str): if not fnmatch.fnmatch(val, kwargs[k]): return False else: if val != kwargs[k]: return False return True PKrNe2mBBatomacos/AXClasses.py# Copyright (c) 2010-2011 VMware, Inc. All Rights Reserved. # This file is part of ATOMac. # ATOMac is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the Free # Software Foundation version 2 and no later version. # ATOMac is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 # for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin # St, Fifth Floor, Boston, MA 02110-1301 USA. import time from collections import deque from atomacos import a11y from atomacos.mixin import KeyboardMouseMixin, SearchMethodsMixin, WaitForMixin class NativeUIElement( KeyboardMouseMixin, WaitForMixin, SearchMethodsMixin, a11y.AXUIElement ): """NativeUIElement class - expose the accessibility API in the simplest, most natural way possible. """ def __init__(self, ref=None): super(NativeUIElement, self).__init__(ref=ref) self.eventList = deque() @classmethod def getRunningApps(cls): """Get a list of the running applications.""" return a11y.get_running_apps() @classmethod def getAppRefByPid(cls, pid): """Get the top level element for the application specified by pid.""" return cls.from_pid(pid) @classmethod def getAppRefByBundleId(cls, bundleId): """ Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. """ return cls.from_bundle_id(bundleId) @classmethod def getAppRefByLocalizedName(cls, name): """Get the top level element for the application with the specified localized name, such as VMware Fusion. Wildcards are also allowed. """ # Refresh the runningApplications list return cls.from_localized_name(name) @classmethod def getFrontmostApp(cls): """Get the current frontmost application. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list return cls.frontmost() @classmethod def getAnyAppWithWindow(cls): """Get a random app that has windows. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list return cls.with_window() @classmethod def getSystemObject(cls): """Get the top level system accessibility object.""" return cls.systemwide() @classmethod def setSystemWideTimeout(cls, timeout=0.0): """Set the system-wide accessibility timeout. Args: timeout: non-negative float. 0 will reset to the system default. Returns: None """ return cls.set_systemwide_timeout(timeout) @staticmethod 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. NativeUIElement.launch_app_by_bundle_id(bundleID) @staticmethod def launchAppByBundlePath(bundlePath, arguments=None): """Launch app with a given bundle path. Return True if succeed. """ return NativeUIElement.launch_app_by_bundle_path(bundlePath, arguments) @staticmethod def terminateAppByBundleId(bundleID): """Terminate app with a given bundle ID. Requires 10.6. Return True if succeed. """ return NativeUIElement.terminate_app_by_bundle_id(bundleID) @classmethod def set_systemwide_timeout(cls, timeout=0.0): """Set the system-wide accessibility timeout. Optional: timeout (non-negative float; defaults to 0) A value of 0 will reset the timeout to the system default. Returns: None. """ return cls.systemwide().setTimeout(timeout) def setTimeout(self, timeout=0.0): """Set the accessibiltiy API timeout on the given reference. Optional: timeout (non-negative float; defaults to 0) A value of 0 will reset the timeout to the system-wide value Returns: None """ self.set_timeout(timeout) def getAttributes(self): """Get a list of the attributes available on the element.""" return self.ax_attributes def getActions(self): """Return a list of the actions available on the element.""" actions = self.ax_actions # strip leading AX from actions - help distinguish them from attributes return [action[2:] for action in actions] def setString(self, attribute, string): """Set the specified attribute to the specified string.""" return self.__setattr__(attribute, str(string)) def getElementAtPosition(self, coord): """Return the AXUIElement at the given coordinates. If self is behind other windows, this function will return self. """ return self._getElementAtPosition(float(coord[0]), float(coord[1])) def activate(self): """Activate the application (bringing menus and windows forward)""" return self._activate() 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 "AXParent" in app.ax_attributes: app = app.AXParent return app 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(0.5) return self._menuItem(self, *args) def getBundleId(self): """Return the bundle ID of the application.""" return self.bundle_id def getLocalizedName(self): """Return the localized name of the application.""" return self.getApplication().AXTitle def __getattr__(self, name): """Handle attribute requests in several ways: 1. If it starts with AX, it is probably an a11y attribute. Pass it to the handler in _a11y which will determine that for sure. 2. See if the attribute is an action which can be invoked on the UIElement. If so, return a function that will invoke the attribute. """ if "AX" + name in self.ax_actions: action = super(NativeUIElement, self).__getattr__("AX" + name) def performSpecifiedAction(): # activate the app before performing the specified action self._activate() return action() return performSpecifiedAction else: return super(NativeUIElement, self).__getattr__(name) PKrN?UEatomacos/AXKeyCodeConstants.py# Copyright (c) 2010 VMware, Inc. All Rights Reserved. # This file is part of ATOMac. # ATOMac is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the Free # Software Foundation version 2 and no later version. # ATOMac is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 # for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin # St, Fifth Floor, Boston, MA 02110-1301 USA. # Special keys TAB = "" RETURN = "" SPACE = "" ESCAPE = "" CAPS_LOCK = "" DELETE = "" NUM_LOCK = "" SCROLL_LOCK = "" PAUSE = "" BACKSPACE = "" INSERT = "" # Cursor movement UP = "" DOWN = "" LEFT = "" RIGHT = "" PAGE_UP = "" PAGE_DOWN = "" HOME = "" END = "" # Numeric keypad NUM_0 = "" NUM_1 = "" NUM_2 = "" NUM_3 = "" NUM_4 = "" NUM_5 = "" NUM_6 = "" NUM_7 = "" NUM_8 = "" NUM_9 = "" NUM_ENTER = "" NUM_PERIOD = "" NUM_PLUS = "" NUM_MINUS = "" NUM_MULTIPLY = "" NUM_DIVIDE = "" # Function keys F1 = "" F2 = "" F3 = "" F4 = "" F5 = "" F6 = "" F7 = "" F8 = "" F9 = "" F10 = "" F11 = "" F12 = "" # Modifier keys COMMAND_L = "" SHIFT_L = "" OPTION_L = "" CONTROL_L = "" COMMAND_R = "" SHIFT_R = "" OPTION_R = "" CONTROL_R = "" # Default modifier keys -> left: COMMAND = COMMAND_L SHIFT = SHIFT_L OPTION = OPTION_L CONTROL = CONTROL_L # Define a dictionary representing characters mapped to their virtual key codes # Lifted from the mappings found in kbdptr.h in the osxvnc project # Mapping is: character -> virtual keycode for each character / symbol / key # as noted below US_keyboard = { # Letters "a": 0, "b": 11, "c": 8, "d": 2, "e": 14, "f": 3, "g": 5, "h": 4, "i": 34, "j": 38, "k": 40, "l": 37, "m": 46, "n": 45, "o": 31, "p": 35, "q": 12, "r": 15, "s": 1, "t": 17, "u": 32, "v": 9, "w": 13, "x": 7, "y": 16, "z": 6, # Numbers "0": 29, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26, "8": 28, "9": 25, # Symbols "!": 18, "@": 19, "#": 20, "$": 21, "%": 23, "^": 22, "&": 26, "*": 28, "(": 25, ")": 29, "-": 27, # Dash "_": 27, # Underscore "=": 24, "+": 24, "`": 50, # Backtick "~": 50, "[": 33, "]": 30, "{": 33, "}": 30, ";": 41, ":": 41, "'": 39, '"': 39, ",": 43, "<": 43, ".": 47, ">": 47, "/": 44, "?": 44, "\\": 42, "|": 42, # Pipe TAB: 48, # Tab: Shift-Tab sent for Tab SPACE: 49, " ": 49, # Space # Characters that on the US keyboard require use with Shift "upperSymbols": [ "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "~", "{", "}", ":", '"', "<", ">", "?", "|", ], } # Mapping for special (meta) keys specialKeys = { # Special keys RETURN: 36, DELETE: 117, TAB: 48, SPACE: 49, ESCAPE: 53, CAPS_LOCK: 57, NUM_LOCK: 71, SCROLL_LOCK: 107, PAUSE: 113, BACKSPACE: 51, INSERT: 114, # Cursor movement UP: 126, DOWN: 125, LEFT: 123, RIGHT: 124, PAGE_UP: 116, PAGE_DOWN: 121, # Numeric keypad NUM_0: 82, NUM_1: 83, NUM_2: 84, NUM_3: 85, NUM_4: 86, NUM_5: 87, NUM_6: 88, NUM_7: 89, NUM_8: 91, NUM_9: 92, NUM_ENTER: 76, NUM_PERIOD: 65, NUM_PLUS: 69, NUM_MINUS: 78, NUM_MULTIPLY: 67, NUM_DIVIDE: 75, # Function keys F1: 122, F2: 120, F3: 99, F4: 118, F5: 96, F6: 97, F7: 98, F8: 100, F9: 101, F10: 109, F11: 103, F12: 111, # Modifier keys COMMAND_L: 55, SHIFT_L: 56, OPTION_L: 58, CONTROL_L: 59, COMMAND_R: 54, SHIFT_R: 60, OPTION_R: 61, CONTROL_R: 62, } # Default keyboard layout DEFAULT_KEYBOARD = US_keyboard PKrNH11atomacos/AXKeyboard.py# Copyright (c) 2010 VMware, Inc. All Rights Reserved. # This file is part of ATOMac. # ATOMac is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the Free # Software Foundation version 2 and no later version. # ATOMac is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 # for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin # St, Fifth Floor, Boston, MA 02110-1301 USA. import Quartz from atomacos.AXKeyCodeConstants import ( COMMAND, CONTROL, DEFAULT_KEYBOARD, OPTION, SHIFT, specialKeys, ) # Based on the flags provided in the Quartz documentation it does not seem # that we can distinguish between left and right modifier keys, even though # there are different virtual key codes offered between the two sets. # Thus for now we offer only a generic modifier key set w/o L-R distinction. modKeyFlagConstants = { COMMAND: Quartz.kCGEventFlagMaskCommand, SHIFT: Quartz.kCGEventFlagMaskShift, OPTION: Quartz.kCGEventFlagMaskAlternate, CONTROL: Quartz.kCGEventFlagMaskControl, } def loadKeyboard(): """Load a given keyboard mapping (of characters to virtual key codes). Default is US keyboard Parameters: None (relies on the internationalization settings) Returns: A dictionary representing the current keyboard mapping (of characters to keycodes) """ # Currently assumes US keyboard keyboard_layout = DEFAULT_KEYBOARD keyboard_layout.update(specialKeys) return keyboard_layout PKrNRatomacos/Clipboard.py# Copyright (c) 2010 VMware, Inc. All Rights Reserved. # This file is part of ATOMac. # ATOMac is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the Free # Software Foundation version 2 and no later version. # ATOMac is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 # for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin # St, Fifth Floor, Boston, MA 02110-1301 USA. import logging import pprint import types import AppKit import Foundation class Clipboard(object): """Class to represent clipboard-related operations for text""" # String encoding type utf8encoding = Foundation.NSUTF8StringEncoding # Class attributes to distinguish types of data: # Reference: # http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ # ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html # Text data type STRING = AppKit.NSStringPboardType # Rich-text format data type (e.g. rtf documents) RTF = AppKit.NSRTFPboardType # Image datatype (e.g. tiff) IMAGE = AppKit.NSTIFFPboardType # URL data type (not just web but file locations also) URL = AppKit.NSURLPboardType # Color datatype - not sure if we'll have to use this one # Supposedly replaced in 10.6 but the pyobjc AppKit module doesn't have the # new data type as an attribute COLOR = AppKit.NSColorPboardType # You can extend this list of data types # e.g. File copy and paste between host and guest # Not sure if text copy and paste between host and guest falls under STRING/ # RTF or not # List of PboardTypes I found in AppKit: # NSColorPboardType # NSCreateFileContentsPboardType # NSCreateFilenamePboardType # NSDragPboard # NSFileContentsPboardType # NSFilenamesPboardType # NSFilesPromisePboardType # NSFindPanelSearchOptionsPboardType # NSFindPboard # NSFontPboard # NSFontPboardType # NSGeneralPboard # NSHTMLPboardType # NSInkTextPboardType # NSMultipleTextSelectionPboardType # NSPDFPboardType # NSPICTPboardType # NSPostScriptPboardType # NSRTFDPboardType # NSRTFPboardType # NSRulerPboard # NSRulerPboardType # NSSoundPboardType # NSStringPboardType # NSTIFFPboardType # NSTabularTextPboardType # NSURLPboardType # NSVCardPboardType @classmethod 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 @classmethod 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) @classmethod 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 @classmethod def clearProperties(cls): """Clear properties of general pasteboard. Future enhancement can include specifying which clipboard's properties to clear Returns: True on success; caller should catch exceptions raised, e.g. from AppKit (ValueError) """ log_msg = "Request to clear properties of pasteboard: general" logging.debug(log_msg) pb = AppKit.NSPasteboard.generalPasteboard() pb.clearProperties() return True @classmethod def clearAll(cls): """Clear contents and properties of general pasteboard. Future enhancement can include specifying which clipboard's properties to clear Returns: Boolean True on success; caller should handle exceptions """ cls.clearContents() cls.clearProperties() return True @classmethod 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.exception(error) raise return bool(its_empty) PKrNǫatomacos/Prefs.py# -*- coding: utf-8 -*- # Copyright (c) 2011 Julián Romero. # This file is part of ATOMac. # ATOMac is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the Free # Software Foundation version 2 and no later version. # ATOMac is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 # for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin # St, Fifth Floor, Boston, MA 02110-1301 USA. from os import path from AppKit import NSDictionary, NSUserDefaults, NSWorkspace from future import standard_library try: from collections import UserDict except ImportError: from UserDict import UserDict standard_library.install_aliases() __all__ = ["Prefs"] class Prefs(UserDict): """NSUserDefaults proxy to read/write application preferences. It has been conceived to prepare the preferences before a test launch the app. Once a Prefs instance is created, it doesn't detect prefs changed elsewhere, so for now you need to create the instance right before reading/writing a pref. Defaults.plist with default values is expected to exist on the app bundle. p = Prefs('com.example.App') coolStuff = p['CoolStuff'] p['CoolStuff'] = newCoolStuff """ def __init__(self, bundleID, bundlePath=None, defaultsPlistName="Defaults"): """ bundleId: the application bundle identifier bundlePath: the full bundle path (useful to test a Debug build) defaultsPlistName: the name of the plist that contains default values """ self.__bundleID = bundleID self.__bundlePath = bundlePath UserDict.__init__(self) self.__setup(defaultsPlistName) def __setup(self, defaultsPlistName=None): NSUserDefaults.resetStandardUserDefaults() prefs = NSUserDefaults.standardUserDefaults() self.defaults = self.__defaults(defaultsPlistName) domainData = prefs.persistentDomainForName_(self.__bundleID) if domainData: self.data = domainData else: self.data = NSDictionary.dictionary() def __defaults(self, plistName="Defaults"): if self.__bundlePath is None: self.__bundlePath = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier_( # noqa:: B950 self.__bundleID ) if self.__bundlePath: plistPath = path.join( self.__bundlePath, "Contents/Resources/%s.plist" % plistName ) plist = NSDictionary.dictionaryWithContentsOfFile_(plistPath) if plist: return plist return NSDictionary.dictionary() def get(self, key): return self.__getitem__(key) def __getitem__(self, key): result = self.data.get(key, None) if result is None or result == "": if self.defaults: result = self.defaults.get(key, None) return result def set(self, key, value): self.__setitem__(key, value) def __setitem__(self, key, value): mutableData = self.data.mutableCopy() mutableData[key] = value self.data = mutableData prefs = NSUserDefaults.standardUserDefaults() prefs.setPersistentDomain_forName_(self.data, self.__bundleID) PK<sN(ratomacos/__init__.py"""Automated Testing on macOS""" # flake8: noqa: F401 __version__ = "0.5.0" from atomacos import a11y, errors from atomacos.AXClasses import NativeUIElement from atomacos.Clipboard import Clipboard from atomacos.Prefs import Prefs Error = errors.AXError ErrorAPIDisabled = errors.AXErrorAPIDisabled ErrorInvalidUIElement = errors.AXErrorInvalidUIElement ErrorCannotComplete = errors.AXErrorCannotComplete ErrorUnsupported = errors.AXErrorUnsupported ErrorNotImplemented = errors.AXErrorNotImplemented getAppRefByLocalizedName = NativeUIElement.getAppRefByLocalizedName terminateAppByBundleId = NativeUIElement.terminateAppByBundleId launchAppByBundlePath = NativeUIElement.launchAppByBundlePath setSystemWideTimeout = NativeUIElement.setSystemWideTimeout getAppRefByBundleId = NativeUIElement.getAppRefByBundleId launchAppByBundleId = NativeUIElement.launchAppByBundleId getFrontmostApp = NativeUIElement.getFrontmostApp getAppRefByPid = NativeUIElement.getAppRefByPid PKrNqFDDatomacos/_macos.py""" Wrap objc calls to raise python exception """ from ApplicationServices import ( AXObserverAddNotification, AXObserverCreate, AXObserverRemoveNotification, AXUIElementCopyActionNames, AXUIElementCopyAttributeNames, AXUIElementCopyAttributeValue, AXUIElementCopyElementAtPosition, AXUIElementGetPid, AXUIElementIsAttributeSettable, AXUIElementPerformAction, AXUIElementSetAttributeValue, AXUIElementSetMessagingTimeout, ) from atomacos import errors from objc import callbackFor PAXObserverCallback = callbackFor(AXObserverCreate) def PAXObserverCreate(application, callback): """ Creates a new observer that can receive notifications from the specified application. Args: application: The process ID of the application callback: The callback function Returns: an AXObserverRef representing the observer object """ err, observer = AXObserverCreate(application, callback, None) errors.check_ax_error(err, "Could not create observer for notification") return observer def PAXObserverAddNotification(observer, element, notification, refcon): """ Registers the specified observer to receive notifications from the specified accessibility object Args: observer: The observer object created from a call to AXObserverCreate element: The accessibility object for which to observe notifications notification: The name of the notification to observe refcon: Application-defined data passed to the callback when it is called """ err = AXObserverAddNotification(observer, element, notification, refcon) errors.check_ax_error(err, "Could not add notification to observer") def PAXObserverRemoveNotification(observer, element, notification): """ Removes the specified notification from the list of notifications the observer wants to receive from the accessibility object. Args: observer: The observer object created from a call to AXObserverCreate element: The accessibility object for which this observer observes notifications notification: The name of the notification to remove from the list of observed notifications """ err = AXObserverRemoveNotification(observer, element, notification) errors.check_ax_error(err, "Could not remove notification from observer") def PAXUIElementCopyAttributeValue(element, attribute): """ Returns the value of an accessibility object's attribute Args: element: The AXUIElementRef representing the accessibility object attribute: The attribute name Returns: the value associated with the specified attribute """ err, attrValue = AXUIElementCopyAttributeValue(element, attribute, None) errors.check_ax_error(err, "Unable to get attribute. %s" % attribute) return attrValue def PAXUIElementIsAttributeSettable(element, attribute): """ Returns whether the specified accessibility object's attribute can be modified Args: element: The AXUIElementRef representing the accessibility object attribute: The attribute name Returns: a Boolean value indicating whether the attribute is settable """ err, settable = AXUIElementIsAttributeSettable(element, attribute, None) errors.check_ax_error(err, "Error querying attribute") return settable def PAXUIElementSetAttributeValue(element, attribute, value): """ Sets the accessibility object's attribute to the specified value Args: element: The AXUIElementRef representing the accessibility object attribute: The attribute name value: The new value for the attribute """ err = AXUIElementSetAttributeValue(element, attribute, value) errors.check_ax_error(err, "Error setting attribute value") def PAXUIElementCopyAttributeNames(element): """ Returns a list of all the attributes supported by the specified accessibility object Args: element: The AXUIElementRef representing the accessibility object Returns: an array containing the accessibility object's attribute names """ err, names = AXUIElementCopyAttributeNames(element, None) errors.check_ax_error(err, "Error retrieving attribute list") return names def PAXUIElementCopyActionNames(element): """ Returns a list of all the actions the specified accessibility object can perform Args: element: The AXUIElementRef representing the accessibility object Returns: an array of actions the accessibility object can perform (empty if the accessibility object supports no actions) """ err, names = AXUIElementCopyActionNames(element, None) errors.check_ax_error(err, "Error retrieving action names") return names def PAXUIElementPerformAction(element, action): """ Requests that the specified accessibility object perform the specified action Args: element: The AXUIElementRef representing the accessibility object action: The action to be performed """ err = AXUIElementPerformAction(element, action) errors.check_ax_error(err, "Error performing requested action") def PAXUIElementGetPid(element): """ Returns the process ID associated with the specified accessibility object Args: element: The AXUIElementRef representing an accessibility object Returns: the process ID associated with the specified accessibility object """ err, pid = AXUIElementGetPid(element, None) errors.check_ax_error(err, "Error retrieving PID") return pid def PAXUIElementCopyElementAtPosition(application, x, y): """ Returns the accessibility object at the specified position in top-left relative screen coordinates Args: application: The AXUIElementRef representing the application that contains the screen coordinates (or the system-wide accessibility object) x: The horizontal position y: The vertical position Returns: the accessibility object at the position specified by x and y """ err, element = AXUIElementCopyElementAtPosition(application, x, y, None) errors.check_ax_error(err, "Unable to get element at position") return element def PAXUIElementSetMessagingTimeout(element, timeoutInSeconds): """ Sets the timeout value used in the accessibility API Args: element: The AXUIElementRef representing an accessibility object timeoutInSeconds: The number of seconds for the new timeout value """ err = AXUIElementSetMessagingTimeout(element, timeoutInSeconds) errors.check_ax_error(err, "The element reference is invalid") PKrN]Zg/g/atomacos/a11y.pyimport fnmatch import logging import AppKit from ApplicationServices import ( AXIsProcessTrusted, AXUIElementCreateApplication, AXUIElementCreateSystemWide, CFEqual, NSWorkspace, ) from atomacos import converter from atomacos._macos import ( PAXUIElementCopyActionNames, PAXUIElementCopyAttributeNames, PAXUIElementCopyAttributeValue, PAXUIElementCopyElementAtPosition, PAXUIElementGetPid, PAXUIElementIsAttributeSettable, PAXUIElementPerformAction, PAXUIElementSetAttributeValue, PAXUIElementSetMessagingTimeout, ) from atomacos.errors import ( AXError, AXErrorAPIDisabled, AXErrorCannotComplete, AXErrorIllegalArgument, AXErrorNotImplemented, AXErrorNoValue, AXErrorUnsupported, ) from PyObjCTools import AppHelper logger = logging.getLogger(__name__) class AXUIElement(object): def __init__(self, ref=None): self.ref = ref self.converter = converter.Converter(self.__class__) def __repr__(self): """Build a descriptive string for UIElements.""" c = repr(self.__class__).partition("")[0] _attributes = self.ax_attributes for element_describer in ("AXTitle", "AXValue", "AXRoleDescription"): if element_describer in _attributes: title = self.__getattr__(element_describer) if title: break else: title = "" if "AXRole" in _attributes: role = self.AXRole else: role = "" if len(title) > 20: title = title[:20] + "...'" return "<%s %s %s>" % (c, role, title) def __getattr__(self, item): if item in self.ax_attributes: return self._get_ax_attribute(item) elif item in self.ax_actions: def perform_ax_action(): self._perform_ax_actions(item) return perform_ax_action else: raise AttributeError( "'%s' object has no attribute '%s'" % (type(self), item) ) def __setattr__(self, key, value): if key.startswith("AX"): try: if key in self.ax_attributes: self._set_ax_attribute(key, value) except AXErrorIllegalArgument: pass else: super(AXUIElement, self).__setattr__(key, value) def __dir__(self): return ( self.ax_attributes + self.ax_actions + list(self.__dict__.keys()) + dir(super(AXUIElement, self)) # not working in python 2 ) def _get_ax_attribute(self, item): """Get the value of the the specified attribute""" if item in self.ax_attributes: try: attr_value = PAXUIElementCopyAttributeValue(self.ref, item) return self.converter.convert_value(attr_value) except AXErrorNoValue: return None raise AttributeError("'%s' object has no attribute '%s'" % (type(self), item)) def _set_ax_attribute(self, name, value): """ Set the specified attribute to the specified value """ settable = PAXUIElementIsAttributeSettable(self.ref, name) if not settable: raise AXErrorUnsupported("Attribute is not settable") PAXUIElementSetAttributeValue(self.ref, name, value) def _activate(self): """Activate the application (bringing menus and windows forward).""" ra = AppKit.NSRunningApplication app = ra.runningApplicationWithProcessIdentifier_(self.pid) # 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) @property def ax_attributes(self): """ Get a list of attributes available on the AXUIElement """ try: names = PAXUIElementCopyAttributeNames(self.ref) return list(names) except AXError: return [] @property def ax_actions(self): """ Get a list of actions available on the AXUIElement """ try: names = PAXUIElementCopyActionNames(self.ref) return list(names) except AXError: return [] def _perform_ax_actions(self, name): PAXUIElementPerformAction(self.ref, name) @property def bundle_id(self): """Return the bundle ID of the application.""" ra = AppKit.NSRunningApplication app = ra.runningApplicationWithProcessIdentifier_(self.pid) return app.bundleIdentifier() @property def pid(self): pid = PAXUIElementGetPid(self.ref) return pid @classmethod def from_pid(cls, pid): """ Get an AXUIElement reference to the application by specified PID. """ app_ref = AXUIElementCreateApplication(pid) if app_ref is None: raise AXErrorUnsupported("Error getting app ref") return cls(ref=app_ref) @classmethod def systemwide(cls): """Get an AXUIElement reference for the system accessibility object.""" app_ref = AXUIElementCreateSystemWide() if app_ref is None: raise AXErrorUnsupported("Error getting a11y object") return cls(ref=app_ref) @classmethod def from_bundle_id(cls, bundle_id): """ Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. """ ra = AppKit.NSRunningApplication # return value (apps) is always an array. if there is a match it will # have an item, otherwise it won't. apps = ra.runningApplicationsWithBundleIdentifier_(bundle_id) if len(apps) == 0: raise ValueError( ("Specified bundle ID not found in " "running apps: %s" % bundle_id) ) pid = apps[0].processIdentifier() return cls.from_pid(pid) @classmethod def from_localized_name(cls, name): """Get the top level element for the application with the specified localized name, such as VMware Fusion. Wildcards are also allowed. """ # Refresh the runningApplications list apps = get_running_apps() for app in apps: if fnmatch.fnmatch(app.localizedName(), name): pid = app.processIdentifier() return cls.from_pid(pid) raise ValueError("Specified application not found in running apps.") @classmethod def frontmost(cls): """Get the current frontmost application. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list apps = get_running_apps() for app in apps: pid = app.processIdentifier() ref = cls.from_pid(pid) try: if ref.AXFrontmost: return ref except ( AttributeError, AXErrorUnsupported, AXErrorCannotComplete, AXErrorAPIDisabled, AXErrorNotImplemented, ): # 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.") @classmethod def with_window(cls): """Get a random app that has windows. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list apps = get_running_apps() for app in apps: pid = app.processIdentifier() ref = cls.from_pid(pid) if hasattr(ref, "windows") and len(ref.windows()) > 0: return ref raise ValueError("No GUI application found.") def __eq__(self, other): if not isinstance(other, type(self)): return False if self.ref is None and other.ref is None: return True if self.ref is None or other.ref is None: return False return CFEqual(self.ref, other.ref) def __ne__(self, other): return not self.__eq__(other) def get_element_at_position(self, x, y): if self.ref is None: raise AXErrorUnsupported( "Operation not supported on null element references" ) try: element = PAXUIElementCopyElementAtPosition(self.ref, x, y) except AXErrorIllegalArgument: raise ValueError("Arguments must be two floats.") return self.__class__(element) @staticmethod def launch_app_by_bundle_id(bundle_id): """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_( # noqa: B950 bundle_id, 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. %s" % str(r)) @staticmethod def launch_app_by_bundle_path(bundle_path, arguments=None): """Launch app with a given bundle path. Return True if succeed. """ if arguments is None: arguments = [] bundleUrl = AppKit.NSURL.fileURLWithPath_(bundle_path) workspace = AppKit.NSWorkspace.sharedWorkspace() configuration = {AppKit.NSWorkspaceLaunchConfigurationArguments: arguments} return workspace.launchApplicationAtURL_options_configuration_error_( bundleUrl, AppKit.NSWorkspaceLaunchAllowingClassicStartup, configuration, None, ) @staticmethod def terminate_app_by_bundle_id(bundle_id): """Terminate app with a given bundle ID. Requires 10.6. Return True if succeed. """ ra = AppKit.NSRunningApplication appList = ra.runningApplicationsWithBundleIdentifier_(bundle_id) if appList: app = appList[0] return app and app.terminate() return False def set_timeout(self, timeout): if self.ref is None: raise AXErrorUnsupported( "Operation not supported on null element references" ) try: PAXUIElementSetMessagingTimeout(self.ref, timeout) except AXErrorIllegalArgument: raise ValueError("Accessibility timeout values must be non-negative") def get_frontmost_pid(): """Return the PID of the application in the foreground.""" frontmost_app = NSWorkspace.sharedWorkspace().frontmostApplication() pid = frontmost_app.processIdentifier() return pid def axenabled(): """Return the status of accessibility on the system.""" return AXIsProcessTrusted() def get_running_apps(): """Get a list of the running applications.""" AppHelper.callLater(1, AppHelper.stopEventLoop) AppHelper.runConsoleEventLoop() # Get a list of running applications ws = AppKit.NSWorkspace.sharedWorkspace() apps = ws.runningApplications() return apps PKrN=atomacos/converter.pyimport re from collections import namedtuple from ApplicationServices import ( AXUIElementGetTypeID, AXValueGetType, NSPointFromString, NSRangeFromString, NSSizeFromString, kAXValueCFRangeType, kAXValueCGPointType, kAXValueCGSizeType, ) from CoreFoundation import CFArrayGetTypeID, CFGetTypeID, CFStringGetTypeID class Converter: def __init__(self, axuielementclass=None): self.app_ref_class = axuielementclass def convert_value(self, value): if CFGetTypeID(value) == CFStringGetTypeID(): return str(value) if CFGetTypeID(value) == AXUIElementGetTypeID(): return self.convert_app_ref(value) if CFGetTypeID(value) == CFArrayGetTypeID(): return self.convert_list(value) if AXValueGetType(value) == kAXValueCGSizeType: return self.convert_size(value) if AXValueGetType(value) == kAXValueCGPointType: return self.convert_point(value) if AXValueGetType(value) == kAXValueCFRangeType: return self.convert_range(value) else: return value def convert_list(self, value): return [self.convert_value(item) for item in value] def convert_app_ref(self, value): return self.app_ref_class(ref=value) def convert_size(self, value): repr_searched = re.search("{.*}", str(value)).group() CGSize = namedtuple("CGSize", ["width", "height"]) size = NSSizeFromString(repr_searched) return CGSize(size.width, size.height) def convert_point(self, value): repr_searched = re.search("{.*}", str(value)).group() CGPoint = namedtuple("CGPoint", ["x", "y"]) point = NSPointFromString(repr_searched) return CGPoint(point.x, point.y) def convert_range(self, value): repr_searched = re.search("{.*}", str(value)).group() CFRange = namedtuple("CFRange", ["location", "length"]) range = NSRangeFromString(repr_searched) return CFRange(range.location, range.length) PKrNC&atomacos/errors.pyfrom ApplicationServices import ( kAXErrorActionUnsupported, kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorIllegalArgument, kAXErrorInvalidUIElement, kAXErrorNotImplemented, kAXErrorNoValue, kAXErrorSuccess, ) class AXError(Exception): pass class AXErrorUnsupported(AXError): pass class AXErrorAPIDisabled(AXError): pass class AXErrorInvalidUIElement(AXError): pass class AXErrorCannotComplete(AXError): pass class AXErrorNotImplemented(AXError): pass class AXErrorIllegalArgument(AXError): pass class AXErrorActionUnsupported(AXError): pass class AXErrorNoValue(AXError): pass def AXErrorFactory(code): return { kAXErrorAPIDisabled: AXErrorAPIDisabled, kAXErrorInvalidUIElement: AXErrorInvalidUIElement, kAXErrorCannotComplete: AXErrorCannotComplete, kAXErrorNotImplemented: AXErrorNotImplemented, kAXErrorIllegalArgument: AXErrorIllegalArgument, kAXErrorNoValue: AXErrorNoValue, kAXErrorActionUnsupported: AXErrorActionUnsupported, }.get(code, AXErrorUnsupported) def check_ax_error(code, message): """ Raises an error with given message based on given error code. Defaults to AXErrorUnsupported for unknown codes. """ if code == kAXErrorSuccess: return else: error_message = "%s (AX Error %s)" % (message, code) raise AXErrorFactory(code)(error_message) PKrNxuұ atomacos/notification.pyimport logging import signal import threading import time from ApplicationServices import AXObserverGetRunLoopSource, NSDefaultRunLoopMode from atomacos._macos import ( PAXObserverAddNotification, PAXObserverCallback, PAXObserverCreate, PAXObserverRemoveNotification, ) from CoreFoundation import CFRunLoopAddSource, CFRunLoopGetCurrent from PyObjCTools import AppHelper try: from PyObjCTools import MachSignals except ImportError: class MachSignals: signal = signal.signal logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) def _sigHandler(sig): AppHelper.stopEventLoop() raise KeyboardInterrupt("Keyboard interrupted Run Loop") class Observer: def __init__(self, uielement=None): self.ref = uielement self.callback = None self.callback_result = None def set_notification( self, timeout=0, notification_name=None, callbackFn=None, callbackArgs=None, callbackKwargs=None, ): if callable(callbackFn): self.callbackFn = callbackFn if isinstance(callbackArgs, tuple): self.callbackArgs = callbackArgs else: self.callbackArgs = tuple() if isinstance(callbackKwargs, dict): self.callbackKwargs = callbackKwargs else: self.callbackKwargs = dict() self.callback_result = None @PAXObserverCallback def _callback(observer, element, notification, refcon): if self.callbackFn is not None: ret_element = self.ref.__class__(element) if ret_element is None: raise RuntimeError("Could not create new AX UI Element.") callback_args = (ret_element,) + self.callbackArgs callback_result = self.callbackFn(*callback_args, **self.callbackKwargs) if callback_result is None: raise RuntimeError("Python callback failed.") if callback_result in (-1, 1): self.callback_result = callback_result observer = PAXObserverCreate(self.ref.pid, _callback) PAXObserverAddNotification( observer, self.ref.ref, notification_name, id(self.ref.ref) ) # Add observer source to run loop CFRunLoopAddSource( CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer), NSDefaultRunLoopMode, ) def event_stopper(): end_time = time.time() + timeout while time.time() < end_time: if self.callback_result is not None: break AppHelper.callAfter(AppHelper.stopEventLoop) event_watcher = threading.Thread(target=event_stopper) event_watcher.daemon = True event_watcher.start() # Set the signal handlers prior to running the run loop oldSigIntHandler = MachSignals.signal(signal.SIGINT, _sigHandler) AppHelper.runConsoleEventLoop() MachSignals.signal(signal.SIGINT, oldSigIntHandler) PAXObserverRemoveNotification(observer, self.ref.ref, notification_name) return self.callback_result PKrNiFdatomacos/mixin/__init__.py# flake8: noqa: F401 from atomacos.mixin._input import KeyboardMouseMixin from atomacos.mixin._search import SearchMethodsMixin from atomacos.mixin._wait import WaitForMixin PKrN]LLatomacos/mixin/_input.pyimport time import AppKit import Quartz from atomacos import AXKeyboard, AXKeyCodeConstants class EventQueue(object): 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 _clearEventQueue(self): """Clear the event queue.""" if hasattr(self, "eventList"): self.eventList.clear() 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). """ self.eventList.append((event, args)) class Mouse(object): 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 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 """ # 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) # 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 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 _ in range(2): self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, clickCount=3) self._postQueuedEvents() class Keyboard(object): 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: self._queueEvent(Quartz.CGEventPostToPid, (self.pid, keyDown)) self._queueEvent(Quartz.CGEventPostToPid, (self.pid, keyUp)) else: self._queueEvent(Quartz.CGEventPost, (0, keyDown)) self._queueEvent(Quartz.CGEventPost, (0, keyUp)) def sendKey(self, keychr): """Send one character with no modifiers.""" return self._sendKey(keychr) def sendGlobalKey(self, keychr): """Send one character without modifiers to the system. It will not send an event directly to the application, system will dispatch it to the window which has keyboard focus. Parameters: keychr - Single keyboard character which will be sent. """ return self._sendKey(keychr, globally=True) def sendKeys(self, keystr): """Send a series of characters with no modifiers.""" return self._sendKeys(keystr) def pressModifiers(self, modifiers): """Hold modifier keys (e.g. [Option]).""" return self._holdModifierKeys(modifiers) def releaseModifiers(self, modifiers): """Release modifier keys (e.g. [Option]).""" return self._releaseModifierKeys(modifiers) def sendKeyWithModifiers(self, keychr, modifiers): """Send one character with modifiers pressed Parameters: key character, modifiers (list) (e.g. [SHIFT] or [COMMAND, SHIFT] (assuming you've first used from pyatom.AXKeyCodeConstants import *)) """ return self._sendKeyWithModifiers(keychr, modifiers, False) def sendGlobalKeyWithModifiers(self, keychr, modifiers): """Global send one character with modifiers pressed. See sendKeyWithModifiers """ return self._sendKeyWithModifiers(keychr, modifiers, True) 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 _sendKeys(self, keystr): """Send a series of characters with no modifiers. Parameters: keystr Returns: None or raise ValueError exception """ for nextChr in keystr: self._sendKey(nextChr) 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: self._queueEvent(Quartz.CGEventPostToPid, (self._getPid(), 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 @staticmethod 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() class KeyboardMouseMixin(Mouse, Keyboard, EventQueue): pass PKrNx atomacos/mixin/_search.pyfrom atomacos import AXCallbacks class SearchMethodsMixin(object): def _generateChildren(self, target=None, recursive=False): """Generator which yields all AXChildren of the object.""" if target is None: target = self if "AXChildren" not in target.ax_attributes: return for child in target.AXChildren: yield child if recursive: for c in self._generateChildren(child, recursive): yield c def _findAll(self, recursive=False, **kwargs): """Return a list of all children that match the specified criteria.""" for needle in self._generateChildren(recursive=recursive): if AXCallbacks.match(needle, **kwargs): yield needle def _findFirst(self, recursive=False, **kwargs): """Return the first object that matches the criteria.""" for item in self._findAll(recursive=recursive, **kwargs): return item def findFirst(self, **kwargs): """Return the first object that matches the criteria.""" return self._findFirst(**kwargs) def findFirstR(self, **kwargs): """Search recursively for the first object that matches the criteria. """ return self._findFirst(recursive=True, **kwargs) def findAll(self, **kwargs): """Return a list of all children that match the specified criteria.""" return list(self._findAll(**kwargs)) def findAllR(self, **kwargs): """Return a list of all children (recursively) that match the specified criteria. """ return list(self._findAll(recursive=True, **kwargs)) 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 textAreas(self, match=None): """Return a list of text areas with an optional match parameter.""" return self._convenienceMatch("AXTextArea", "AXTitle", match) def textAreasR(self, match=None): """Return a list of text areas with an optional match parameter.""" return self._convenienceMatchR("AXTextArea", "AXTitle", match) def textFields(self, match=None): """Return a list of textfields with an optional match parameter.""" return self._convenienceMatch("AXTextField", "AXRoleDescription", match) def textFieldsR(self, match=None): """Return a list of textfields with an optional match parameter.""" return self._convenienceMatchR("AXTextField", "AXRoleDescription", match) def buttons(self, match=None): """Return a list of buttons with an optional match parameter.""" return self._convenienceMatch("AXButton", "AXTitle", match) def buttonsR(self, match=None): """Return a list of buttons with an optional match parameter.""" return self._convenienceMatchR("AXButton", "AXTitle", match) def windows(self, match=None): """Return a list of windows with an optional match parameter.""" return self._convenienceMatch("AXWindow", "AXTitle", match) def windowsR(self, match=None): """Return a list of windows with an optional match parameter.""" return self._convenienceMatchR("AXWindow", "AXTitle", match) def sheets(self, match=None): """Return a list of sheets with an optional match parameter.""" return self._convenienceMatch("AXSheet", "AXDescription", match) def sheetsR(self, match=None): """Return a list of sheets with an optional match parameter.""" return self._convenienceMatchR("AXSheet", "AXDescription", match) def staticTexts(self, match=None): """Return a list of statictexts with an optional match parameter.""" return self._convenienceMatch("AXStaticText", "AXValue", match) def staticTextsR(self, match=None): """Return a list of statictexts with an optional match parameter""" return self._convenienceMatchR("AXStaticText", "AXValue", match) def genericElements(self, match=None): """Return a list of genericelements with an optional match parameter.""" return self._convenienceMatch("AXGenericElement", "AXValue", match) def genericElementsR(self, match=None): """Return a list of genericelements with an optional match parameter.""" return self._convenienceMatchR("AXGenericElement", "AXValue", match) def groups(self, match=None): """Return a list of groups with an optional match parameter.""" return self._convenienceMatch("AXGroup", "AXRoleDescription", match) def groupsR(self, match=None): """Return a list of groups with an optional match parameter.""" return self._convenienceMatchR("AXGroup", "AXRoleDescription", match) def radioButtons(self, match=None): """Return a list of radio buttons with an optional match parameter.""" return self._convenienceMatch("AXRadioButton", "AXTitle", match) def radioButtonsR(self, match=None): """Return a list of radio buttons with an optional match parameter.""" return self._convenienceMatchR("AXRadioButton", "AXTitle", match) def popUpButtons(self, match=None): """Return a list of popup menus with an optional match parameter.""" return self._convenienceMatch("AXPopUpButton", "AXTitle", match) def popUpButtonsR(self, match=None): """Return a list of popup menus with an optional match parameter.""" return self._convenienceMatchR("AXPopUpButton", "AXTitle", match) def rows(self, match=None): """Return a list of rows with an optional match parameter.""" return self._convenienceMatch("AXRow", "AXTitle", match) def rowsR(self, match=None): """Return a list of rows with an optional match parameter.""" return self._convenienceMatchR("AXRow", "AXTitle", match) def sliders(self, match=None): """Return a list of sliders with an optional match parameter.""" return self._convenienceMatch("AXSlider", "AXValue", match) def slidersR(self, match=None): """Return a list of sliders with an optional match parameter.""" return self._convenienceMatchR("AXSlider", "AXValue", match) 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 try: menuitem = menuitem.AXChildren[int(item)] except ValueError: menuitem = menuitem.findFirst(AXRole="AXMenu*Item", AXTitle=item) return menuitem PKrNRzatomacos/mixin/_wait.pyfrom atomacos import AXCallbacks from atomacos.notification import Observer class WaitForMixin(object): 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 = AXCallbacks.match 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: if retelem: callbackArgs = (retelem,) # Pass the kwargs to the default callback callbackKwargs = kwargs return Observer(self).set_notification( timeout, notification, callback, callbackArgs, callbackKwargs ) 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 waitForWindowToAppear(self, winName, timeout=10): """Convenience method to wait for a window with the given name to appear. Returns: Boolean """ return self.waitFor(timeout, "AXWindowCreated", AXTitle=winName) 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) # noqa: F841 return self.waitFor( timeout, "AXUIElementDestroyed", callback=callback, args=args, AXRole="AXWindow", AXTitle=winName, ) def waitForSheetToAppear(self, timeout=10): """Convenience method to wait for a sheet to appear. Returns: the sheet that appeared (element) or None """ return self.waitForCreation(timeout, "AXSheetCreated") 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 """ return self.waitFor(timeout, "AXFocusedWindowChanged", AXTitle=nextWinName) 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 ) PKrNFNFF atomacos-0.5.0.dist-info/LICENSE GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. PK!HMuSaatomacos-0.5.0.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!H vZ !atomacos-0.5.0.dist-info/METADATAYms۸_^X4Z8NNSGvsGA$$"& J> zMgay-o[h#Ue'h eܪ'Do8Ej"ewXYN*XnT!BLfmeTڬlj*:) QN(;].e"J?W?"ϔD<,EeeN?đ0*(mnQAlR5/#'R&b&rUeڰngmvUZ'$\l]3Ug{Jߠթe",`6hzU xc7BtZGilU 5M1/\駶}KFs*BBϐfTZܡ=C?m'Oc`ӜR1ak+-`}Ҫo/*&JIu*z gۤȰLAzAel{M%[kEo7;wܗǃEbL<5TcvήGc8ܶ/+qBs5FGD1ם␰UJ> >vf Xij{ׇZi Ϥ٭" /x,$98JY${'i` œݒ('YHcNcGv)&Hx1uaeҰU#g&l=Q߲97,ŹUij-r1s!2;fRڲHxmDd3AHhUkC#i :9~n'jAH? ~z|w8%'%:kLrl4X9S]=EqI,㎌q}'fcex2u`3 U:Ƣ[)bLG?qkFU|1IXT/*=߾m|p,߶AԟQC1U 1CLet:"BU_ )z3v[ +eL$ONPBOcF(LZLSc/1gjQ ź>Ԍ&RT{꯻e֤݊Axi%!>᠂fEKY5y 7ul2=\h4l\5MQXL+Up#b 7c!9 B`MU>juAOyazO 7^T4]9{0Qǫhr^ITXϼnD}Θ,\XnNkE G?,>e~zBeICVuA04d#6ER o5"w炆րC)#~g+oe2/E+L<\amb\w6P#JH!cޝU(OL6d7L7~ LnZQLchر Dbhx@L?xp]a}˃_4Lhy?ۓ9psDҥKx$c>/_pDۍ{\ADCw%A\ ~55ڱNJ6Ft 9MW ~~@$_TvHn*fLTRJI]xPZݚs68q+Vuzs)Rc%tE;1 EHKƱgIŴl2͓Ӌ*eZv\UUK#\@ӘsăGT6-8ջmFz%;mАqt08tqP7e>xp +S7~7vpI&NY4&偌晵Mm]0矹4{⢳0.8>f  SXb1e,L8`yI;o\h蜂NNY"qk,0A| i5pOM~nt#uKZk]E>=>|; ˵EiȜۆew9Sz,[H4SI| Yd(KIrݢqj>5B7RWaIc#wy'PKrN;patomacos/AXCallbacks.pyPKrNe2mBBatomacos/AXClasses.pyPKrN?UEn&atomacos/AXKeyCodeConstants.pyPKrNH11/9atomacos/AXKeyboard.pyPKrNR큔@atomacos/Clipboard.pyPKrNǫ큜\atomacos/Prefs.pyPK<sN(rjatomacos/__init__.pyPKrNqFDDnatomacos/_macos.pyPKrN]Zg/g/Xatomacos/a11y.pyPKrN=atomacos/converter.pyPKrNC&/atomacos/errors.pyPKrNxuұ atomacos/notification.pyPKrNiFdatomacos/mixin/__init__.pyPKrN]LLatomacos/mixin/_input.pyPKrNx  "atomacos/mixin/_search.pyPKrNRz)Aatomacos/mixin/_wait.pyPKrNFNFF dZatomacos-0.5.0.dist-info/LICENSEPK!HMuSaNatomacos-0.5.0.dist-info/WHEELPK!H vZ !ݡatomacos-0.5.0.dist-info/METADATAPK!HP atomacos-0.5.0.dist-info/RECORDPKs