def zoom_with_mouse_wheel(nr_of_times=1, zoom_type=None): """Zoom in/Zoom out using the mouse wheel. :param nr_of_times: Number of times the 'zoom in'/'zoom out' action should take place. :param zoom_type: Type of the zoom action('zoom in'/'zoom out') intended to be performed. :return: None. """ # MAC needs doubled number of mouse wheels to zoom in correctly. if OSHelper.is_mac(): nr_of_times *= 2 # Move focus in the middle of the page to be able to use the scroll. Mouse().move(Location(Screen.SCREEN_WIDTH // 4, Screen.SCREEN_HEIGHT // 2)) for i in range(nr_of_times): if OSHelper.is_mac(): key_down('command') else: key_down('ctrl') Mouse().scroll(dy=zoom_type, dx=0) if OSHelper.is_mac(): key_up('command') else: key_up('ctrl') time.sleep(Settings.DEFAULT_UI_DELAY) Mouse().move(Location(0, 0))
def __init__(self): self.root = Tk() self.root.overrideredirect(1) s_width = MULTI_MONITOR_AREA['width'] s_height = MULTI_MONITOR_AREA['height'] self.root.wm_attributes('-topmost', True) canvas = Canvas(self.root, width=s_width, height=s_height, borderwidth=0, highlightthickness=0, bg=Color.BLACK.value) canvas.grid() Canvas.draw_circle = _draw_circle Canvas.draw_rectangle = _draw_rectangle if OSHelper.is_mac(): self.root.wm_attributes('-fullscreen', 1) self.root.wm_attributes('-transparent', True) self.root.config(bg='systemTransparent') canvas.config(bg='systemTransparent') canvas.pack() if OSHelper.is_windows(): self.root.wm_attributes('-transparentcolor', Color.BLACK.value) if OSHelper.is_linux(): self.root.wait_visibility(self.root) self.root.attributes('-alpha', 0.7) self.canvas = canvas
def open_directory(directory): if OSHelper.is_windows(): os.startfile(directory) elif OSHelper.is_linux(): os.system('xdg-open \"' + directory + '\"') else: os.system('open \"' + directory + '\"')
def create_region_for_hamburger_menu(): """Create region for hamburger menu pop up.""" hamburger_menu_pattern = NavBar.HAMBURGER_MENU try: wait(hamburger_menu_pattern, 10) click(hamburger_menu_pattern) time.sleep(0.5) sign_in_to_sync = Pattern('sign_in_to_sync.png') if OSHelper.is_linux(): quit_menu_pattern = Pattern('quit.png') return RegionUtils.create_region_from_patterns(None, sign_in_to_sync, quit_menu_pattern, None, padding_right=20) elif OSHelper.is_mac(): help_menu_pattern = Pattern('help.png') return RegionUtils.create_region_from_patterns(None, sign_in_to_sync, help_menu_pattern, None, padding_right=20) else: exit_menu_pattern = Pattern('exit.png') return RegionUtils.create_region_from_patterns(None, sign_in_to_sync, exit_menu_pattern, None, padding_right=20) except (FindError, ValueError): raise APIHelperError( 'Can\'t find the hamburger menu in the page, aborting test.')
def open_about_firefox(): """Open the 'About Firefox' window.""" if OSHelper.get_os() == OSPlatform.MAC: type(Key.F3, modifier=KeyModifier.CTRL) type(Key.F2, modifier=KeyModifier.CTRL) time.sleep(0.5) type(Key.RIGHT) type(Key.DOWN) type(Key.DOWN) type(Key.ENTER) elif OSHelper.get_os() == OSPlatform.WINDOWS: type(Key.ALT) if args.locale != 'ar': type(Key.LEFT) else: type(Key.RIGHT) type(Key.ENTER) type(Key.UP) type(Key.ENTER) else: type(Key.F10) if args.locale != 'ar': type(Key.LEFT) else: type(Key.RIGHT) type(Key.UP) type(Key.ENTER)
def maximize_window(): """Maximize the browser window to fill the screen. This is NOT Full Screen mode. """ if OSHelper.is_mac(): # There is no keyboard shortcut for this on Mac. We'll do it the old fashioned way. # This image is of the three window control buttons at top left of the window. # We have to resize the window to ensure maximize works properly in all cases. window_controls_pattern = Pattern('window_controls.png') controls_location = find(window_controls_pattern) xcoord = controls_location.x ycoord = controls_location.y width, height = window_controls_pattern.get_size() drag_start = Location(xcoord + 70, ycoord + 5) drag_end = Location(xcoord + 75, ycoord + 5) Mouse().drag_and_drop(drag_start, drag_end, duration=0.1) # Alt key changes maximize button from full screen to maximize window. maximize_button = window_controls_pattern.target_offset( width / 2 - 3, 0) key_down(Key.ALT) click(maximize_button) key_up(Key.ALT) elif OSHelper.is_windows(): type(text=Key.UP, modifier=KeyModifier.WIN) else: type(text=Key.UP, modifier=[KeyModifier.CTRL, KeyModifier.META]) time.sleep(Settings.DEFAULT_UI_DELAY)
def restore_window_control(window_type): """Click on restore window control. :param window_type: Type of window that need to be restored. :return: None. """ find_window_controls(window_type) if window_type == 'auxiliary': if OSHelper.is_mac(): key_down(Key.ALT) width, height = AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.get_size() click(AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.target_offset(width - 10, height / 2), align=Alignment.TOP_LEFT) key_up(Key.ALT) else: if OSHelper.is_linux(): reset_mouse() click(AuxiliaryWindow.ZOOM_RESTORE_BUTTON) else: if OSHelper.is_mac(): key_down(Key.ALT) width, height = MainWindow.MAIN_WINDOW_CONTROLS.get_size() click(MainWindow.MAIN_WINDOW_CONTROLS.target_offset(width - 10, height / 2), align=Alignment.TOP_LEFT) key_up(Key.ALT) else: if OSHelper.is_linux(): reset_mouse() click(MainWindow.RESIZE_BUTTON)
def restore_window_from_taskbar(option=None): """Restore firefox from task bar.""" if OSHelper.is_mac(): try: click(Pattern('main_menu_window.png')) if option == "browser_console": click(Pattern('window_browser_console.png')) else: click(Pattern('window_firefox.png')) except FindError: raise APIHelperError('Restore window from taskbar unsuccessful.') elif OSHelper.get_os_version() == 'win7': try: click(Pattern('firefox_start_bar.png')) if option == "library_menu": click(Pattern('firefox_start_bar_library.png')) if option == "browser_console": click(Pattern('firefox_start_bar_browser_console.png')) except FindError: raise APIHelperError('Restore window from taskbar unsuccessful.') else: type(text=Key.TAB, modifier=KeyModifier.ALT) if OSHelper.is_linux(): Mouse().move(Location(0, 50)) time.sleep(Settings.DEFAULT_UI_DELAY)
def get_local_firefox_path() -> str or None: """Checks if Firefox is installed on your machine.""" paths = { 'osx': [ '/Applications/Firefox.app/Contents/MacOS/firefox', '/Applications/Firefox Developer Edition.app/Contents/MacOS/firefox', '/Applications/Firefox Nightly.app/Contents/MacOS/firefox' ], 'win': [ 'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', 'C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe', 'C:\\Program Files (x86)\\Nightly\\firefox.exe', 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', 'C:\\Program Files\\Firefox Developer Edition\\firefox.exe', 'C:\\Program Files\\Nightly\\firefox.exe' ], 'linux': ['/usr/bin/firefox', '/usr/lib/firefox/firefox'] } if OSHelper.is_windows(): paths['win'].append(PathManager.get_win_environment_path()) for path in paths[OSHelper.get_os().value]: if os.path.exists(path): return path return None
def get_active_modifiers(key): """Gets all the active modifiers depending on the used OS. :param key: Key modifier. :return: Returns an array with all the active modifiers. """ all_modifiers = [ Key.SHIFT, Key.CTRL] if OSHelper.is_mac(): all_modifiers.append(Key.CMD) elif OSHelper.is_windows(): all_modifiers.append(Key.WIN) else: all_modifiers.append(Key.META) all_modifiers.append(Key.ALT) active_modifiers = [] for item in all_modifiers: try: for key_value in key: if item == key_value.value: active_modifiers.append(item) except TypeError: if item == key.value: active_modifiers.append(item) return active_modifiers
def is_blocked(bug_id): """Checks if a Github issue/Bugzilla bug is blocked or not.""" try: if 'issue_' in bug_id: bug = get_github_issue(bug_id) if bug is None: return True if bug.state == 'closed': return False else: if OSHelper.get_os() in bug.title: return True return False else: bug = get_bugzilla_bug(bug_id) if bug is None: return True if bug.status in ['CLOSED', 'RESOLVED']: return False else: if bugzilla_os[OSHelper.get_os(). value] == bug.op_sys or bug.platform in [ 'All', 'Unspecified' ]: return True return False except BugManagerError as e: logger.error(str(e)) return True
def open_downloads(): """Open the Downloads dialog.""" if OSHelper.is_mac(): type(text='j', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='j', modifier=KeyModifier.CTRL) else: type(text='y', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def open_library(): """Open the Library window.""" if OSHelper.is_mac(): type(text='b', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) elif OSHelper.is_windows(): type(text='b', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='o', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def select_last_tab(): """Select the last tab.""" if OSHelper.is_mac(): type(text='9', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='9', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='9', modifier=KeyModifier.CTRL)
def minimize_window(): """Minimize the browser window to the application launch bar.""" if OSHelper.is_mac(): type(text='m', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text=Key.DOWN, modifier=KeyModifier.WIN) else: type(text=Key.DOWN, modifier=[KeyModifier.CTRL, KeyModifier.META]) time.sleep(Settings.DEFAULT_UI_DELAY)
def delete_selected_file(): """Delete selected file/files inside a folder.""" if OSHelper.is_mac(): type(text=Key.BACKSPACE, modifier=KeyModifier.CMD) elif OSHelper.get_os_version() == 'win7': type(text=Key.DELETE) type(text='y') else: type(text=Key.DELETE)
def open_firefox_menu(): """ Opens Firefox top menu """ if OSHelper.is_linux(): key_down(Key.ALT) time.sleep(0.5) key_up(Key.ALT) elif OSHelper.is_windows(): type(Key.ALT)
def select_tab(num): """Select a given tab (only 1-8). param: num is a string 1-8. example: '4'. """ if OSHelper.is_mac(): type(text=str(num), modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text=str(num), modifier=KeyModifier.CTRL) else: type(text=str(num), modifier=KeyModifier.ALT)
def launch_control_center(): profile_path = os.path.join(get_core_args().workdir, 'cc_profile') fx_path = PathManager.get_local_firefox_path() if fx_path is None: logger.error( 'Can\'t find local Firefox installation, aborting Iris run.') return False, None args = ['http://127.0.0.1:%s' % get_core_args().port] process_args = {'stream': None} profile = MozProfile(profile=profile_path, preferences={}) if OSHelper.is_windows(): process = subprocess.Popen([ fx_path, '-no-remote', '-new-tab', args, '--wait-for-browser', '-foreground', '-profile', profile.profile ], shell=False) else: fx_runner = FirefoxRunner(binary=fx_path, profile=profile, cmdargs=args, process_args=process_args) fx_runner.start() server = LocalWebServer(get_core_args().workdir, get_core_args().port) server.stop() time.sleep(Settings.DEFAULT_UI_DELAY) if OSHelper.is_mac(): type(text='q', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='w', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='q', modifier=KeyModifier.CTRL) if OSHelper.is_windows(): if process.pid is not None: try: logger.debug('Closing Firefox process ID: %s' % process.pid) process = psutil.Process(process.pid) for proc in process.children(recursive=True): proc.kill() process.kill() except psutil.NoSuchProcess: pass else: try: fx_runner.stop() except Exception as e: logger.debug('Error stopping fx_runner') logger.debug(e) return server.result
def quit_firefox(): """Quit the browser.""" # Press the ESC key to exit any modal dialogs that might prevent key capture. type(text=Key.ESC) # Wait before quitting Firefox to avoid concurrency. time.sleep(1) if OSHelper.is_mac(): type(text='q', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='q', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='q', modifier=KeyModifier.CTRL)
def pytest_runtest_teardown(self, item): BaseTarget.pytest_runtest_teardown(self, item) try: if not OSHelper.is_windows(): if item.funcargs['firefox'].runner and item.funcargs[ 'firefox'].runner.process_handler: quit_firefox() status = item.funcargs[ 'firefox'].runner.process_handler.wait(10) if status is None: item.funcargs['firefox'].browser.runner.stop() else: item.funcargs['firefox'].stop() if not target_args.save: profile_instance = item.funcargs['firefox'].profile if os.path.exists(profile_instance.profile): try: shutil.rmtree(profile_instance.profile, ignore_errors=True) except sqlite3.OperationalError: pass else: logger.error('Invalid Path: %s' % profile_instance.profile) except (AttributeError, KeyError): pass
def stop(self): if OSHelper.is_windows(): quit_firefox() if FXRunner.process.pid is not None: logger.debug('Closing Firefox process ID: %s' % FXRunner.process.pid) try: process = psutil.Process(pid=FXRunner.process.pid) if process.children() is not None: for proc in process.children(recursive=True): proc.kill() if psutil.pid_exists(process.pid): logger.debug('Terminating PID :%s' % process.pid) process.terminate() except psutil.NoSuchProcess: logger.debug('Failed to find and close Firefox PID: %s' % FXRunner.process.pid) # shutdown_process('firefox') else: if self.runner and self.runner.process_handler: quit_firefox() status = self.runner.process_handler.wait( DEFAULT_FIREFOX_TIMEOUT) if status is None: self.runner.stop()
def select_search_bar(): """If the search bar is present, select the search bar, otherwise this selects the location bar.""" if OSHelper.is_mac(): type(text='k', modifier=KeyModifier.CMD) else: type(text='k', modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
def new_tab(): """Open a new browser tab.""" if OSHelper.is_mac(): type(text='t', modifier=KeyModifier.CMD) else: type(text='t', modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY)
def create_region_from_image(image): """Create region starting from a pattern. :param image: Pattern used to create a region. :return: None. """ try: from mattapi.api.rectangle import Rectangle from mattapi.api.enums import Alignment m = image_find(image) if m: sync_pattern = Pattern('sync_hamburger_menu.png') sync_width, sync_height = sync_pattern.get_size() sync_image = image_find(sync_pattern) top_left = Rectangle(sync_image.x, sync_image.y, sync_width, sync_width). \ apply_alignment(Alignment.TOP_RIGHT) if OSHelper.is_mac(): exit_pattern = Pattern('help_hamburger_menu.png') else: exit_pattern = Pattern('exit_hamburger_menu.png') exit_width, exit_height = exit_pattern.get_size() exit_image = image_find(exit_pattern) bottom_left = Rectangle(exit_image.x, exit_image.y, exit_width, exit_height). \ apply_alignment(Alignment.BOTTOM_RIGHT) x0 = top_left.x + 2 y0 = top_left.y height = bottom_left.y - top_left.y width = Screen().width - top_left.x - 2 region = Region(x0, y0, width, height) return region else: raise APIHelperError('No matching found.') except FindError: raise APIHelperError('Image not present.')
def is_lock_on(key): """Determines if a keyboard key(CAPS LOCK, NUM LOCK or SCROLL LOCK) is ON. :param key: Keyboard key(CAPS LOCK, NUM LOCK or SCROLL LOCK). :return: TRUE if keyboard_key state is ON or FALSE if keyboard_key state is OFF. """ if OSHelper.is_windows(): hll_dll = ctypes.WinDLL("User32.dll") keyboard_code = 0 if key == Key.CAPS_LOCK: keyboard_code = 0x14 elif key == Key.NUM_LOCK: keyboard_code = 0x90 elif key == Key.SCROLL_LOCK: keyboard_code = 0x91 try: key_state = hll_dll.GetKeyState(keyboard_code) & 1 except Exception: raise Exception('Unable to run Command.') if key_state == 1: return True return False elif OSHelper.is_linux() or OSHelper.is_mac(): try: cmd = subprocess.Popen('xset q', shell=True, stdout=subprocess.PIPE) shutdown_process('Xquartz') except subprocess.CalledProcessError as e: logger.error('Command failed: %s' % repr(e.cmd)) raise Exception('Unable to run Command.') else: processed_lock_key = key.value.label if 'caps' in processed_lock_key: processed_lock_key = 'Caps' elif 'num' in processed_lock_key: processed_lock_key = 'Num' elif 'scroll' in processed_lock_key: processed_lock_key = 'Scroll' for line in cmd.stdout: line = line.decode("utf-8") if processed_lock_key in line: values = re.findall('\d*\D+', ' '.join(line.split())) for val in values: if processed_lock_key in val and 'off' in val: return False return True
def shutdown_process(process_name: str): """Checks if the process name exists in the process list and close it .""" if OSHelper.is_windows(): command_str = 'taskkill /IM ' + process_name + '.exe' try: subprocess.Popen(command_str, shell=True, stdout=subprocess.PIPE) except subprocess.CalledProcessError: logger.error('Command failed: "%s"' % command_str) raise Exception('Unable to run Command.') elif OSHelper.is_mac() or OSHelper.is_linux(): command_str = 'pkill ' + process_name try: subprocess.Popen(command_str, shell=True, stdout=subprocess.PIPE) except subprocess.CalledProcessError: logger.error('Command failed: "%s"' % command_str) raise Exception('Unable to run Command.')
def restart_via_console(): """ restarts Firefox if web console is opened """ if OSHelper.is_mac(): type(text='r', modifier=[KeyModifier.CMD, KeyModifier.ALT]) else: type(text='r', modifier=[KeyModifier.CTRL, KeyModifier.ALT])
def select_location_bar(): """Set focus to the location bar.""" if OSHelper.is_mac(): type(text='l', modifier=KeyModifier.CMD) else: type(text='l', modifier=KeyModifier.CTRL) # Wait to allow the location bar to become responsive. time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
def select_folder_location_bar(): """Set focus to the location bar/open folder popup in previously opened file manager (e.g. "Open file", "Import bookmark") to navigate to path""" if OSHelper.is_mac(): type(text='g', modifier=[KeyModifier.SHIFT, KeyModifier.CMD]) else: type(text='l', modifier=KeyModifier.CTRL)