def initialStore(self):
        print "initialing iTunesStore"
        atomac.launchAppByBundleId(self.bundle_name)
        pattern = re.compile(u'No role')
        trytime = self.tryTime

        while pattern.search(str(atomac.getAppRefByBundleId(
                self.bundle_name))):
            print "step 1 sleep 5 sec..."
            time.sleep(self.shortSleepTime)

        appStoreRef = atomac.getAppRefByBundleId(self.bundle_name)
        # print appStoreRef
        pattern = re.compile('None')

        # print appStoreRef.AXMainWindow.AXFrame
        while trytime > 0 and (pattern.search(str(appStoreRef.AXMainWindow))
                               or pattern.search(str(appStoreRef.AXMainWindow))
                               or pattern.search(
                                   str(
                                       appStoreRef.AXMainWindow.findFirst(
                                           AXRole='AXSplitGroup').findAll()))
                               or len(
                                   appStoreRef.AXMainWindow.findFirst(
                                       AXRole='AXSplitGroup').findAll()) == 0):
            print "network excetion!try again in {}s, try_time remain {} times".format(
                self.shortSleepTime, trytime)
            time.sleep(self.shortSleepTime)
            trytime -= 1

        return appStoreRef
示例#2
0
    def getApp(bundleName):
        ax = None
        try:
            ax = atomac.getAppRefByBundleId(bundleName)
        except ValueError:
            ax = atomac.launchAppByBundleId(bundleName)
            if ax is None:
                ax = atomac.getAppRefByBundleId(bundleName)

        while ax.AXTitle is None:
            ax = atomac.getAppRefByBundleId(bundleName)

        ax.activate()
        return UIApp(ax)
示例#3
0
 def _get_first_window(self):
     sim = atomac.getAppRefByBundleId(self.bid)
     windows = sim.windows()
     if windows:
         return sim.windows()[0]
     else:
         raise Exception("Cannot get simulator window")
 def start_record():
     # atomac.launchAppByBundleId("com.apple.dt.Instruments")
     # time.sleep(2)
     instrument = atomac.getAppRefByBundleId("com.apple.dt.Instruments")
     recordbutton = instrument.windows()[0].toolbars()[0].checkboxs()[0]
     recordbutton.Press()
     return instrument
示例#5
0
    def find(device_info, text):
        try:
            # Get list of iOS Simulator Windows
            simulator = atomac.getAppRefByBundleId("com.apple.iphonesimulator")
            windows = simulator.findAll(AXRole='AXWindow')
            names = list()

            # Get all simulator's windows names
            for window in windows:
                names.append(window.AXTitle)

            # Get the full name of the window where the click will be performed
            for name in names:
                if device_info.name in name:
                    window = simulator.findFirstR(AXTitle=name)
                    window.activate()
                    sleep(1)
                    element = window.findFirstR(AXTitle=text)
                    if element is not None:
                        return element

                    element2 = window.findFirstR(AXValue=text)
                    if element2 is not None:
                        return element2

            return None
        except Exception:
            return None
def fetch_atomac_ui_object(bundle_id=None):
	""" fetches the ui objects and properties of the opened windows  """
	try:
		return atomac.getAppRefByBundleId(bundle_id)
	except Exception:
		log.warning('Exception caught while  fetching atomac object', exc_info=True)
		return None
示例#7
0
def view_profile(cbundleID,index,remark=''):
    ''' View the profile and change the remark '''
    try:
        app = atomac.getAppRefByBundleId(cbundleID)
        chat_window = app.findFirst(AXRole=object_repo['unknown_window']['AXRole'],AXSubrole=object_repo['unknown_window']['AXSubrole'])
        time.sleep(2)
        panel = chat_window.findFirst(AXRole=object_repo['split_panel']['AXRole'])
        time.sleep(2)
        name_list_panel = panel.findFirst(AXRole=object_repo['scroll_area']['AXRole'])
        time.sleep(2)
        row_item = name_list_panel.findAll(AXRole=object_repo['row_item']['AXRole'])
        for item in row_item:
            if item.AXIndex == index -1:
                select_right_click_menu(app,item,1)
                break
        time.sleep(3)
        profile_window =app.windows()[1]
        profile_detail_panel = profile_window.findFirst(AXRole=object_repo['scroll_area']['AXRole'])
        time.sleep(2)
        remark_button = profile_detail_panel.findFirst(AXRole=object_repo['remark_button']['AXRole'])
        time.sleep(2)
        remark_button.Press()
        time.sleep(1)
        remark_field = profile_detail_panel.textFileds()[0]
        fill_text(remark_field,remark)
        close_profile_checkbox =profile_window.findFirst(AXRole=object_repo['remark_button']['AXRole'],AXIdentifier=object_repo['remark_button']['AXIdentifier'])
        time.sleep(2)
        close_profile_checkbox.Press()
    except Exception as er :
        logger("[-] Error @view_profile")
        logger("[-] Error is "+str(er))
