def multiselect(self, window_name, object_name, row_text_list, partial_match=False):
        """
        Select multiple row

        @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 row_text_list: Row list with matching text to select
        @type row_text: 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)

        object_handle.activate()
        selected = False
        try:
            window = self._get_front_most_window()
        except (IndexError,):
            window = self._get_any_window()
        for row_text in row_text_list:
            selected = False
            for cell in object_handle.AXRows:
                parent_cell = cell
                cell = self._getfirstmatchingchild(cell, "(AXTextField|AXStaticText)")
                if not cell:
                    continue
                if re.match(row_text, cell.AXValue):
                    selected = True
                    if not parent_cell.AXSelected:
                        x, y, width, height = self._getobjectsize(parent_cell)
                        window.clickMouseButtonLeftWithMods((x + width / 2,
                                                             y + height / 2),
                                                            ['<command_l>'])
                        # Following selection doesn't work
                        # parent_cell.AXSelected=True
                        self.wait(0.5)
                    else:
                        # Selected
                        pass
                    break
            if not selected:
                raise LdtpServerException(u"Unable to select row: %s" % row_text)
        if not selected:
            raise LdtpServerException(u"Unable to select any row")
        return 1

def
multiselect
(
self
,
window_name
,
object_name
,
row_text_list
,
partial_match
=
False
)
:
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
if
not
object_handle
.
AXEnabled
:
raise
LdtpServerException
(
u"Object %s state disabled"
%
object_name
)
object_handle
.
activate
(
)
selected
=
False
try
:
window
=
self
.
_get_front_most_window
(
)
except
(
IndexError
,
)
:
window
=
self
.
_get_any_window
(
)
for
row_text
in
row_text_list
:
selected
=
False
for
cell
in
object_handle
.
AXRows
:
parent_cell
=
cell
cell
=
self
.
_getfirstmatchingchild
(
cell
,
"(AXTextField|AXStaticText)"
)
if
not
cell
:
continue
if
re
.
match
(
row_text
,
cell
.
AXValue
)
:
selected
=
True
if
not
parent_cell
.
AXSelected
:
x
,
y
,
width
,
height
=
self
.
_getobjectsize
(
parent_cell
)
window
.
clickMouseButtonLeftWithMods
(
(
x
+
width
/
2
,
y
+
height
/
2
)
,
[
'<command_l>'
]
)
# Following selection doesn't work
# parent_cell.AXSelected=True
self
.
wait
(
0.5
)
else
:
# Selected
pass
break
if
not
selected
:
raise
LdtpServerException
(
u"Unable to select row: %s"
%
row_text
)
if
not
selected
:
raise
LdtpServerException
(
u"Unable to select any row"
)
return
1


def selectrowpartialmatch(self, window_name, object_name, row_text):
        """
        Select row partial match

        @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 row_text: Row text to select
        @type row_text: 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)

        for cell in object_handle.AXRows:
            if re.search(row_text,
                         cell.AXChildren[0].AXValue):
                if not cell.AXSelected:
                    object_handle.activate()
                    cell.AXSelected = True
                else:
                    # Selected
                    pass
                return 1
        raise LdtpServerException(u"Unable to select row: %s" % row_text)

def
selectrowpartialmatch
(
self
,
window_name
,
object_name
,
row_text
)
:
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
if
not
object_handle
.
AXEnabled
:
raise
LdtpServerException
(
u"Object %s state disabled"
%
object_name
)
for
cell
in
object_handle
.
AXRows
:
if
re
.
search
(
row_text
,
cell
.
AXChildren
[
0
]
.
AXValue
)
:
if
not
cell
.
AXSelected
:
object_handle
.
activate
(
)
cell
.
AXSelected
=
True
else
:
# Selected
pass
return
1
raise
LdtpServerException
(
u"Unable to select row: %s"
%
row_text
)


