<commit_before>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2011 Software Freedom Conservancy

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */


goog.provide('WebElement');

goog.require('Utils');
goog.require('WebLoadingListener');
goog.require('bot.ErrorCode');
goog.require('bot.action');
goog.require('bot.dom');
goog.require('fxdriver.Logger');
goog.require('fxdriver.moz');
goog.require('fxdriver.preconditions');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.selection');
goog.require('webdriver.atoms.element');


WebElement.elementEquals = function(respond, parameters) {
  try {
    var elementA = Utils.getElementAt(parameters.id,
                                      respond.session.getDocument());
    var elementB = Utils.getElementAt(parameters.other,
                                      respond.session.getDocument());
    respond.value = elementA == elementB;
  } catch (e) {
    if (e.code && e.code == bot.ErrorCode.STALE_ELEMENT_REFERENCE) {
      // Assume any style elements are not equal to any others.
      // Users shouldn't care about equality of stale elements.
      respond.value = false;
    } else {
      throw e;
    }
  }
  respond.send();
};

WebElement.clickElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var unwrapped = fxdriver.moz.unwrapFor4(element);
  var nativeMouse = Utils.getNativeMouse();
  var node = Utils.getNodeForNativeEvents(unwrapped);
  var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].
      getService(Components.interfaces.nsIXULAppInfo);
  var versionChecker = Components.
      classes["@mozilla.org/xpcom/version-comparator;1"].
      getService(Components.interfaces.nsIVersionComparator);

  // I'm having trouble getting clicks to work on Firefox 2 on Windows. Always
  // fall back for that
  var useNativeClick =
      versionChecker.compare(appInfo.platformVersion, "1.9") >= 0;
  var thmgr_cls = Components.classes["@mozilla.org/thread-manager;1"];

  // For now, we need to bypass native events for option elements
  var isOption = "option" == unwrapped.tagName.toLowerCase();

  var loc = Utils.getLocation(unwrapped, unwrapped.tagName == "A");
  var elementHalfWidth = (loc.width ? loc.width / 2 : 0);
  var elementHalfHeight = (loc.height ? loc.height / 2 : 0);

  if (!isOption && this.enableNativeEvents && nativeMouse && node && useNativeClick && thmgr_cls) {
    fxdriver.Logger.dumpn("Using native events for click");

    var inViewAfterScroll = bot.action.scrollIntoView(
        unwrapped,
        new goog.math.Coordinate(elementHalfWidth, elementHalfHeight));

    if (!inViewAfterScroll) {
        respond.sendError(
            new WebDriverError(bot.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS,
                'Element cannot be scrolled into view:' + element));
        return;
    }

    loc = Utils.getLocation(unwrapped, unwrapped.tagName == "A");
    var x = loc.x + elementHalfWidth;
    var y = loc.y + elementHalfHeight;

    // In Firefox 3.6 and above, there's a shared window handle. We need to calculate an offset
    // to add to the x and y locations.

    if (bot.userAgent.isProductVersion(3.6)) {
      // Get the ultimate parent frame
      var current = unwrapped.ownerDocument.defaultView;
      var ultimateParent = unwrapped.ownerDocument.defaultView.parent;
      while (ultimateParent != current) {
        current = ultimateParent;
        ultimateParent = current.parent;
      }

      var offX = unwrapped.ownerDocument.defaultView.mozInnerScreenX - ultimateParent.mozInnerScreenX;
      var offY = unwrapped.ownerDocument.defaultView.mozInnerScreenY - ultimateParent.mozInnerScreenY;

      x += offX;
      y += offY;
    }

    try {
      var currentPosition = respond.session.getMousePosition();
      Utils.translateByBrowserSpecificOffset(respond.session.getBrowser(), currentPosition);

      var destinationCoordinates = new goog.math.Coordinate(x, y);
      Utils.translateByBrowserSpecificOffset(respond.session.getBrowser(), destinationCoordinates);

      var adjustedX = destinationCoordinates.x;
      var adjustedY = destinationCoordinates.y;

      nativeMouse.mouseMove(node,
                             currentPosition.x,
                             currentPosition.y,
                             adjustedX,
                             adjustedY);

      var pageUnloadedIndicator = Utils.getPageUnloadedIndicator(unwrapped);

      nativeMouse.click(node, adjustedX, adjustedY, 1);

      respond.session.setMousePosition(x, y);

      Utils.waitForNativeEventsProcessing(unwrapped, Utils.getNativeEvents(),
          pageUnloadedIndicator, this.jsTimer);

      respond.send();

      return;
    } catch (e) {
      // Make sure that we only fall through only if
      // the error returned from the native call indicates it's not
      // implemented.

      fxdriver.Logger.dumpn("Detected error when clicking: " + e.name);

      if (e.name != "NS_ERROR_NOT_IMPLEMENTED") {
        throw new WebDriverError(bot.ErrorCode.INVALID_ELEMENT_STATE, e);
      }

      // Fall through to the synthesized click code.
    }
  }

  fxdriver.Logger.dumpn("Falling back to synthesized click");

  // TODO(simon): Delete the above and sink most of it into a "nativeMouse"
  Utils.installWindowCloseListener(respond);
  Utils.installClickListener(respond, WebLoadingListener);

  var res = this.mouse.move(element, elementHalfWidth, elementHalfHeight);
  if (res.status != bot.ErrorCode.SUCCESS) {
    respond.status = res.status;
    respond.value = res.message;
    respond.send();
    return;
  }

  res = this.mouse.click(element);
  respond.status = res.status;
  respond.value = res.message;
};
WebElement.clickElement.preconditions =
    [ fxdriver.preconditions.visible ];