示例#8
0
 def _get_sim_window(self):
     sim = atomac.getAppRefByBundleId(self.bid)
     windows = sim.windows(match = 'iOS Simulator*')
     if windows:
         return windows[0]
     else:
         raise Exception("Cannot get simulator window.")
 def launch_restore_manager():
     import atomac
     atomac.launchAppByBundleId('com.mozy.restoremanager')
     time.sleep(2)
     app = atomac.getAppRefByBundleId('com.mozy.restoremanager')
     if app:
         app.activate()
示例#10
0
def launchApplication():
    scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
    atomac.launchAppByBundlePath(scriptDir +
                                 "/build/Default/transient-property.app")
    time.sleep(0.5)
    application = atomac.getAppRefByBundleId(
        'fr.irccyn.molinaro.transient-property')
    return application
示例#11
0
def launchApplication():
    scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
    atomac.launchAppByBundlePath(scriptDir +
                                 "/build/Default/simple-preferences.app")
    time.sleep(0.5)
    application = atomac.getAppRefByBundleId(
        'fr.irccyn.molinaro.simple-preferences')
    return application
示例#12
0
def launchApplication():
    scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
    atomac.launchAppByBundlePath(scriptDir +
                                 "/build/Default/hidden-binding.app")
    time.sleep(0.5)
    application = atomac.getAppRefByBundleId(
        'fr.irccyn.molinaro.hidden-binding')
    return application
示例#13
0
文件: a.py 项目: d910aa14/atomac
def main():
    pos = 64, 170
    launchAppByBundleId('com.apple.Automator')
    automator = getAppRefByBundleId('com.apple.Automator')
    sleep(3)
    automator.doubleClickMouse(pos)
    sleep(3)
    automator.clickMouseButtonLeftWithMods(pos, ['<control_l>'])
示例#14
0
 def launch(self):
     if self.isRunning():
         self.sim = atomac.getAppRefByBundleId(self.bid)
         return self.sim
     else:
         atomac.launchAppByBundleId(self.bid)
         init_time = time.time()
         timeout = 20
         thinktime = 0.2
         
         while(time.time() - init_time < timeout):
             sim = atomac.getAppRefByBundleId(self.bid)
             if sim.windows():
                 self.sim = sim
                 return self.sim
             time.sleep(thinktime)
         raise Exception("Simulator launching time out!")
示例#15
0
def getApplicationReferenceID(Cbundleid):
    try:
        ReferenceID = atomac.getAppRefByBundleId(Cbundleid)
        #print ("ReferenceID of the Application : %s" % ReferenceID)
        logging.info("Application RefferenceID : %s" % ReferenceID)
    except Exception as er:
        logging.info('Not able to get Application ReferenceID')
        return False
    return ReferenceID
示例#16
0
def launch_app():
    global automator, currentWindow
    atomac.launchAppByBundleId('us.zoom.ringcentral')
    time.sleep(1)
    automator = atomac.getAppRefByBundleId('us.zoom.ringcentral')
    currentWindow = automator.windows()[0]
    signInBtn = currentWindow.findFirstR(AXRole='AXButton', AXTitle='Sign In')
    signInBtn.Press()
    wait_login_screen(15)
示例#17
0
 def query_app(self, name=None, pid=0, bundle_id=None):
     if name:
         app = atomac.getAppRefByLocalizedName(name)
     elif pid:
         app = atomac.getAppRefByPid(pid)
     elif bundle_id:
         app = atomac.getAppRefByBundleId(bundle_id)
     else:
         app = atomac.getFrontmostApp()
     return self._push(MacUiElementOperand(app))
    def wait_restore_finished(timeout=300, recheck_time=2):
        """
        wait restore to be finished
        :param timeout: wait_time
        :param recheck_time: sleep time
        :return: Boolean
        """

        LogHelper.info('wait restore to be finished')
        result = False
        import atomac
        app = atomac.getAppRefByBundleId('com.mozy.restoremanager')
        sa = None
        try:
            sa = atomac.getAppRefByBundleId('com.apple.SecurityAgent')
        except ValueError:
            LogHelper.info("Security Agent is not found")
            sa = None

        is_restore_complete = MacUIUtils.is_element_exist(app, AXRole='AXStaticText', AXValue='Complete:')
        restore_time = 0
        while (not is_restore_complete) and restore_time <= timeout:
            LogHelper.info("restore is not completed")
            if sa:
                sa_exist = MacUIUtils.is_element_exist(sa, AXRole='AXButton', AXTitle='Cancel')
            else:
                sa_exist = False

            if sa_exist:
                LogHelper.info("Cancel Security Agent")
                MacUIUtils.click_button(sa_exist)
            time.sleep(recheck_time)
            restore_time += recheck_time
            is_restore_complete = MacUIUtils.is_element_exist(app, AXRole='AXStaticText', AXValue='Complete:')
            if is_restore_complete:
                LogHelper.info("Restore completed, retsore take %d" % restore_time)
                result = True

        if restore_time >= timeout:
            LogHelper.error("Restore is not completed in %d second!" % timeout)

        return result
示例#19
0
def open_app(cbundID):
    ''' To open the App '''
    try:
        logger("[+] Opening the "+cbundID+"app")
        atomac.launchAppByBundleId(cbundleID)
        time.sleep(3)
        app = atomac.getAppRefByBundleId(cbundleID)
        app.activate()
    except Exception as er:
        logger("[-] Exception while opening the app")
        logger("[-] Error @open_app is "+str(er))
