browser/components/translation/LanguageDetector.jsm
author Ryan VanderMeulen <ryanvm@gmail.com>
Thu, 25 Jun 2015 19:48:42 -0400
changeset 281060 1a326aaaba371e18e090f98ca1c4474bbdce2fca
parent 190677 f33b136050106e4dec3d27b6df3474b84ec4b4fd
child 295257 380817d573cdfbfc4a4b4a4647cf1a53bb52c3b9
permissions -rw-r--r--
Backed out changeset 8b4e4083639e (bug 1171931) for B2G debug emulator bustage.

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

this.EXPORTED_SYMBOLS = ["LanguageDetector"];

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, "Promise",
                                  "resource://gre/modules/Promise.jsm");

const WORKER_URL = "resource:///modules/translation/cld-worker.js";

let detectionQueue = [];

let workerReady = false;
let pendingStrings = [];

XPCOMUtils.defineLazyGetter(this, "worker", () => {
  let worker = new Worker(WORKER_URL);
  worker.onmessage = function(aMsg) {
    if (aMsg.data == "ready") {
      workerReady = true;
      for (let string of pendingStrings)
        worker.postMessage(string);
      pendingStrings = [];
    }
    else
      detectionQueue.shift().resolve(aMsg.data);
  }
  return worker;
});

this.LanguageDetector = {
  /**
   * Detect the language of a given string
   *
   * @returns {Promise}
   * @resolves When detection is finished, with a object containing
   * these fields:
   *  - 'language' (string with a language code)
   *  - 'confident' (boolean).
   */
  detectLanguage: function(aString) {
    let deferred = Promise.defer();
    detectionQueue.push(deferred);
    if (worker && workerReady)
      worker.postMessage(aString);
    else
      pendingStrings.push(aString);
    return deferred.promise;
  }
};