TODO: Common driver module =>  this is shared by both Watir and Selenium

 use win32screenshot library or Selenium to save curernt active window

 opts[:to_dir] => the direcotry to save image under
172615
def take_screenshot(to_file = nil, opts = {})
        # puts "calling new take screenshot: #{$screenshot_supported}"
        # unless $screenshot_supported
        #   puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" 
        #   return
        # end

        if to_file
          screenshot_image_filepath = to_file
        else
          screenshot_image_filename =  "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg"
          the_dump_dir = opts[:to_dir] || default_dump_dir
          FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir)
          screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename)
          screenshot_image_filepath.gsub!("/", "\\") if is_windows?

          FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath)
        end

          # save screenshot with selenium
          @web_browser.driver.save_screenshot(screenshot_image_filepath)
          notify_screenshot_location(screenshot_image_filepath)

      end
995125
@When("^I change active window$")
    public void seleniumChangeWindow() {
        String originalWindowHandle = commonspec.getDriver().getWindowHandle();
        Set<String> windowHandles = commonspec.getDriver().getWindowHandles();

        for (String window : windowHandles) {
            if (!window.equals(originalWindowHandle)) {
                commonspec.getDriver().switchTo().window(window);
            }
        }

    }
1164019
function createWorld() {

    var runtime = {
        driver: null,               // the browser object
        eyes: null,
        selenium: selenium,         // the raw nodejs selenium driver
        By: selenium.By,            // in keeping with Java expose selenium By
        by: selenium.By,            // provide a javascript lowercase version
        until: selenium.until,      // provide easy access to selenium until methods
        expect: expect,             // expose chai expect to allow variable testing
        assert: assert,             // expose chai assert to allow variable testing
        trace: consoleInfo,         // expose an info method to log output to the console in a readable/visible format
        page: global.page || {},    // empty page objects placeholder
        shared: global.shared || {} // empty shared objects placeholder
    };

    // expose properties to step definition methods via global variables
    Object.keys(runtime).forEach(function (key) {
        if (key === 'driver' && browserTeardownStrategy !== 'always') {
            return;
        }

        // make property/method available as a global (no this. prefix required)
        global[key] = runtime[key];
    });
}
731945
def add_assert_screenshot_methods(context_or_world, scenario):
    
    file_suffix = scenario.name

    def assert_screenshot(element_or_selector, filename, threshold=0, exclude_elements=[], driver_wrapper=None,
                          force=False):
        VisualTest(driver_wrapper, force).assert_screenshot(element_or_selector, filename, file_suffix, threshold,
                                                            exclude_elements)

    def assert_full_screenshot(filename, threshold=0, exclude_elements=[], driver_wrapper=None, force=False):
        VisualTest(driver_wrapper, force).assert_screenshot(None, filename, file_suffix, threshold, exclude_elements)

    # Monkey patching assert_screenshot method in PageElement to use the correct test name
    def assert_screenshot_page_element(self, filename, threshold=0, exclude_elements=[], force=False):
        VisualTest(self.driver_wrapper, force).assert_screenshot(self.web_element, filename, file_suffix, threshold,
                                                                 exclude_elements)

    context_or_world.assert_screenshot = assert_screenshot
    context_or_world.assert_full_screenshot = assert_full_screenshot
    PageElement.assert_screenshot = assert_screenshot_page_element
229737
function() {
    // Walk all of the elements in the DOM (try to only do this once)
    var elements = doc.getElementsByTagName('*');
    var re = /url\((http.*)\)/ig;
    for (var i = 0; i < elements.length; i++) {
      var el = elements[i];
      var style = win.getComputedStyle(el);

      // check for Images
      if (el.tagName == 'IMG') {
        CheckElement(el, el.src);
      }
      // Check for background images
      if (style['background-image']) {
        re.lastIndex = 0;
        var matches = re.exec(style['background-image']);
        if (matches && matches.length > 1)
          CheckElement(el, matches[1]);
      }
      // recursively walk any iFrames
      if (el.tagName == 'IFRAME') {
        try {
          var rect = GetElementViewportRect(el);
          if (rect) {
            var tm = RUMSpeedIndex(el.contentWindow);
            if (tm) {
              rects.push({'tm': tm,
                          'area': rect.area,
                          'rect': rect});
            }
        }
        } catch(e) {
        }
      }
    }
  }