示例#20
0
    def from_bundle(cls, bundle, matcher, index=0, wait_time=1):
        app = None
        wait_t = 10
        while app is None and wait_t > 0:
            time.sleep(1)
            app = atomac.getAppRefByBundleId(bundle)
            wait_t -= 1

        if app:
            app.activate()
            return cls(app, matcher, index, wait_time)
示例#21
0
 def get_root(bundle_id=bundle_id, kwargs=kwargs, wait_time=root_wait_time):
     try:
         atomac.launchAppByBundleId(bundle_id)
         app = atomac.getAppRefByBundleId(bundle_id)
         app.activate()
     except ValueError as e:
         atomac.launchAppByBundleId(bundle_id)
         app = atomac.getAppRefByBundleId(bundle_id)
         app.activate()
     current_wait_second = 0
     parent = app.findFirstR(**kwargs)
     while (parent is None) and current_wait_second < wait_time:
         sleep_time = 5
         time.sleep(sleep_time)
         parent = app.findFirstR(**kwargs)
         current_wait_second += sleep_time
     if parent is None:
         print "error: parent is not find for kwargs %s in %d" % (kwargs, wait_time)
     else:
         parent.activate()
     return parent
示例#22
0
    def initialStore(self):
        """
        start AppleStore
        :return:
        """
        print "initialing appStore"
        atomac.launchAppByBundleId(self.bundle_name)
        pattern = re.compile(u'No role')
        trytime = self.tryTime

        while pattern.search(str(atomac.getAppRefByBundleId(self.bundle_name))):
            print "step 1 sleep 5 sec..."
            time.sleep(self.shortSleepTime)

        appStoreRef = atomac.getAppRefByBundleId(self.bundle_name)
        # print appStoreRef
        pattern = re.compile('None')
        while trytime > 0 and pattern.search(str(appStoreRef.AXMainWindow.findAll()[0])):
            print "network excetion!try again in {}s,trytime remain {} times".format(self.shortSleepTime, self.tryTime)
            time.sleep(self.shortSleepTime)
            trytime -= 1

        return appStoreRef
def click_appstore_icon(identifier=None):
	""" This function clicks the featured icon in the App Store """
	# open the product
	app_store = atomac.getAppRefByBundleId(app_store_id)
	app_store.activate()
	time.sleep(1)
	# search for the UI object
	app_store_obj = app_store.windows()[0].findAllR(AXRole='AXRadioButton', AXTitle='', AXIdentifier=identifier)
	if not len(app_store_obj):
		log.info('No clicking object found')
		return None
	# double click the ui obj
	double_click(app_store_obj[0])
	time.sleep(5)
	return 1
def open_app(bundle_id=None):
	""" to open the application using the bundle ids """
	if not bundle_id:
			log.debug('BundleId value is empty - %s' % bundle_id)
			return 0
	try:
		atomac.launchAppByBundleId(bundle_id)
		time.sleep(5)
		app_ref = atomac.getAppRefByBundleId(bundle_id)
		app_ref.activate()
		log.info('Bundle Id - %s is opened now' % bundle_id)
		return app_ref
	except Exception:
		log.error('Exception caught while opening app', exc_info=True)
		return 0
示例#25
0
文件: OSXUI.py 项目: adolli/Poco
    def EnumWindows(self, selector):
        names = []
        if 'bundleid' in selector:
            self.app = atomac.getAppRefByBundleId(selector['bundleid'])
            windows = self.app.windows()
            for i, w in enumerate(windows):
                names.append((w.AXTitle, i))
            return names

        if 'appname' in selector:
            self.app = atomac.getAppRefByLocalizedName(selector['appname'])
            windows = self.app.windows()
            for i, w in enumerate(windows):
                names.append((w.AXTitle, i))
            return names

        if 'appname_re' in selector:  # 此方法由于MacOS API,问题较多
            apps = atomac.NativeUIElement._getRunningApps()  # 获取当前运行的所有应用程序
            appset = set()  # 应用程序集合
            appnameset = set()  # 应用程序标题集合
            for t in apps:
                tempapp = atomac.getAppRefByPid(t.processIdentifier())
                if str(tempapp) == str(atomac.AXClasses.NativeUIElement()
                                       ):  # 通过trick判断应用程序是都否为空
                    continue
                attrs = tempapp.getAttributes()
                if 'AXTitle' in attrs:
                    tit = tempapp.AXTitle
                    if re.match(selector['appname_re'], tit):
                        appset.add(tempapp)
                        appnameset.add(
                            tit)  # 这里有Bug,可能会获取到进程的不同副本,所以要通过名字去判断是否唯一

            if len(appnameset) is 0:
                raise InvalidSurfaceException(
                    selector,
                    "Can't find any applications by the given parameter")
            if len(appnameset) != 1:
                raise NonuniqueSurfaceException(selector)
            while len(names) is 0:  # 有可能有多个副本,但只有一个真的应用程序有窗口,所以要枚举去找
                if len(appset) is 0:
                    return names
                self.app = appset.pop()
                windows = self.app.windows()  # 获取当前应用程序的所有窗口
                for i, w in enumerate(windows):
                    names.append((w.AXTitle, i))
            return names
        return names