WebElement.getElementText = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());
  respond.value = webdriver.atoms.element.getText(element);
  respond.send();
};


WebElement.sendKeysToElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var browser = respond.session.getBrowser();
  var dispatcher = browser.ownerDocument.commandDispatcher;
  var currentDocument =
      dispatcher.focusedElement && goog.dom.getOwnerDocument(dispatcher.focusedElement);
  currentDocument = currentDocument ? new XPCNativeWrapper(currentDocument) : null;

  var alreadyFocused = true;
  var currentlyActive = Utils.getActiveElement(respond.session.getDocument());
  var newDocument = goog.dom.getOwnerDocument(currentlyActive);

  if (currentlyActive != element || currentDocument != new XPCNativeWrapper(newDocument)) {
    fxdriver.Logger.dumpn("Need to switch focus");
    alreadyFocused = false;
    currentlyActive.blur();<commit_msg>DanielWagnerHall: Apparently this code wasn't quite as dead as I thought.  Which makes me really sad.<commit_after>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2011 Software Freedom Conservancy

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */


goog.provide('WebElement');

goog.require('Utils');
goog.require('WebLoadingListener');
goog.require('bot.ErrorCode');
goog.require('bot.action');
goog.require('bot.dom');
goog.require('fxdriver.Logger');
goog.require('fxdriver.moz');
goog.require('fxdriver.preconditions');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.selection');
goog.require('webdriver.atoms.element');


WebElement.elementEquals = function(respond, parameters) {
  try {
    var elementA = Utils.getElementAt(parameters.id,
                                      respond.session.getDocument());
    var elementB = Utils.getElementAt(parameters.other,
                                      respond.session.getDocument());
    respond.value = elementA == elementB;
  } catch (e) {
    if (e.code && e.code == bot.ErrorCode.STALE_ELEMENT_REFERENCE) {
      // Assume any style elements are not equal to any others.
      // Users shouldn't care about equality of stale elements.
      respond.value = false;
    } else {
      throw e;
    }
  }
  respond.send();
};

WebElement.clickElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var unwrapped = fxdriver.moz.unwrapFor4(element);
  var nativeMouse = Utils.getNativeMouse();
  var node = Utils.getNodeForNativeEvents(unwrapped);
  var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].
      getService(Components.interfaces.nsIXULAppInfo);
  var versionChecker = Components.
      classes["@mozilla.org/xpcom/version-comparator;1"].
      getService(Components.interfaces.nsIVersionComparator);

  // I'm having trouble getting clicks to work on Firefox 2 on Windows. Always
  // fall back for that
  var useNativeClick =
      versionChecker.compare(appInfo.platformVersion, "1.9") >= 0;
  var thmgr_cls = Components.classes["@mozilla.org/thread-manager;1"];

  // For now, we need to bypass native events for option elements
  var isOption = "option" == unwrapped.tagName.toLowerCase();

  var loc = Utils.getLocation(unwrapped, unwrapped.tagName == "A");
  var elementHalfWidth = (loc.width ? loc.width / 2 : 0);
  var elementHalfHeight = (loc.height ? loc.height / 2 : 0);

  if (!isOption && this.enableNativeEvents && nativeMouse && node && useNativeClick && thmgr_cls) {
    fxdriver.Logger.dumpn("Using native events for click");

    var inViewAfterScroll = bot.action.scrollIntoView(
        unwrapped,
        new goog.math.Coordinate(elementHalfWidth, elementHalfHeight));

    if (!inViewAfterScroll) {
        respond.sendError(
            new WebDriverError(bot.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS,
                'Element cannot be scrolled into view:' + element));
        return;
    }

    loc = Utils.getLocation(unwrapped, unwrapped.tagName == "A");
    var x = loc.x + elementHalfWidth;
    var y = loc.y + elementHalfHeight;

    // In Firefox 3.6 and above, there's a shared window handle. We need to calculate an offset
    // to add to the x and y locations.

    if (bot.userAgent.isProductVersion(3.6)) {
      // Get the ultimate parent frame
      var current = unwrapped.ownerDocument.defaultView;
      var ultimateParent = unwrapped.ownerDocument.defaultView.parent;
      while (ultimateParent != current) {
        current = ultimateParent;
        ultimateParent = current.parent;
      }

      var offX = unwrapped.ownerDocument.defaultView.mozInnerScreenX - ultimateParent.mozInnerScreenX;
      var offY = unwrapped.ownerDocument.defaultView.mozInnerScreenY - ultimateParent.mozInnerScreenY;

      x += offX;
      y += offY;
    }

    try {
      var currentPosition = respond.session.getMousePosition();
      Utils.translateByBrowserSpecificOffset(respond.session.getBrowser(), currentPosition);

      var destinationCoordinates = new goog.math.Coordinate(x, y);
      Utils.translateByBrowserSpecificOffset(respond.session.getBrowser(), destinationCoordinates);

      var adjustedX = destinationCoordinates.x;
      var adjustedY = destinationCoordinates.y;

      nativeMouse.mouseMove(node,
                             currentPosition.x,
                             currentPosition.y,
                             adjustedX,
                             adjustedY);

      var pageUnloadedIndicator = Utils.getPageUnloadedIndicator(unwrapped);

      nativeMouse.click(node, adjustedX, adjustedY, 1);

      respond.session.setMousePosition(x, y);

      Utils.waitForNativeEventsProcessing(unwrapped, Utils.getNativeEvents(),
          pageUnloadedIndicator, this.jsTimer);

      respond.send();

      return;
    } catch (e) {
      // Make sure that we only fall through only if
      // the error returned from the native call indicates it's not
      // implemented.

      fxdriver.Logger.dumpn("Detected error when clicking: " + e.name);

      if (e.name != "NS_ERROR_NOT_IMPLEMENTED") {
        throw new WebDriverError(bot.ErrorCode.INVALID_ELEMENT_STATE, e);
      }

      // Fall through to the synthesized click code.
    }
  }

  fxdriver.Logger.dumpn("Falling back to synthesized click");

  // TODO(simon): Delete the above and sink most of it into a "nativeMouse"
  Utils.installWindowCloseListener(respond);
  Utils.installClickListener(respond, WebLoadingListener);

  var res = this.mouse.move(element, elementHalfWidth, elementHalfHeight);
  if (res.status != bot.ErrorCode.SUCCESS) {
    respond.status = res.status;
    respond.value = res.message;
    respond.send();
    return;
  }

  res = this.mouse.click(element);
  respond.status = res.status;
  respond.value = res.message;
};
WebElement.clickElement.preconditions =
    [ fxdriver.preconditions.visible ];


