def minimize_window_control(window_type): """Click on minimize window control. :param window_type: Type of window that need to be minimized. :return: None. """ find_window_controls(window_type) if window_type == "auxiliary": if OSHelper.is_mac(): width, height = AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.get_size( ) click(AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.target_offset( width / 2, height / 2), align=Alignment.TOP_LEFT) else: click(AuxiliaryWindow.MINIMIZE_BUTTON) else: if OSHelper.is_mac(): width, height = MainWindow.MAIN_WINDOW_CONTROLS.get_size() click(MainWindow.MAIN_WINDOW_CONTROLS.target_offset( width / 2, height / 2), align=Alignment.TOP_LEFT) else: click(MainWindow.MINIMIZE_BUTTON)
def maximize_window_control(window_type): """Click on maximize window control. :param window_type: Type of window that need to be maximized. :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: click(AuxiliaryWindow.MAXIMIZE_BUTTON) if OSHelper.is_linux(): reset_mouse() 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: click(MainWindow.MAXIMIZE_BUTTON)
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 select_file_in_folder(directory, filename_pattern, file_option, max_num_of_attempts=3): """ Opens directory, selects file in opened directory, and provides action with it (e.g. copy, cut, delete), and closes opened directory. :param directory: Folder on hard drive to open. :param filename_pattern: File Pattern to select. :param file_option: File processing function. Appropriate methods are: edit_copy, edit_cut, edit_delete. :param max_num_of_attempts: Attempts to find pattern of file name. Default: 3 """ finder_list_view = '2' type_delay = 0.5 if not isinstance(directory, str): raise ValueError(INVALID_GENERIC_INPUT) if not isinstance(filename_pattern, Pattern): raise ValueError(INVALID_GENERIC_INPUT) if not callable(file_option): raise ValueError(INVALID_GENERIC_INPUT) open_directory(directory) try: for attempt in range(1, max_num_of_attempts + 1): file_located = exists(filename_pattern) if file_located: logger.debug('File {} in directory {} is available.'.format(filename_pattern, directory)) break else: if attempt == max_num_of_attempts: logger.debug('File {} is not available after {} attempt(s).'.format(filename_pattern, attempt)) raise Exception time.sleep(Settings.DEFAULT_UI_DELAY_LONG) if OSHelper.is_mac(): type(text=finder_list_view, modifier=KeyModifier.CMD, interval=type_delay) click(filename_pattern) file_option() except Exception: raise APIHelperError('Could not find file {} in folder {}.'.format(filename_pattern, directory)) finally: if OSHelper.is_windows(): type(text='w', modifier=KeyModifier.CTRL) elif OSHelper.is_linux(): type(text='q', modifier=KeyModifier.CTRL) elif OSHelper.is_mac(): type(text='w', modifier=[KeyModifier.CMD, KeyModifier.ALT])
def close_window(): """Close the currently focused window.""" if OSHelper.is_mac(): type(text="w", modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text="w", modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) time.sleep(Settings.DEFAULT_UI_DELAY)
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_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 paste(text: str): """ :param text: Text to be pasted. :return: None. """ pyperclip.copy(text) text_copied = False wait_scan_rate = float(Settings.wait_scan_rate) interval = 1 / wait_scan_rate max_attempts = int(Settings.auto_wait_timeout * wait_scan_rate) attempt = 0 while not text_copied and attempt < max_attempts: if pyperclip.paste() == text: text_copied = True else: time.sleep(interval) attempt += 1 if not text_copied: raise FindError("Paste method failed.") if OSHelper.is_mac(): type(text="v", modifier=KeyModifier.CMD) else: type(text="v", modifier=KeyModifier.CTRL) pyperclip.copy("")
def full_screen_control(window_type): """Click on full screen window mode (Applicable only for MAC system). :param window_type: Type of window that need to be maximized in full screen mode. :reurn: None. """ if OSHelper.is_mac(): find_window_controls(window_type) if window_type == "auxiliary": width, height = AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.get_size() click( AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.target_offset( width - 10, height / 2 ), align=Alignment.TOP_LEFT, ) else: width, height = MainWindow.MAIN_WINDOW_CONTROLS.get_size() click( MainWindow.MAIN_WINDOW_CONTROLS.target_offset(width - 10, height / 2), align=Alignment.TOP_LEFT, ) else: raise APIHelperError("Full screen mode applicable only for MAC")
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 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 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 history_sidebar(): """Toggle open/close the history sidebar.""" if OSHelper.is_mac(): type(text='h', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text='h', modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY)
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 close_tab(): """Close the currently focused tab (Except for app tabs).""" if OSHelper.is_mac(): type(text="w", modifier=KeyModifier.CMD) else: type(text="w", modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY)
def launch_control_center(): profile_path = os.path.join(PathManager.get_working_dir(), "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=get_fx_prefs()) 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() logger.debug("Launching web server for directory %s" % PathManager.get_working_dir()) server = LocalWebServer(PathManager.get_working_dir(), 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 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)
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 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 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_browser_console(): """ Opens the Browser Console. """ if OSHelper.is_mac(): type(text="j", modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text="j", modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def bookmark_all_tabs(): """Open the Bookmark All Tabs dialog.""" if OSHelper.is_mac(): type(text='d', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text='d', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) # Wait for the Bookmark All Tabs dialog to be opened. time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
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 find_previous(): """Find the previous occurrence of term, if find is already active on a search term. Find previous can also find the previous occurrence of a term without opening the find toolbar. """ if OSHelper.is_mac(): type(text='g', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text='g', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
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_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]) time.sleep(Settings.DEFAULT_UI_DELAY)
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 find_next(): """Find next occurrence of term, if find is already active on a search term. Find next (again) can also find the next occurrence of a term without opening the find toolbar. """ if OSHelper.is_mac(): type(text='g', modifier=KeyModifier.CMD) else: type(text='g', modifier=KeyModifier.CTRL)
def change_search_previous(): """If the search bar has focus, change the search engine to the previous in the list. (side effect: this also opens the search engine manager, if it wasn't already open). """ if OSHelper.is_mac(): type(text=Key.UP, modifier=KeyModifier.CMD) else: type(text=Key.UP, modifier=KeyModifier.CTRL)