示例#26
0
 def __init__(self, required_capabilities, desired_capabilities):
     self._required_capabilities = required_capabilities
     self._desired_capabilities = desired_capabilities
     self._async_script_timeout = self.get_default_timeout()
     self._implicit_wait = self.get_default_implicit_wait()
     self._timeouts = {}
     self._bundle_id = desired_capabilities.get("bundleId", "")
     self._should_launch_app = desired_capabilities.get("shouldLaunch", True) == True
     self._should_terminate_app = desired_capabilities.get("shouldTerminate", True) == True
     if self._should_launch_app:
         atomac.launchAppByBundleId(self._bundle_id)
         time.sleep(2) #FIXME: wait until app up or timeout
     self._app = atomac.getAppRefByBundleId(self._bundle_id)
     self._current_window = None
     self._active_element = None
     self._update_current_window_to_be_the_first()
     self._cache_of_elements_by_id = {} #FIXME: need to limit the cache and also purge on new windows etc
     self._cache_of_element_ids_by_element_name = {} #FIXME: need to limit the cache and also purge on new windows etc
示例#27
0
def main():
  # Assume ProPresenter is running; get the accessibility object for our slider
  print "Getting transition sliders..."
  pp = atomac.getAppRefByBundleId("com.renewedvision.ProPresenter4")
  textSlider = pp.findFirstR(AXRole="AXSlider", AXHelp="Slide transition time")
  bgSlider = pp.findFirstR(AXRole="AXSlider", AXHelp="Image/Video transition time")
  
  # Now start receiving MIDI messages
  print "Getting available MIDI controllers..."
  
  midiin = rtmidi.RtMidiIn()
  ports = range(midiin.getPortCount())
  if ports:
    for i in ports:
      print i, midiin.getPortName(i)
    print "Setting up lights..."
    midiout = setUpLights()
    midiin.openPort(0)
    try:
      print "Listening for MIDI..."
      while True:
        m = midiin.getMessage(250) # some timeout in ms
        if m != None:
          print_message(m, textSlider, bgSlider, pp)
          # hack around pyrtmidi bug; if messages are queued, midiin.getMessage
          # blocks until the timeout elapses if a timeout is specified
          m = midiin.getMessage()
          m1 = m
          while m1 != None: #flush queue and get the last "real" message
            m1 = midiin.getMessage()
            if m1 != None:
              m = m1
          if m != None:
            print_message(m, textSlider, bgSlider, pp)
    except KeyboardInterrupt:
      midiout.sendMessage(rtmidi.MidiMessage.controllerEvent(MIDI_CHANNEL, PREV_CONTROLLER, OFF_VALUE))
      midiout.sendMessage(rtmidi.MidiMessage.controllerEvent(MIDI_CHANNEL, NEXT_CONTROLLER, OFF_VALUE))
      midiout.sendMessage(rtmidi.MidiMessage.controllerEvent(MIDI_CHANNEL, BLANK_TEXT_CONTROLLER, OFF_VALUE))
      midiout.sendMessage(rtmidi.MidiMessage.controllerEvent(MIDI_CHANNEL, BLANK_BG_CONTROLLER, OFF_VALUE))
    midiout.sendMessage(rtmidi.MidiMessage.controllerEvent(MIDI_CHANNEL, BLANK_ALL_CONTROLLER, OFF_VALUE))
    midiout.sendMessage(rtmidi.MidiMessage.controllerEvent(MIDI_CHANNEL, LOGO_CONTROLLER, OFF_VALUE))
          
  else:
    print 'NO MIDI INPUT PORTS!'
 def restart_appium_server():
     LogHelper.info('===========Now Restarting Appium Server===========')
     print('===========Now Restarting Appium Server===========')
     atomac.launchAppByBundleId('com.appium.Appium')
     app = atomac.getAppRefByBundleId('com.appium.Appium')
     time.sleep(2)
     exec_button = app.findFirstR(AXRole='AXButton', AXIdentifier='_NS:15')
     dustbin_button = app.findFirstR(AXRole='AXButton',
                                     AXIdentifier='_NS:215')
     status = exec_button._getAttribute('AXTitle')
     if status == 'Stop':
         exec_button.Press()
         time.sleep(2)
     dustbin_button.Press()
     exec_button.Press()
     time.sleep(15)
     LogHelper.info(
         '===========Appium Server is launched successfully===========')
     print('===========Appium Server is launched successfully===========')
def search_in_appstore(search_value='Linux'):
	""" this function helps to search the apps in search filed  """
	try:
		app_store = atomac.getAppRefByBundleId(app_store_id)
		app_store.activate()
	except ValueError:
		return -1
	time.sleep(1)
	app_store_obj = app_store.windows()[0].findAllR(AXRole='AXTextField', AXRoleDescription='search text field')[0]
	click_left(app_store_obj)
	# select all
	app_store_obj.sendKeyWithModifiers('a', [COMMAND])
	# delete the previous entry
	app_store_obj.sendKey(DELETE)
	# enter the search value
	app_store_obj.sendKeys(search_value)
	# enter key to search
	app_store_obj.sendKey(RETURN)
	time.sleep(10)