WebElement.getElementText = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());
  if (bot.dom.isElement(element, goog.dom.TagName.TITLE)) {
    respond.value = respond.session.getBrowser().contentTitle;
  } else {
    respond.value = webdriver.atoms.element.getText(element);
  }
  respond.send();
};


WebElement.sendKeysToElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var browser = respond.session.getBrowser();
  var dispatcher = browser.ownerDocument.commandDispatcher;
  var currentDocument =
      dispatcher.focusedElement && goog.dom.getOwnerDocument(dispatcher.focusedElement);
  currentDocument = currentDocument ? new XPCNativeWrapper(currentDocument) : null;

  var alreadyFocused = true;
  var currentlyActive = Utils.getActiveElement(respond.session.getDocument());
  var newDocument = goog.dom.getOwnerDocument(currentlyActive);

  if (currentlyActive != element || currentDocument != new XPCNativeWrapper(newDocument)) {
    fxdriver.Logger.dumpn("Need to switch focus");
    alreadyFocused = false;
    currentlyActive.blur();
{'fraction_non_alphanumeric': 0.10411495754408884, 'fraction_numerical': 0.005355976485956891, 'mean_word_length': 3.258970792767733, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6951930', 'n_tokens_mistral': 4391, 'n_tokens_neox': 4164, 'n_words': 1040}