def selectrowindex(self, window_name, object_name, row_index):
        """
        Select row index

        @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 row_index: Row index to select
        @type row_index: integer

        @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)

        count = len(object_handle.AXRows)
        if row_index < 0 or row_index > count:
            raise LdtpServerException('Row index out of range: %d' % row_index)
        cell = object_handle.AXRows[row_index]
        if not cell.AXSelected:
            object_handle.activate()
            cell.AXSelected = True
        else:
            # Selected
            pass
        return 1

def
selectrowindex
(
self
,
window_name
,
object_name
,
row_index
)
:
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
if
not
object_handle
.
AXEnabled
:
raise
LdtpServerException
(
u"Object %s state disabled"
%
object_name
)
count
=
len
(
object_handle
.
AXRows
)
if
row_index
<
0
or
row_index
>
count
:
raise
LdtpServerException
(
'Row index out of range: %d'
%
row_index
)
cell
=
object_handle
.
AXRows
[
row_index
]
if
not
cell
.
AXSelected
:
object_handle
.
activate
(
)
cell
.
AXSelected
=
True
else
:
# Selected
pass
return
1


def selectlastrow(self, window_name, object_name):
        """
        Select last row

        @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)

        cell = object_handle.AXRows[-1]
        if not cell.AXSelected:
            object_handle.activate()
            cell.AXSelected = True
        else:
            # Selected
            pass
        return 1

def
selectlastrow
(
self
,
window_name
,
object_name
)
:
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
if
not
object_handle
.
AXEnabled
:
raise
LdtpServerException
(
u"Object %s state disabled"
%
object_name
)
cell
=
object_handle
.
AXRows
[
1
]
if
not
cell
.
AXSelected
:
object_handle
.
activate
(
)
cell
.
AXSelected
=
True
else
:
# Selected
pass
return
1


def getcellvalue(self, window_name, object_name, row_index, column=0):
        """
        Get cell 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 row_index: Row index to get
        @type row_index: integer
        @param column: Column index to get, default value 0
        @type column: integer

        @return: cell value 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)

        count = len(object_handle.AXRows)
        if row_index < 0 or row_index > count:
            raise LdtpServerException('Row index out of range: %d' % row_index)
        cell = object_handle.AXRows[row_index]
        count = len(cell.AXChildren)
        if column < 0 or column > count:
            raise LdtpServerException('Column index out of range: %d' % column)
        obj = cell.AXChildren[column]
        if not re.search("AXColumn", obj.AXRole):
            obj = cell.AXChildren[column]
        return obj.AXValue

def
getcellvalue
(
self
,
window_name
,
object_name
,
row_index
,
column
=
0
)
:
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
if
not
object_handle
.
AXEnabled
:
raise
LdtpServerException
(
u"Object %s state disabled"
%
object_name
)
count
=
len
(
object_handle
.
AXRows
)
if
row_index
<
0
or
row_index
>
count
:
raise
LdtpServerException
(
'Row index out of range: %d'
%
row_index
)
cell
=
object_handle
.
AXRows
[
row_index
]
count
=
len
(
cell
.
AXChildren
)
if
column
<
0
or
column
>
count
:
raise
LdtpServerException
(
'Column index out of range: %d'
%
column
)
obj
=
cell
.
AXChildren
[
column
]
if
not
re
.
search
(
"AXColumn"
,
obj
.
AXRole
)
:
obj
=
cell
.
AXChildren
[
column
]
return
obj
.
AXValue


def gettablerowindex(self, window_name, object_name, row_text):
        """
        Get table row index matching given 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 row_text: Row text to select
        @type row_text: string

        @return: row index matching the text 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)

        index = 0
        for cell in object_handle.AXRows:
            if re.match(row_text,
                        cell.AXChildren[0].AXValue):
                return index
            index += 1
        raise LdtpServerException(u"Unable to find row: %s" % row_text)

def
gettablerowindex
(
self
,
window_name
,
object_name
,
row_text
)
:
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
if
not
object_handle
.
AXEnabled
:
raise
LdtpServerException
(
u"Object %s state disabled"
%
object_name
)
index
=
0
for
cell
in
object_handle
.
AXRows
:
if
re
.
match
(
row_text
,
cell
.
AXChildren
[
0
]
.
AXValue
)
:
return
index
index
+=
1
raise
LdtpServerException
(
u"Unable to find row: %s"
%
row_text
)