9401
def __set_last_page_screenshot(self):
        
        if not self.__last_page_screenshot and (
                not self.__last_page_screenshot_png):
            try:
                element = self.driver.find_element_by_tag_name('body')
                if self.is_pytest and self.report_on:
                    self.__last_page_screenshot_png = (
                        self.driver.get_screenshot_as_png())
                    self.__last_page_screenshot = element.screenshot_as_base64
                else:
                    self.__last_page_screenshot_png = element.screenshot_as_png
            except Exception:
                if not self.__last_page_screenshot:
                    if self.is_pytest and self.report_on:
                        try:
                            self.__last_page_screenshot = (
                                self.driver.get_screenshot_as_base64())
                        except Exception:
                            pass
                if not self.__last_page_screenshot_png:
                    try:
                        self.__last_page_screenshot_png = (
                            self.driver.get_screenshot_as_png())
                    except Exception:
                        pass
1099214
def windows(self):
        
        from foxpuppet.windows import BrowserWindow

        return [
            BrowserWindow(self.selenium, handle)
            for handle in self.selenium.window_handles
        ]
854828
private void saveScreenshotTo(final File file) throws IOException {
		byte[] bytes = null;
		try {
			bytes = ((TakesScreenshot) driver)
					.getScreenshotAs(OutputType.BYTES);
		} catch (ClassCastException e) {
			WebDriver augmentedDriver = new Augmenter().augment(driver);
			bytes = ((TakesScreenshot) augmentedDriver)
					.getScreenshotAs(OutputType.BYTES);
		}

		Files.write(bytes, file);
	}
471712
def save_selected_state_as():
    

    state_machine_manager_model = rafcon.gui.singleton.state_machine_manager_model
    selection = state_machine_manager_model.get_selected_state_machine_model().selection
    selected_state = selection.get_selected_state()
    state_machine_id = state_machine_manager_model.get_selected_state_machine_model().state_machine.state_machine_id
    if len(selection.states) == 1:
        state_m = copy.copy(selected_state)
        sm_m = StateMachineModel(StateMachine(root_state=state_m.state))
        sm_m.root_state = state_m
        path = interface.create_folder_func("Please choose a root folder and a folder name for the state-machine your "
                                            "state is saved in. The default folder name is the name of state.",
                                            format_default_folder_name(selected_state.state.name))
        if path:
            storage.save_state_machine_to_path(sm_m.state_machine, base_path=path)
            sm_m.store_meta_data()
        else:
            logger.warning("No valid path specified")
            return False

        def open_as_state_machine_saved_state_as_separate_state_machine():
            logger.debug("Open state machine.")
            try:
                open_state_machine(path=path, recent_opened_notification=True)
            except (ValueError, IOError) as e:
                logger.error('Error while trying to open state machine: {0}'.format(e))

        # check if state machine is in library path
        root_window = rafcon.gui.singleton.main_window_controller.get_root_window()
        if library_manager.is_os_path_within_library_root_paths(path):

            _library_path, _library_name = \
                library_manager.get_library_path_and_name_for_os_path(sm_m.state_machine.file_system_path)
            overwrote_old_lib = library_manager.is_library_in_libraries(_library_path, _library_name)

            message_string = "You stored your state machine in a path that is within the library root paths. " \
                             "Thereby your state machine can be used as a library state.\n\n"\
                             "Do you want to:"

            table_header = ["Option", "Description"]
            table_data = [(True, "Substitute the original state by this new library state."),
                          (True, "Open the newly created library state machine.")]
            if overwrote_old_lib:
                table_data.append((False, "Refresh all open state machines, as an already existing library was "
                                          "overwritten."))

            dialog = RAFCONCheckBoxTableDialog(message_string,
                                               button_texts=("Apply", "Cancel"),
                                               table_header=table_header, table_data=table_data,
                                               message_type=Gtk.MessageType.QUESTION,
                                               parent=root_window,
                                               width=800, standalone=False)
            response_id = dialog.run()
            if response_id == 1:  # Apply pressed

                if overwrote_old_lib and dialog.list_store[2][0]:  # refresh all open state machine selected
                    logger.debug("Refresh all is triggered.")
                    refresh_all()
                else:  # if not all was refreshed at least the libraries are refreshed
                    logger.debug("Library refresh is triggered.")
                    refresh_libraries()

                if dialog.list_store[0][0]:  # Substitute saved state with Library selected
                    logger.debug("Substitute saved state with Library.")
                    if dialog.list_store[0][0] or dialog.list_store[0][1]:
                        refresh_libraries()
                    state_machine_manager_model.selected_state_machine_id = state_machine_id
                    [library_path, library_name] = library_manager.get_library_path_and_name_for_os_path(path)
                    state = library_manager.get_library_instance(library_path, library_name)
                    try:
                        substitute_selected_state(state, as_template=False)
                    except ValueError as e:
                        logger.error('Error while trying to open state machine: {0}'.format(e))
                if dialog.list_store[1][0]:  # Open as state machine saved state as separate state machine selected
                    open_as_state_machine_saved_state_as_separate_state_machine()
            elif response_id in [2, -4]:  # Cancel or Close pressed
                pass
            else:
                raise ValueError("Response id: {} is not considered".format(response_id))
            dialog.destroy()
        else:
            # Offer to open saved state machine dialog
            message_string = "Should the newly created state machine be opened?"
            dialog = RAFCONButtonDialog(message_string, ["Open", "Do not open"],
                                        message_type=Gtk.MessageType.QUESTION,
                                        parent=root_window)
            response_id = dialog.run()
            if response_id == 1:  # Apply pressed
                open_as_state_machine_saved_state_as_separate_state_machine()
            elif response_id in [2, -4]:  # Cancel or Close pressed
                pass
            else:
                raise ValueError("Response id: {} is not considered".format(response_id))
            dialog.destroy()

        return True
    else:
        logger.warning("Multiple states can not be saved as state machine directly. Group them before.")
        return False