示例#30
0
def login_app(cbundleID):
    '''login application with username and password'''
    try:
        atomac.launchAppByBundleId(cbundleID)
        app = atomac.getAppRefByBundleId(cbundleID)
        login_window = app.windows()[0]
        time.sleep(2)
        username  = login_window.textFields()[0]
        click_left(username)
        username.sendKeys("YOUR-USERNAME")
        time.sleep(2)
        password = login_window.textFields()[1]
        click_left(password)
        password.sendKeys("YOUR-PASSWORD")
        login_checkbox = login_window.findFirst(AXRole=object_repo['login_checkbox']['AXRole'],AXIdentifier=object_repo['login_checkbox']['AXIdentifier'])
        login_checkbox.Press()
    except Exception as er:
        print "[-] Error @login_app"
        print "[-] Error is "+str(er)
示例#31
0
 def __init__(self, matcher, index=0, wait_time=1):
     if self.app == None:
         atomac.launchAppByBundleId('com.mozy.restoremanager')
         time.sleep(2)
         self.app = atomac.getAppRefByBundleId('com.mozy.restoremanager')
         self.app.activate()
         self.restore_manager = self.app.findFirstR(AXRole='AXWindow',
                                                    AXIdentifier='_NS:6')
     kwargs = {}
     for (attr, value) in matcher.items():
         kwargs[attr] = value
     time.sleep(wait_time)
     if index == 0:
         self.element = self.restore_manager.findFirstR(**kwargs)
         if self.element == None:
             self.element = self.app.findFirstR(**kwargs)
     else:
         self.element = self.restore_manager.findAllR(**kwargs)[index]
         if self.element == None:
             self.element = self.app.findAllR(**kwargs)[index]
    def launch_mozy_application():
        """
        launch app
        :return:
        """
        bundleId = MacController().spbundleid
        WindowName = 'MozyPro'
        try:
            atomac.launchAppByBundleId(bundleId)
        except RuntimeError as e:
            print e.message
        mozy_window = None

        app = atomac.getAppRefByBundleId(bundleId)
        window = MacUIUtils.wait_element(app, AXRole='AXWindow')
        app.activate()
        btn_showall = MacUIUtils.wait_element(window,
                                              AXRole='AXButton',
                                              AXTitle='Show All')
        MacUIUtils.click_button(btn_showall)
        window = MacUIUtils.wait_element(app, AXRole='AXWindow')

        title = window.AXTitle
        if title == 'MozyPro':  # it is already mozy window
            mozy_window = window
        elif title == "System Preferences":
            btn_mozypro = MacUIUtils.wait_element(app,
                                                  AXRole='AXButton',
                                                  AXTitle=WindowName)
            btn_mozypro.Press()
            mozy_window = MacUIUtils.wait_element(app,
                                                  AXRole='AXWindow',
                                                  AXTitle=WindowName)
        else:
            raise Exception('Not implemented yet')

        if mozy_window.AXRole:
            MacMozyUIBase.mozy_window = mozy_window
            return mozy_window
        else:
            return False
示例#33
0
def send_message(cbundleID,name='',msg=''):
    '''serach the name whom is trying to start a chat with '''
    '''send message to the guy whom you are chatting with'''
    try:
        app = atomac.getAppRefByBundleId(cbundleID)
        chat_window = app.windows()[0]
        time.sleep(2)
        panel = chat_window.findFirst(AXRole=object_repo['split_panel']['AXRole'])
        time.sleep(2)
        serach_field = panel.textFileds()[0]
        fill_text(serach_field,name)
        chat_panel=panel.findFirst(AXRole=object_repo['split_panel']['AXRole'])
        time.sleep(2)
        emotion_button = chat_panel.findFirst()
        input_srcoll_area = chat_panel.findAll(AXRole=object_repo['scroll_area']['AXRole'])[1]
        time.sleep(2)
        input_area =input_srcoll_area.textAreas()[0]
        fill_text(input_area,msg)
    except Exception as er :
        logger("[-] Error @view_profile")
        logger("[-] Error is "+str(er))
示例#34
0
    def is_setup_assistant_launched(wait_time=60):
        result = False
        spbundleid = MacController().spbundleid
        app = None
        wait_t = wait_time
        while app is None and wait_t > 0:
            time.sleep(1)
            app = atomac.getAppRefByBundleId(spbundleid)
            wait_t -= 1

        window = None
        if app is not None:
            window = AppUIElement(app, {'AXRole': 'AXWindow'}, 0, wait_time)

        if window is not None:
            brand = RUNNER_CONFIG.get('OEM_CLIENT')
            window_name = MacController.normalize_brand_name(brand)
            title = window.get_title()
            if title == window_name:
                result = True

        return result