def verifypartialtablecell(self, window_name, object_name, row_index,
                               column_index, row_text):
        """
        Verify partial table cell 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 row_index: Row index to get
        @type row_index: integer
        @param column_index: Column index to get, default value 0
        @type column_index: integer
        @param row_text: Row text to match
        @type string

        @return: 1 on success 0 on failure.
        @rtype: integer
        """
        try:
            value = getcellvalue(window_name, object_name, row_index, column_index)
            if re.searchmatch(row_text, value):
                return 1
        except LdtpServerException:
            pass
        return 0

def verifypartialtablecell ( self , window_name , object_name , row_index , column_index , row_text ) : try : value = getcellvalue ( window_name , object_name , row_index , column_index ) if re . searchmatch ( row_text , value ) : return 1 except LdtpServerException : pass return 0


def getapplist(self):
        """
        Get all accessibility application name that are currently running

        @return: list of appliction name of string type on success.
        @rtype: list
        """
        app_list = []
        # Update apps list, before parsing the list
        self._update_apps()
        for gui in self._running_apps:
            name = gui.localizedName()
            # default type was objc.pyobjc_unicode
            # convert to Unicode, else exception is thrown
            # TypeError: "cannot marshal <type 'objc.pyobjc_unicode'> objects"
            try:
                name = unicode(name)
            except NameError:
                name = str(name)
            except UnicodeEncodeError:
                pass
            app_list.append(name)
        # Return unique application list
        return list(set(app_list))


def startprocessmonitor(self, process_name, interval=2):
        """
        Start memory and CPU monitoring, with the time interval between
        each process scan

        @param process_name: Process name, ex: firefox-bin.
        @type process_name: string
        @param interval: Time interval between each process scan
        @type interval: double

        @return: 1 on success
        @rtype: integer
        """
        if process_name in self._process_stats:
            # Stop previously running instance
            # At any point, only one process name can be tracked
            # If an instance already exist, then stop it
            self._process_stats[process_name].stop()
        # Create an instance of process stat
        self._process_stats[process_name] = ProcessStats(process_name, interval)
        # start monitoring the process
        self._process_stats[process_name].start()
        return 1

Start memory and CPU monitoring with the time interval between each process scan


def stopprocessmonitor(self, process_name):
        """
        Stop memory and CPU monitoring

        @param process_name: Process name, ex: firefox-bin.
        @type process_name: string

        @return: 1 on success
        @rtype: integer
        """
        if process_name in self._process_stats:
            # Stop monitoring process
            self._process_stats[process_name].stop()
        return 1

def
stopprocessmonitor
(
self
,
process_name
)
:
if
process_name
in
self
.
_process_stats
:
# Stop monitoring process
self
.
_process_stats
[
process_name
]
.
stop
(
)
return
1


def getcpustat(self, process_name):
        """
        get CPU stat for the give process name

        @param process_name: Process name, ex: firefox-bin.
        @type process_name: string

        @return: cpu stat list on success, else empty list
                If same process name, running multiple instance,
                get the stat of all the process CPU usage
        @rtype: list
        """
        # Create an instance of process stat
        _stat_inst = ProcessStats(process_name)
        _stat_list = []
        for p in _stat_inst.get_cpu_memory_stat():
            try:
                _stat_list.append(p.get_cpu_percent())
            except psutil.AccessDenied:
                pass
        return _stat_list

def
getcpustat
(
self
,
process_name
)
:
# Create an instance of process stat
_stat_inst
=
ProcessStats
(
process_name
)
_stat_list
=
[
]
for
p
in
_stat_inst
.
get_cpu_memory_stat
(
)
:
try
:
_stat_list
.
append
(
p
.
get_cpu_percent
(
)
)
except
psutil
.
AccessDenied
:
pass
return
_stat_list


