<commit_before>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2007 ThoughtWorks, Inc

 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.
 */


function FirefoxDriver(server, enableNativeEvents, win) {
  this.server = server;
  this.enableNativeEvents = enableNativeEvents;
  this.window = win;

  this.currentX = 0;
  this.currentY = 0;

  // We do this here to work around an issue in the import function:
  // https://groups.google.com/group/mozilla.dev.apps.firefox/browse_thread/thread/e178d41afa2ccc87?hl=en&pli=1#
  var resources = [
    "atoms.js",
    "timer.js",
    "utils.js"
  ];

  for (var i = 0; i < resources.length; i++) {
    var name = 'resource://fxdriver/modules/' + resources[i];
    try {
      Components.utils.import(name);
    } catch (e) {
      dump(e);
    }
  }

  FirefoxDriver.listenerScript = Utils.loadUrl("resource://fxdriver/evaluate.js");

  this.jsTimer = new Timer();

}


/**
 * Enumeration of supported speed values.
 * @enum {number}
 */
FirefoxDriver.Speed = {
  SLOW: 1,
  MEDIUM: 10,
  FAST: 100
};


FirefoxDriver.prototype.__defineGetter__("id", function() {
  if (!this.id_) {
    this.id_ = this.server.getNextId();
  }

  return this.id_;
});


FirefoxDriver.prototype.getCurrentWindowHandle = function(respond) {
  respond.value = this.id;
  respond.send();
};


FirefoxDriver.prototype.get = function(respond, parameters) {
  var url = parameters.url;
  // Check to see if the given url is the same as the current one, but
  // with a different anchor tag.
  var current = respond.session.getWindow().location;
  var ioService =
      Utils.getService("@mozilla.org/network/io-service;1", "nsIIOService");
  var currentUri = ioService.newURI(current, "", null);
  var futureUri = ioService.newURI(url, "", currentUri);

  var loadEventExpected = true;

  if (currentUri && futureUri &&
      currentUri.prePath == futureUri.prePath &&
      currentUri.filePath == futureUri.filePath) {
    // Looks like we're at the same url with a ref
    // Being clever and checking the ref was causing me headaches.
    // Brute force for now
    loadEventExpected = futureUri.path.indexOf("#") == -1;
  }

  if (loadEventExpected) {
    new WebLoadingListener(respond.session.getBrowser(), function() {
      // TODO: Rescue the URI and response code from the event
      var responseText = "";
      // Focus on the top window.
      respond.session.setWindow(respond.session.getBrowser().contentWindow);
      respond.value = responseText;
      respond.send();
    });
  }

  respond.session.getBrowser().loadURI(url);

  if (!loadEventExpected) {
    Logger.dumpn("No load event expected");
    respond.send();
  }
};


FirefoxDriver.prototype.close = function(respond) {
  // Grab all the references we'll need. Once we call close all this might go away
  var wm = Utils.getService(
      "@mozilla.org/appshell/window-mediator;1", "nsIWindowMediator");
  var appService = Utils.getService(
      "@mozilla.org/toolkit/app-startup;1", "nsIAppStartup");
  var forceQuit = Components.interfaces.nsIAppStartup.eForceQuit;

  // Here we go!
  try {
    var browser = respond.session.getBrowser();
    createSwitchFile("close:" + browser.id);
    browser.contentWindow.close();
  } catch(e) {
    Logger.dump(e);
  }

  // Send the response so the client doesn't get a connection refused socket
  // error.
  respond.send();

  // If we're on a Mac we might have closed all the windows but not quit, so
  // ensure that we do actually quit :)
  var allWindows = wm.getEnumerator("navigator:browser");
  if (!allWindows.hasMoreElements()) {
    appService.quit(forceQuit);
    return;  // The client should catch the fact that the socket suddenly closes
  }
};