示例#35
0
    def check_installation(cls):
        found = 0
        cmd = 'open -a Firefox'

        log.info("[Firefox] Starting firefox...")

        if not cls.run(cmd):
            log.info("[Firefox] Failed to open firefox")
            return 0

        try:
            firefox = atomac.getAppRefByBundleId(BID_FIREFOX)
            found = 1
            firefox.activate()
            sleep(5)
            capture_screen('firefox_install_success')
            sleep(2)
            atomac.terminateAppByBundleId(BID_FIREFOX)
            log.info("[Firefox] Firefox launched successfully!")
        except ValueError:
            log.error("[Firefox] Firefox not running!")

        return found
示例#36
0
    def start_mac_mozy(self):
        """
            launch app
            :return:
            """
        import atomac
        from apps.mac.mac_lib.mac_ui_util import MacUIUtils
        bundleId = MacController().spbundleid
        WindowName = 'MozyPro'
        try:
            atomac.launchAppByBundleId(bundleId)
        except RuntimeError as e:
            print e.message

        app = atomac.getAppRefByBundleId(bundleId)
        app.activate()

        window = MacUIUtils.wait_element(app, AXRole='AXWindow')
        btn_showall = MacUIUtils.wait_element(window,
                                              AXRole='AXButton',
                                              AXTitle='Show All')
        MacUIUtils.click_button(btn_showall)

        title = window.AXTitle
        if title == 'MozyPro':  # it is already mozy window
            mozy_window = window
        elif title == "System Preferences":
            btn_mozypro = MacUIUtils.wait_element(app,
                                                  AXRole='AXButton',
                                                  AXTitle=WindowName)
            btn_mozypro.Press()
            mozy_window = MacUIUtils.wait_element(app,
                                                  AXRole='AXWindow',
                                                  AXTitle=WindowName)

        return mozy_window
    # 停止记录
    def stop_record():
        start_record()


# windows上安装atomac失败,便于调试其他函数
else:

    def start_record():
        pass

    def stop_record():
        pass

    def get_systeminfo(instrument, appname):
        return ['1', '2', '3']

    def get_graphinfo(instrument):
        return [['1', '2', '3']]

    def get_appref(bundleid):
        pass

    def jump_page(a, b):
        pass

if __name__ == "__main__":
    #print(get_graphinfo("aa"))
    instrument = atomac.getAppRefByBundleId("com.apple.dt.Instruments")
    print(get_systeminfo(instrument, "test"))
示例#38
0
#!/usr/bin/python
# https://pypi.python.org/pypi/atomac
# https://github.com/pyatom/pyatom/blob/master/atomac/AXClasses.py

import atomac, sys, time, random, string
import AppKit, os

sourceFilePath = os.path.dirname(__file__) + '/z.observingPrefsInDocument'
ok = AppKit.NSWorkspace.sharedWorkspace().openFile_ (sourceFilePath) 
if not ok:
    print '*** Erreur 0 ***'
    sys.exit (1)

bundleName = 'fr.irccyn.molinaro.observingPrefsInDocument'
#atomac.launchAppByBundleId (bundleName)
monAppli = atomac.getAppRefByBundleId (bundleName)
time.sleep (0.5)

#print monAppli
#print monAppli.windows ()

documentWindow = monAppli.windows () [0]
documentString = documentWindow.findFirst (AXDescription='documentString')
transientPrefsString = documentWindow.findFirst (AXDescription='transientPrefsString')
resultingString = documentWindow.findFirst (AXDescription='resultingString')