def getmemorystat(self, process_name):
        """
        get memory stat

        @param process_name: Process name, ex: firefox-bin.
        @type process_name: string

        @return: memory stat list on success, else empty list
                If same process name, running multiple instance,
                get the stat of all the process memory usage
        @rtype: list
        """
        # Create an instance of process stat
        _stat_inst = ProcessStats(process_name)
        _stat_list = []
        for p in _stat_inst.get_cpu_memory_stat():
            # Memory percent returned with 17 decimal values
            # ex: 0.16908645629882812, round it to 2 decimal values
            # as 0.03
            try:
                _stat_list.append(round(p.get_memory_percent(), 2))
            except psutil.AccessDenied:
                pass
        return _stat_list


def getobjectlist(self, window_name):
        """
        Get list of items in given GUI.

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string

        @return: list of items in LDTP naming convention.
        @rtype: list
        """
        try:
            window_handle, name, app = self._get_window_handle(window_name, True)
            object_list = self._get_appmap(window_handle, name, True)
        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
            window_handle, name, app = self._get_window_handle(window_name, True)
            object_list = self._get_appmap(window_handle, name, True)
        return object_list.keys()


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

Gets the list of object available in the window which matches component name or role name or both .


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 activatewindow ( self , window_name ) : 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 getallstates ( self , window_name , object_name ) : 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 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 getobjectsize ( self , window_name , object_name = None ) : 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 grabfocus ( self , window_name , object_name = None ) : 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 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

Wait till a window or component exists .


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 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 stateenabled ( self , window_name , object_name ) : 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 verifycheck ( self , window_name , object_name ) : 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 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)

Method to test if the general pasteboard is empty or not with respect to the type of object you want .


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))

Match given string by escaping regex characters


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 doesmenuitemexist ( self , window_name , object_name ) : 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 menuitemenabled ( self , window_name , object_name ) : try : menu_handle = self . _get_menu_handle ( window_name , object_name , False ) if menu_handle . AXEnabled : return 1 except LdtpServerException : pass return 0


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
verifymenucheck
(
self
,
window_name
,
object_name
)
:
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 _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
_getRunningApps
(
cls
)
:
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

Get a list of the running applications .


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
getAnyAppWithWindow
(
cls
)
:
# 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

Terminate app with a given bundle ID . Requires 10 . 6 .


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 _queueEvent ( self , event , args ) : 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 _sendKey ( self , keychr , modFlags = 0 , globally = False ) : 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 _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
_isSingleCharacter
(
keychr
)
:
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
]
==
'>'

Check whether given keyboard character is a single character .


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()

Send one character with the given modifiers pressed .


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))

Private method to handle generic mouse button clicking .


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)

Private method to handle generic mouse left button dragging and dropping .


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)

Wait for a particular UI event to occur ; this can be built upon in NativeUIElement for specific convenience methods .


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]

Retrieve a list of actions supported by the object .


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 _performAction ( self , 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 _generateChildren ( self ) : try : children = self . AXChildren except _a11y . Error : return if children : for child in children : yield child

Generator which yields all AXChildren of the object .


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 _generateChildrenR ( self , target = None ) : 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

Generator which recursively yields all AXChildren of the object .


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

Method which indicates if the object matches specified criteria .


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

Perform _match but on another object not self .


def _generateFind(self, **kwargs):
        """Generator which yields matches on AXChildren."""
        for needle in self._generateChildren():
            if needle._match(**kwargs):
                yield needle

def _generateFind ( self , * * kwargs ) : for needle in self . _generateChildren ( ) : if needle . _match ( * * kwargs ) : yield needle

Generator which yields matches on AXChildren .


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 _generateFindR ( self , * * kwargs ) : for needle in self . _generateChildrenR ( ) : if needle . _match ( * * kwargs ) : yield needle

Generator which yields matches on AXChildren and their children .


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 _findAll ( self , * * kwargs ) : result = [ ] for item in self . _generateFind ( * * kwargs ) : result . append ( item ) return result

Return a list of all children that match the specified criteria .


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 _getApplication ( self ) : app = self while True : try : app = app . AXParent except _a11y . ErrorUnsupported : break return app


def _getBundleId(self):
        """Return the bundle ID of the application."""
        ra = AppKit.NSRunningApplication
        app = ra.runningApplicationWithProcessIdentifier_(
            self._getPid())
        return app.bundleIdentifier()

Return the bundle ID of the application .


def popUpItem(self, *args):
        """Return the specified item in a pop up menu."""
        self.Press()
        time.sleep(.5)
        return self._menuItem(self, *args)

def popUpItem ( self , * args ) : self . Press ( ) time . sleep ( .5 ) return self . _menuItem ( self , * args )

Return the specified item in a pop up menu .


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 dragMouseButtonLeft ( self , coord , dest_coord , interval = 0.5 ) : modFlags = 0 self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , dest_coord = dest_coord ) self . _postQueuedEvents ( interval = interval )