174494
function captureScreenshot (chromy, filePath_, selector, selectorMap, config, selectors) {
  return new Promise(function (resolve, reject) {
    // VIEWPORT screenshot
    if (selector === VIEWPORT_SELECTOR || selector === BODY_SELECTOR) {
      chromy
        .screenshot()
        .result(buffer => {
          return saveViewport(buffer, selector);
        });
    // DOCUMENT screenshot
    } else if (selector === NOCLIP_SELECTOR || selector === DOCUMENT_SELECTOR) {
      chromy.screenshotMultipleSelectors(['body'], saveSelector);
    // OTHER-SELECTOR screenshot
    } else {
      chromy.screenshotMultipleSelectors(selectors, saveSelector);
    }

    chromy
      .end()
      .then(_ => {
        resolve();
      })
      .catch(e => {
        reject(e);
      });

    // result helpers

    // saveViewport: selectors will be `body` or `viewport` ONLY
    function saveViewport (buffer, selector) {
      const filePath = selectorMap[selector].filePath;

      ensureDirectoryPath(filePath);
      return fs.writeFile(filePath, buffer);
    }

    // saveSelector: selectorArr will contain any valid selector (not body or viewport).
    // If body *is* found in selector arr then it was originally DOCUMENT_SELECTOR -- and it will be reset back to DOCUMENT_SELECTOR -- this is because chromy takes a Document shot when BODY is used.
    function saveSelector (err, buffer, index, selectorArr) {
      let selector = selectorArr[index];
      if (selector === BODY_SELECTOR) {
        selector = DOCUMENT_SELECTOR;
      }
      const selectorProps = selectorMap[selector];
      const filePath = selectorProps.filePath;
      if (!selectorProps.exists) {
        return fs.copy(config.env.backstop + SELECTOR_NOT_FOUND_PATH, filePath);
      } else if (!selectorProps.isVisible) {
        return fs.copy(config.env.backstop + HIDDEN_SELECTOR_PATH, filePath);
      } else {
        if (err) {
          console.log('ChromyJS returned an unexpected error while attempting to capture a selector.', err);
          return new Error(err);
        }
        ensureDirectoryPath(filePath);
        return fs.writeFile(filePath, buffer);
      }
    }
  });
}
1225878
function simulateScreenshot(driver, w, h, browserName) {
  var scrollPos;
  var isRetina;
  var rawImageString;

  return browser
    .executeScript(driver, hideScrollbarScript + infoScript)
    .then(function(info) {
      scrollPos = info.slice(0, 4);
      isRetina = info[4];
      return browser.takeScreenshot(driver);
    })
    .then(function(res) {
      rawImageString = res;
      return browser.executeScript(driver, showScrollbarScript);
    })
    .then(function() {
      var left = Math.min(scrollPos[0], scrollPos[2] - w);
      var top = Math.min(scrollPos[1], scrollPos[3] - h);

      var config = {
        left: left < 0 ? 0 : left,
        top: top < 0 ? 0 : top,
        width: w,
        height: h,
      };

      if (browserName === 'chrome') {
        // chrome already takes partial ss. Browser size is adjusted correctly
        // except for width. If it's retina then instead of cropping w, we need
        // to crop w * 2. FF still takes the right dimensions regardless of
        // retina-ness so nothing to adjust here.
        config = {
          left: 0,
          top: 0,
          width: isRetina ? w * 2 : w,
          height: 99999,
        };
      }
      var buf = new Buffer(rawImageString, 'base64');

      return cropP(buf, config);
    });
}
1307014
public static BufferedImage takeScreenShotAsImage(WebElement iframe, WebElement element) {
    return screenshots.takeScreenshotAsImage(driver(), iframe, element);
  }