FirefoxDriver.prototype.executeScript = function(respond, parameters) {
  var doc = respond.session.getDocument();

  var rawScript = parameters['script'];
  var converted = Utils.unwrapParameters(parameters['args'], doc);
  var me = this;

  if (doc.designMode && "on" == doc.designMode.toLowerCase()) {
    // See https://developer.mozilla.org/en/rich-text_editing_in_mozilla#Internet_Explorer_Differences
    Logger.dumpn("Window in design mode, falling back to sandbox: " + doc.designMode);
    var window = respond.session.getWindow();
    window = window.wrappedJSObject;
    var sandbox = new Components.utils.Sandbox(window);
    sandbox.window = window;
    sandbox.__webdriverParams = converted;

    try {
      var scriptSrc = "with(window) { var __webdriverFunc = function(){" + parameters.script +
          "};  __webdriverFunc.apply(null, __webdriverParams); }";
      var res = Components.utils.evalInSandbox(scriptSrc, sandbox);
      respond.value = Utils.wrapResult(res, doc);
      respond.send();
      return;
    } catch (e) {
      Logger.dumpn(JSON.stringify(e));
      throw new WebDriverError(ErrorCode.UNEXPECTED_JAVASCRIPT_ERROR, e);
    }
  }

  var docBodyLoadTimeOut = function() {
    respond.sendError(new WebDriverError(ErrorCode.UNEXPECTED_JAVASCRIPT_ERROR,
        "waiting for doc.body failed"));
  };

  var scriptLoadTimeOut = function() {
    respond.sendError(new WebDriverError(ErrorCode.UNEXPECTED_JAVASCRIPT_ERROR,
        "waiting for evaluate.js load failed"));
  };

  var checkScriptLoaded = function() {
    return !!doc.getUserData('webdriver-evaluate-attached');
  };<commit_msg>SimonStewart: Adding some missing properties when executing javascript via the components sandbox' mechanism<commit_after>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2007 ThoughtWorks, Inc

 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.
 */


function FirefoxDriver(server, enableNativeEvents, win) {
  this.server = server;
  this.enableNativeEvents = enableNativeEvents;
  this.window = win;

  this.currentX = 0;
  this.currentY = 0;

  // We do this here to work around an issue in the import function:
  // https://groups.google.com/group/mozilla.dev.apps.firefox/browse_thread/thread/e178d41afa2ccc87?hl=en&pli=1#
  var resources = [
    "atoms.js",
    "timer.js",
    "utils.js"
  ];

  for (var i = 0; i < resources.length; i++) {
    var name = 'resource://fxdriver/modules/' + resources[i];
    try {
      Components.utils.import(name);
    } catch (e) {
      dump(e);
    }
  }

  FirefoxDriver.listenerScript = Utils.loadUrl("resource://fxdriver/evaluate.js");

  this.jsTimer = new Timer();

}


/**
 * Enumeration of supported speed values.
 * @enum {number}
 */
FirefoxDriver.Speed = {
  SLOW: 1,
  MEDIUM: 10,
  FAST: 100
};


FirefoxDriver.prototype.__defineGetter__("id", function() {
  if (!this.id_) {
    this.id_ = this.server.getNextId();
  }

  return this.id_;
});


FirefoxDriver.prototype.getCurrentWindowHandle = function(respond) {
  respond.value = this.id;
  respond.send();
};


FirefoxDriver.prototype.get = function(respond, parameters) {
  var url = parameters.url;
  // Check to see if the given url is the same as the current one, but
  // with a different anchor tag.
  var current = respond.session.getWindow().location;
  var ioService =
      Utils.getService("@mozilla.org/network/io-service;1", "nsIIOService");
  var currentUri = ioService.newURI(current, "", null);
  var futureUri = ioService.newURI(url, "", currentUri);

  var loadEventExpected = true;

  if (currentUri && futureUri &&
      currentUri.prePath == futureUri.prePath &&
      currentUri.filePath == futureUri.filePath) {
    // Looks like we're at the same url with a ref
    // Being clever and checking the ref was causing me headaches.
    // Brute force for now
    loadEventExpected = futureUri.path.indexOf("#") == -1;
  }

  if (loadEventExpected) {
    new WebLoadingListener(respond.session.getBrowser(), function() {
      // TODO: Rescue the URI and response code from the event
      var responseText = "";
      // Focus on the top window.
      respond.session.setWindow(respond.session.getBrowser().contentWindow);
      respond.value = responseText;
      respond.send();
    });
  }

  respond.session.getBrowser().loadURI(url);

  if (!loadEventExpected) {
    Logger.dumpn("No load event expected");
    respond.send();
  }
};


FirefoxDriver.prototype.close = function(respond) {
  // Grab all the references we'll need. Once we call close all this might go away
  var wm = Utils.getService(
      "@mozilla.org/appshell/window-mediator;1", "nsIWindowMediator");
  var appService = Utils.getService(
      "@mozilla.org/toolkit/app-startup;1", "nsIAppStartup");
  var forceQuit = Components.interfaces.nsIAppStartup.eForceQuit;

  // Here we go!
  try {
    var browser = respond.session.getBrowser();
    createSwitchFile("close:" + browser.id);
    browser.contentWindow.close();
  } catch(e) {
    Logger.dump(e);
  }

  // Send the response so the client doesn't get a connection refused socket
  // error.
  respond.send();

  // If we're on a Mac we might have closed all the windows but not quit, so
  // ensure that we do actually quit :)
  var allWindows = wm.getEnumerator("navigator:browser");
  if (!allWindows.hasMoreElements()) {
    appService.quit(forceQuit);
    return;  // The client should catch the fact that the socket suddenly closes
  }
};


FirefoxDriver.prototype.executeScript = function(respond, parameters) {
  var doc = respond.session.getDocument();

  var rawScript = parameters['script'];
  var converted = Utils.unwrapParameters(parameters['args'], doc);
  var me = this;

  if (doc.designMode && "on" == doc.designMode.toLowerCase()) {
    // See https://developer.mozilla.org/en/rich-text_editing_in_mozilla#Internet_Explorer_Differences
    Logger.dumpn("Window in design mode, falling back to sandbox: " + doc.designMode);
    var window = respond.session.getWindow();
    window = window.wrappedJSObject;
    var sandbox = new Components.utils.Sandbox(window);
    sandbox.window = window;
    sandbox.document = doc.wrappedJSObject ? doc.wrappedJSObject : doc;
    sandbox.navigator = window.navigator;
    sandbox.__webdriverParams = converted;

    try {
      var scriptSrc = "with(window) { var __webdriverFunc = function(){" + parameters.script +
          "};  __webdriverFunc.apply(null, __webdriverParams); }";
      var res = Components.utils.evalInSandbox(scriptSrc, sandbox);
      respond.value = Utils.wrapResult(res, doc);
      respond.send();
      return;
    } catch (e) {
      Logger.dumpn(JSON.stringify(e));
      throw new WebDriverError(ErrorCode.UNEXPECTED_JAVASCRIPT_ERROR, e);
    }
  }

  var docBodyLoadTimeOut = function() {
    respond.sendError(new WebDriverError(ErrorCode.UNEXPECTED_JAVASCRIPT_ERROR,
        "waiting for doc.body failed"));
  };

  var scriptLoadTimeOut = function() {
    respond.sendError(new WebDriverError(ErrorCode.UNEXPECTED_JAVASCRIPT_ERROR,
        "waiting for evaluate.js load failed"));
  };

  var checkScriptLoaded = function() {
    return !!doc.getUserData('webdriver-evaluate-attached');
  };
{'fraction_non_alphanumeric': 0.1182039038284326, 'fraction_numerical': 0.007707129094412331, 'mean_word_length': 3.5564885496183205, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4434442', 'n_tokens_mistral': 3735, 'n_tokens_neox': 3555, 'n_words': 968}