#--- Change document string
newDocumentValue = ''.join (random.choice (string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(8))
documentString.AXFocused = True
documentString.AXValue = newDocumentValue
documentString.Confirm ()
示例#39
0
__author__ = 'mqm'

import re
import atomac
import time

#atomac.launchAppByBundleId('com.apple.mail')
mail = atomac.getAppRefByBundleId('com.apple.mail')
time.sleep(2)
window = mail.windows()[0]
print window
#input = "AXToolbar/AXButton"
#input = "AXToolbar/AXButton[2]"
#input = 'AXToolbar/AXButton[name=New Message]'
#input = '/AXWindow[1]/AXToolbar/AXButton[name=New Message]'
#input = '/AXWindow[title=New Message]/AXTextField[4]'
input = '/AXWindow[title=New Message]/AXScrollArea/AXWebArea/AXStaticText'


parts = input.split('/')
current_node = window
for part in parts:
    print part
    if current_node is None:
        break
    if part == "":
        current_node = mail
        continue
    search_result_like_array = re.search('(\w+)[[]?(\d+)[]]?', part)
    search_result_like_property= re.search('(\w+)[[]?(\w+)=([^]]+)[]]?', part)
    if search_result_like_array is not None:
示例#40
0
def verify(statement):
    if statement:
        print "passed"
    else:
        print "failed"


# defs
bundleId = "com.kapralos.Unbelievable"
appTitle = "Unbelievable"
upperCaseRadioTitle = "Upper case"
lowerCaseRadioTitle = "Lower case"
transformButtonTitle = "Transform text"

at.launchAppByBundleId(bundleId)
app = at.getAppRefByBundleId(bundleId)

# there is no notification app finish launch notification in atomac, so set a 1-sec sleep
sleep(1)
appWindow = app.windows()[0]
print "App title: " + appWindow.AXTitle

print appWindow.findAll()

inputTextLabel = appWindow.findFirst(AXRole="AXStaticText")
print inputTextLabel

inputTextField = appWindow.findFirst(AXRole="AXTextField")
prefixCheckBox = appWindow.findFirst(AXRole="AXCheckBox")
upperCaseRadio = appWindow.findFirst(AXRole="AXRadioGroup").findFirst(AXTitle=upperCaseRadioTitle)
lowerCaseRadio = appWindow.findFirst(AXRole="AXRadioGroup").findFirst(AXTitle=lowerCaseRadioTitle)
示例#41
0
def check_button_functionality(cbundleID,obj_to_screenshot_cut,matrix_x=0,matrix_y=0):
    '''Check the functionality on the split panel:
       --send emotion icons
       --send nudge
       --cut sreenshot
       --send picture
       --message mamagement
    '''
    try:
        app = atomac.getAppRefByBundleId(cbundleID)
        chat_window = app.windows()[0]
        time.sleep(2)
        panel = chat_window.findFirst(AXRole=object_repo['split_panel']['AXRole'])
        time.sleep(2)
        chat_panel=panel.findFirst(AXRole=object_repo['split_panel']['AXRole'])
        time.sleep(2)
        buttons = chat_panel.findAll(AXRole=object_repo['button']['AXRole'])
        time.sleep(2)
        # send a nudge
        # nudge_button = buttons[2]
        # nudge_button.Press()
        # # send a emotion icon
        # time.sleep(2)
        # emotion_button = buttons[0]
        # click_left(emotion_button)
        # emotion_window = app.findFirst(AXRole=object_repo['unknown_window']['AXRole'],AXSubrole=object_repo['unknown_window']['AXSubrole'])
        # time.sleep(2)
        # emotion_panel =emotion_window.findFirst(AXRole=object_repo['scroll_area']['AXRole'])
        # time.sleep(2)
        # position = emotion_panel.AXPosition
        # size = emotion_panel.AXSize
        # clickpoint = ((position[0] + math.floor(size[0] / 11) * matrix_x), (position[1] + math.floor(size[1] / 5) * matrix_y))
        # emotion_panel.clickMouseButtonLeft(clickpoint)
        # app.sendKey(RETURN)
        # send a sreen shot
        screen_shot_button = buttons[1]
        # screen_shot_button_position = screen_shot_button.AXPosition
        # screen_shot_button_size =screen_shot_button.AXSize
        # start_posx = screen_shot_button_position[0]
        # start_posy = screen_shot_button_position[1]
        # dest_posx = screen_shot_button_position[0]+screen_shot_button_size[0]
        # dest_posy = screen_shot_button_position[1]+screen_shot_button_size[1]
        # double_click_posx = screen_shot_button_position[0]+screen_shot_button_size[0]/2
        # double_click_posy = screen_shot_button_position[1]+screen_shot_button_size[1]/2
        # double_click_coord = (double_click_posx,double_click_posy)

        # key_event.mousemove(start_posx,start_posy)
        # key_event.mouseclickdn(start_posx,start_posy)
        # key_event.mousedrag(dest_posx,dest_posy)
        # key_event.mouseclickup(dest_posx,dest_posy)
        # app.doubleClickMouse(double_click_coord)
        # time.sleep(1)
        click_left(screen_shot_button)
        time.sleep(2)
        cut_screen_shot(app,obj_to_screenshot_cut)
        app.sendKey(RETURN)

        # upload picture(s)
        upload_pic_button = buttons[3]
        upload_pic_button.Press()


    except Exception as er:
        print "[-] Error @check_button_functionality"
        print "[-] Error is "+str(er)
    window.sendKey('<num_enter>')
    time.sleep(0.5)
    group.groups()[7].groups()[0].textFields()[0].setString("AXValue", lastName)
    group.groups()[7].groups()[1].textFields()[0].setString("AXValue", firstName)
    group.groups()[8].groups()[0].textFields()[0].setString("AXValue", street)
    group.groups()[9].groups()[0].textFields()[0].setString("AXValue", index)
    group.groups()[9].groups()[1].textFields()[0].setString("AXValue", city)
    group.groups()[10].groups()[0].textFields()[0].setString("AXValue", cityCode)
    group.groups()[10].groups()[1].textFields()[0].setString("AXValue", phoneNumber)
    time.sleep(0.5)
    getContent(window).buttons('Create Apple ID')[0].Press()


atomac.launchAppByBundleId('com.apple.iTunes')
time.sleep(10)
itunes = atomac.getAppRefByBundleId('com.apple.iTunes')
window = itunes.windows()[0]

signOut = itunes.menuItem('Account', 'Sign Out')
if(signOut):
    signOut.Press()
    time.sleep(7)

itunes.menuItem('Account', 1).Press()
time.sleep(7)
signIn(itunes.windows()[0])
time.sleep(7)
if itunes.windows()[0].AXIdentifier == "_NS:15":
    itunes.windows()[0].findFirst(AXRole = "AXButton", AXSubrole = "AXCloseButton").Press()
    time.sleep(2)
    getAppleIDWindow(window)
示例#43
0
import atomac
import time
bundle_name = 'com.apple.iTunes'
atomac.launchAppByBundleId(bundle_name)
appStoreRef = atomac.getAppRefByBundleId(bundle_name)
_searchTextField = appStoreRef.AXMainWindow.findFirst(AXRole='AXTextField')

x, y = _searchTextField.AXPosition
width, height = _searchTextField.AXSize
_searchTextField.AXValue = '1111'
time.sleep(5)
_searchTextField.clickMouseButtonLeft((x + width / 2, y + height / 2))
time.sleep(5)
_searchTextField.sendKey('<cursor_right>')
_searchTextField.sendKey('<space>')
_searchTextField.sendKey('<backspace>')
_searchTextField.sendKey('\r')

print appStoreRef.AXMainWindow.AXSize
示例#44
0
# Copyright(c) 2019 Yuki KODAMA / @kuy
# This script is distributed under the MIT License.

import time
import cv2
import atomac

cap = cv2.VideoCapture(0)
ai = atomac.getAppRefByBundleId('com.adobe.illustrator')

while True:
    ret, frame = cap.read()

    frame = cv2.resize(frame, (int(frame.shape[1]/24), int(frame.shape[0]/24)))
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Camera: ' + str(frame.shape[1]) + 'x' + str(frame.shape[0]), frame)

    buf = ''
    for y in range(frame.shape[0]):
        for x in range(frame.shape[1]):
            buf += '%02x' % frame[y, x]

    atomac.Clipboard.copy(buf)

    ai.sendKeyWithModifiers('a', [atomac.AXKeyCodeConstants.COMMAND])
    ai.sendKey(atomac.AXKeyCodeConstants.DELETE)
    ai.sendKeyWithModifiers('v', [atomac.AXKeyCodeConstants.COMMAND])

    k = cv2.waitKey(1)
    if k == 27:
        break
 def get_appref(bundleid):
     instrument = atomac.getAppRefByBundleId(bundleid)
     return instrument
示例#46
0
 def isRunning(self):
     try:
         atomac.getAppRefByBundleId(self.bid)   
         return True 
     except:
         return False
示例#47
0
    group.groups()[7].groups()[1].textFields()[0].setString(
        "AXValue", firstName)
    group.groups()[8].groups()[0].textFields()[0].setString("AXValue", street)
    group.groups()[9].groups()[0].textFields()[0].setString("AXValue", index)
    group.groups()[9].groups()[1].textFields()[0].setString("AXValue", city)
    group.groups()[10].groups()[0].textFields()[0].setString(
        "AXValue", cityCode)
    group.groups()[10].groups()[1].textFields()[0].setString(
        "AXValue", phoneNumber)
    time.sleep(0.5)
    getContent(window).buttons('Create Apple ID')[0].Press()


atomac.launchAppByBundleId('com.apple.iTunes')
time.sleep(10)
itunes = atomac.getAppRefByBundleId('com.apple.iTunes')
window = itunes.windows()[0]

signOut = itunes.menuItem('Account', 'Sign Out')
if (signOut):
    signOut.Press()
    time.sleep(7)

itunes.menuItem('Account', 1).Press()
time.sleep(7)
signIn(itunes.windows()[0])
time.sleep(7)
if itunes.windows()[0].AXIdentifier == "_NS:15":
    itunes.windows()[0].findFirst(AXRole="AXButton",
                                  AXSubrole="AXCloseButton").Press()
    time.sleep(2)
示例#48
0
import atomac
import time
import pyscreeze
atomac.launchAppByBundleId('com.apple.calculator')
calc = atomac.getAppRefByBundleId('com.apple.calculator')
time.sleep(2)
window = calc.windows()[0]
print window.getAttributes()
print window.AXPosition
print window.AXSize
rect = [window.AXPosition[0], window.AXPosition[1], window.AXSize[0], window.AXSize[1]]
print rect
calc_img = pyscreeze.screenshot(region=rect)
calc_img.load() #important!!!!!
calc_img.save("calc.png", "PNG")
print calc_img
from base64 import encodestring, b64encode
from StringIO import StringIO
buffer_in_memory = StringIO()
calc_img.save(buffer_in_memory, 'PNG')
buffer_in_memory.seek(0)
img_base_64 = b64encode(buffer_in_memory.getvalue())
print img_base_64
示例#49
0
文件: auto.py 项目: zbo/AutoPyMac
import atomac
import time

atomac.launchAppByBundleId('us.zoom.ringcentral')
time.sleep(1)
automator = atomac.getAppRefByBundleId('us.zoom.ringcentral')
window = automator.windows()[0]
print window.AXTitle
all=window.findAll()
all_in_group=all[0].findAll()
sign_in_button=all_in_group[2]
sign_in_button.Press()
time.sleep(10)
window = automator.windows()[0]
all=window.findAll()
print len(all)
#all[3].Press() #3 is close
#all[4].Press() #4 is max
#all[5].Press() #5 is min
web_area=all[0].findAll()[0]
web_all=web_area.findAll()
for i in range(len(web_all)):
    group_all=web_all[i].findAll()
    for j in range(0,len(group_all)):
        print '=================='+str(j)+'================'
        print group_all[j]
        print group_all[j].getActions()