467150
def save_element_as_image_file(self, selector, file_name, folder=None):
        
        element = self.find_element(selector)
        element_png = element.screenshot_as_png
        if len(file_name.split('.')[0]) < 1:
            raise Exception("Error: file_name length must be > 0.")
        if not file_name.endswith(".png"):
            file_name = file_name + ".png"
        image_file_path = None
        if folder:
            if folder.endswith("/"):
                folder = folder[:-1]
            if len(folder) > 0:
                self.create_folder(folder)
                image_file_path = "%s/%s" % (folder, file_name)
        if not image_file_path:
            image_file_path = file_name
        with open(image_file_path, "wb") as file:
            file.write(element_png)
1221966
def hover_element_and_click(driver, element, click_selector,
                            click_by=By.CSS_SELECTOR,
                            timeout=settings.SMALL_TIMEOUT):
    
    start_ms = time.time() * 1000.0
    stop_ms = start_ms + (timeout * 1000.0)
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    for x in range(int(timeout * 10)):
        try:
            element = driver.find_element(by=click_by, value=click_selector)
            element.click()
            return element
        except Exception:
            now_ms = time.time() * 1000.0
            if now_ms >= stop_ms:
                break
            time.sleep(0.1)
    raise NoSuchElementException(
        "Element {%s} was not present after %s seconds!" %
        (click_selector, timeout))
1266067
def capture_screenshots(cls, name):
        
        screenshot_name = '{}_driver{}' if len(cls.driver_wrappers) > 1 else '{}'
        driver_index = 1
        for driver_wrapper in cls.driver_wrappers:
            if not driver_wrapper.driver:
                continue
            from toolium.jira import add_attachment
            try:
                add_attachment(driver_wrapper.utils.capture_screenshot(screenshot_name.format(name, driver_index)))
            except Exception:
                # Capture exceptions to avoid errors in teardown method due to session timeouts
                pass
            driver_index += 1
996088
def open_window(self, private=False):
        
        handles_before = self.selenium.window_handles
        self.switch_to()

        with self.selenium.context(self.selenium.CONTEXT_CHROME):
            # Opens private or non-private window
            self.selenium.find_element(*self._file_menu_button_locator).click()
            if private:
                self.selenium.find_element(
                    *self._file_menu_private_window_locator
                ).click()
            else:
                self.selenium.find_element(
                    *self._file_menu_new_window_button_locator
                ).click()

        return self.wait.until(
            expected.new_browser_window_is_opened(self.selenium, handles_before),
            message="No new browser window opened",
        )
364354
def save_current_page(options = {})
        default_options = {:replacement => true}
        options = default_options.merge(options)
        to_dir = options[:dir] || default_dump_dir

        if options[:filename]
          file_name = options[:filename]
        else
          file_name = Time.now.strftime("%m%d%H%M%S") + ".html"
        end

        Dir.mkdir(to_dir) unless File.exists?(to_dir)
        file = File.join(to_dir, file_name)

        content = page_source
        base_url = @web_browser.context.base_url
        current_url = @web_browser.url
        current_url =~ /(.*\/).*$/
        current_url_parent = $1
        if options[:replacement] && base_url =~ /^http:/
          File.new(file, "w").puts absolutize_page_hpricot(content, base_url, current_url_parent)
        else
          File.new(file, "w").puts content
        end

      end