Drag the left mouse button without modifiers pressed .


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 doubleClickDragMouseButtonLeft ( self , coord , dest_coord , interval = 0.5 ) : 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 )

Double - click and drag the left mouse button without modifiers pressed .


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 clickMouseButtonLeft ( self , coord , interval = None ) : modFlags = 0 self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags ) if interval : self . _postQueuedEvents ( interval = interval ) else : self . _postQueuedEvents ( )

Click the left mouse button without modifiers pressed .


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 clickMouseButtonRight ( self , coord ) : modFlags = 0 self . _queueMouseButton ( coord , Quartz . kCGMouseButtonRight , modFlags ) self . _postQueuedEvents ( )

Click the right mouse button without modifiers pressed .


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 clickMouseButtonRightWithMods ( self , coord , modifiers ) : modFlags = self . _pressModifiers ( modifiers ) self . _queueMouseButton ( coord , Quartz . kCGMouseButtonRight , modFlags ) self . _releaseModifiers ( modifiers ) self . _postQueuedEvents ( )

Click the right mouse button with modifiers pressed .


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 leftMouseDragged ( self , stopCoord , strCoord = ( 0 , 0 ) , speed = 1 ) : self . _leftMouseDragged ( stopCoord , strCoord , speed )

Click the left mouse button and drag object .


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 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 waitFor ( self , timeout , notification , * * kwargs ) : return self . _waitFor ( timeout , notification , * * kwargs )

Generic wait for a UI event that matches the specified criteria to occur .


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 waitForCreation ( self , timeout = 10 , notification = 'AXCreated' ) : callback = AXCallbacks . returnElemCallback retelem = None args = ( retelem , ) return self . waitFor ( timeout , notification , callback = callback , args = args )

Convenience method to wait for creation of some UI element .


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)

Convenience method to wait for a window with the given name to disappear .


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,))

Convenience method to wait for value attribute of given element to change .


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 waitForFocusedWindowToChange ( self , nextWinName , timeout = 10 ) : callback = AXCallbacks . returnElemCallback retelem = None return self . waitFor ( timeout , 'AXFocusedWindowChanged' , AXTitle = nextWinName )


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 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

Stop the current event loop if possible returns True if it expects that it was successful False otherwise


def main(port=4118, parentpid=None):
    """Main entry point. Parse command line options and start up a server."""
    if "LDTP_DEBUG" in os.environ:
        _ldtp_debug = True
    else:
        _ldtp_debug = False
    _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None)
    if _ldtp_debug:
        print("Parent PID: {}".format(int(parentpid)))
    if _ldtp_debug_file:
        with open(unicode(_ldtp_debug_file), "a") as fp:
            fp.write("Parent PID: {}".format(int(parentpid)))
    server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug,
                        requestHandler=RequestHandler)
    server.register_introspection_functions()
    server.register_multicall_functions()
    ldtp_inst = core.Core()
    server.register_instance(ldtp_inst)
    if parentpid:
        thread.start_new_thread(notifyclient, (parentpid,))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    except:
        if _ldtp_debug:
            print(traceback.format_exc())
        if _ldtp_debug_file:
            with open(_ldtp_debug_file, "a") as fp:
                fp.write(traceback.format_exc())

def
main
(
port
=
4118
,
parentpid
=
)
:
if
"LDTP_DEBUG"
in
os
.
environ
:
_ldtp_debug
=
True
else
:
_ldtp_debug
=
False
_ldtp_debug_file
=
os
.
environ
.
get
(
'LDTP_DEBUG_FILE'
,
)
if
_ldtp_debug
:
print
(
"Parent PID: {}"
.
format
(
int
(
parentpid
)
)
)
if
_ldtp_debug_file
:
with
open
(
unicode
(
_ldtp_debug_file
)
,
"a"
)
as
fp
:
fp
.
write
(
"Parent PID: {}"
.
format
(
int
(
parentpid
)
)
)
server
=
LDTPServer
(
(
''
,
port
)
,
allow_none
=
True
,
logRequests
=
_ldtp_debug
,
requestHandler
=
RequestHandler
)
server
.
register_introspection_functions
(
)
server
.
register_multicall_functions
(
)
ldtp_inst
=
core
.
Core
(
)
server
.
register_instance
(
ldtp_inst
)
if
parentpid
:
thread
.
start_new_thread
(
notifyclient
,
(
parentpid
,
)
)
try
:
server
.
serve_forever
(
)
except
KeyboardInterrupt
:
pass
except
:
if
_ldtp_debug
:
print
(
traceback
.
format_exc
(
)
)
if
_ldtp_debug_file
:
with
open
(
_ldtp_debug_file
,
"a"
)
as
fp
:
fp
.
write
(
traceback
.
format_exc
(
)
)

Main entry point . Parse command line options and start up a server .


def server_bind(self, *args, **kwargs):
        '''Server Bind. Forces reuse of port.'''
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # Can't use super() here since SimpleXMLRPCServer is an old-style class
        SimpleXMLRPCServer.server_bind(self, *args, **kwargs)


def log(self, message, level=logging.DEBUG):
        """
        Logs the message in the root logger with the log level
        @param message: Message to be logged
        @type message: string
        @param level: Log level, defaul DEBUG
        @type level: integer

        @return: 1 on success and 0 on error
        @rtype: integer
        """
        if _ldtp_debug:
            print(message)
        self.logger.log(level, str(message))
        return 1

def log ( self , message , level = logging . DEBUG ) : if _ldtp_debug : print ( message ) self . logger . log ( level , str ( message ) ) return 1


def stoplog(self):
        """ Stop logging.

        @return: 1 on success and 0 on error
        @rtype: integer
        """
        if self._file_logger:
            self.logger.removeHandler(_file_logger)
            self._file_logger = None
        return 1

def stoplog ( self ) : if self . _file_logger : self . logger . removeHandler ( _file_logger ) self . _file_logger = None return 1


def imagecapture(self, window_name=None, out_file=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: integer
        @param y: y co-ordinate value
        @type y: integer
        @param width: width co-ordinate value
        @type width: integer
        @param height: height co-ordinate value
        @type height: integer

        @return: screenshot filename
        @rtype: string
        """
        if not out_file:
            out_file = tempfile.mktemp('.png', 'ldtp_')
        else:
            out_file = os.path.expanduser(out_file)

        ### Windows compatibility
        if _ldtp_windows_env:
            if width == None:
                width = -1
            if height == None:
                height = -1
            if window_name == None:
                window_name = ''
        ### Windows compatibility - End
        data = self._remote_imagecapture(window_name, x, y, width, height)
        f = open(out_file, 'wb')
        f.write(b64decode(data))
        f.close()
        return out_file

def
imagecapture
(
self
,
window_name
=
,
out_file
=
,
x
=
0
,
y
=
0
,
width
=
,
height
=
)
:
if
not
out_file
:
out_file
=
tempfile
.
mktemp
(
'.png'
,
'ldtp_'
)
else
:
out_file
=
os
.
path
.
expanduser
(
out_file
)
### Windows compatibility
if
_ldtp_windows_env
:
if
width
==
:
width
=
1
if
height
==
:
height
=
1
if
window_name
==
:
window_name
=
''
### Windows compatibility - End
data
=
self
.
_remote_imagecapture
(
window_name
,
x
,
y
,
width
,
height
)
f
=
open
(
out_file
,
'wb'
)
f
.
write
(
b64decode
(
data
)
)
f
.
close
(
)
return
out_file


def onwindowcreate(self, window_name, fn_name, *args):
        """
        On window create, call the function with given arguments

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param fn_name: Callback function
        @type fn_name: function
        @param *args: arguments to be passed to the callback function
        @type *args: var args

        @return: 1 if registration was successful, 0 if not.
        @rtype: integer
        """
        self._pollEvents._callback[window_name] = ["onwindowcreate", fn_name, args]
        return self._remote_onwindowcreate(window_name)

def onwindowcreate ( self , window_name , fn_name , * args ) : self . _pollEvents . _callback [ window_name ] = [ "onwindowcreate" , fn_name , args ] return self . _remote_onwindowcreate ( window_name )

On window create call the function with given arguments


def registerevent(self, event_name, fn_name, *args):
        """
        Register at-spi event

        @param event_name: Event name in at-spi format.
        @type event_name: string
        @param fn_name: Callback function
        @type fn_name: function
        @param *args: arguments to be passed to the callback function
        @type *args: var args

        @return: 1 if registration was successful, 0 if not.
        @rtype: integer
        """
        if not isinstance(event_name, str):
            raise ValueError("event_name should be string")
        self._pollEvents._callback[event_name] = [event_name, fn_name, args]
        return self._remote_registerevent(event_name)

def
registerevent
(
self
,
event_name
,
fn_name
,
*
args
)
:
if
not
isinstance
(
event_name
,
str
)
:
raise
ValueError
(
"event_name should be string"
)
self
.
_pollEvents
.
_callback
[
event_name
]
=
[
event_name
,
fn_name
,
args
]
return
self
.
_remote_registerevent
(
event_name
)


def registerkbevent(self, keys, modifiers, fn_name, *args):
        """
        Register keystroke events

        @param keys: key to listen
        @type keys: string
        @param modifiers: control / alt combination using gtk MODIFIERS
        @type modifiers: int
        @param fn_name: Callback function
        @type fn_name: function
        @param *args: arguments to be passed to the callback function
        @type *args: var args

        @return: 1 if registration was successful, 0 if not.
        @rtype: integer
        """
        event_name = "kbevent%s%s" % (keys, modifiers)
        self._pollEvents._callback[event_name] = [event_name, fn_name, args]
        return self._remote_registerkbevent(keys, modifiers)

def registerkbevent ( self , keys , modifiers , fn_name , * args ) : event_name = "kbevent%s%s" % ( keys , modifiers ) self . _pollEvents . _callback [ event_name ] = [ event_name , fn_name , args ] return self . _remote_registerkbevent ( keys , modifiers )


def windowuptime(self, window_name):
        """
        Get window uptime

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string

        @return: "starttime, endtime" as datetime python object
        """
        tmp_time = self._remote_windowuptime(window_name)
        if tmp_time:
            tmp_time = tmp_time.split('-')
            start_time = tmp_time[0].split(' ')
            end_time = tmp_time[1].split(' ')
            _start_time = datetime.datetime(int(start_time[0]), int(start_time[1]),
                                            int(start_time[2]), int(start_time[3]),
                                            int(start_time[4]), int(start_time[5]))
            _end_time = datetime.datetime(int(end_time[0]), int(end_time[1]),
                                          int(end_time[2]), int(end_time[3]),
                                          int(end_time[4]), int(end_time[5]))
            return _start_time, _end_time
        return None

def
windowuptime
(
self
,
window_name
)
:
tmp_time
=
self
.
_remote_windowuptime
(
window_name
)
if
tmp_time
:
tmp_time
=
tmp_time
.
split
(
'-'
)
start_time
=
tmp_time
[
0
]
.
split
(
' '
)
end_time
=
tmp_time
[
1
]
.
split
(
' '
)
_start_time
=
datetime
.
datetime
(
int
(
start_time
[
0
]
)
,
int
(
start_time
[
1
]
)
,
int
(
start_time
[
2
]
)
,
int
(
start_time
[
3
]
)
,
int
(
start_time
[
4
]
)
,
int
(
start_time
[
5
]
)
)
_end_time
=
datetime
.
datetime
(
int
(
end_time
[
0
]
)
,
int
(
end_time
[
1
]
)
,
int
(
end_time
[
2
]
)
,
int
(
end_time
[
3
]
)
,
int
(
end_time
[
4
]
)
,
int
(
end_time
[
5
]
)
)
return
_start_time
,
_end_time
return


def verifyscrollbarvertical(self, window_name, object_name):
        """
        Verify scrollbar is vertical

        @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
        """
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if object_handle.AXOrientation == "AXVerticalOrientation":
                return 1
        except:
            pass
        return 0

def verifyscrollbarvertical ( self , window_name , object_name ) : try : object_handle = self . _get_object_handle ( window_name , object_name ) if object_handle . AXOrientation == "AXVerticalOrientation" : return 1 except : pass return 0


def verifyscrollbarhorizontal(self, window_name, object_name):
        """
        Verify scrollbar is horizontal

        @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
        """
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if object_handle.AXOrientation == "AXHorizontalOrientation":
                return 1
        except:
            pass
        return 0

def verifyscrollbarhorizontal ( self , window_name , object_name ) : try : object_handle = self . _get_object_handle ( window_name , object_name ) if object_handle . AXOrientation == "AXHorizontalOrientation" : return 1 except : pass return 0


def setmax(self, window_name, object_name):
        """
        Set max 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

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        object_handle.AXValue = 1
        return 1

def setmax ( self , window_name , object_name ) : object_handle = self . _get_object_handle ( window_name , object_name ) object_handle . AXValue = 1 return 1


def setmin(self, window_name, object_name):
        """
        Set min 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

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        object_handle.AXValue = 0
        return 1

def setmin ( self , window_name , object_name ) : object_handle = self . _get_object_handle ( window_name , object_name ) object_handle . AXValue = 0 return 1


def onedown(self, window_name, object_name, iterations):
        """
        Press scrollbar down with number of iterations

        @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 interations: iterations to perform on slider increase
        @type iterations: integer

        @return: 1 on success.
        @rtype: integer
        """
        if not self.verifyscrollbarvertical(window_name, object_name):
            raise LdtpServerException('Object not vertical scrollbar')
        object_handle = self._get_object_handle(window_name, object_name)
        i = 0
        maxValue = 1.0 / 8
        flag = False
        while i < iterations:
            if object_handle.AXValue >= 1:
                raise LdtpServerException('Maximum limit reached')
            object_handle.AXValue += maxValue
            time.sleep(1.0 / 100)
            flag = True
            i += 1
        if flag:
            return 1
        else:
            raise LdtpServerException('Unable to increase scrollbar')

def
onedown
(
self
,
window_name
,
object_name
,
iterations
)
:
if
not
self
.
verifyscrollbarvertical
(
window_name
,
object_name
)
:
raise
LdtpServerException
(
'Object not vertical scrollbar'
)
object_handle
=
self
.
_get_object_handle
(
window_name
,
object_name
)
i
=
0
maxValue
=
1.0
/
8
flag
=
False
while
i
<
iterations
:
if
object_handle
.
AXValue
>=
1
:
raise
LdtpServerException
(
'Maximum limit reached'
)
object_handle
.
AXValue
+=
maxValue
time
.
sleep
(
1.0
/
100
)
flag
=
True
i
+=
1
if
flag
:
return
1
else
:
raise
LdtpServerException
(
'Unable to increase scrollbar'
)