michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: this.EXPORTED_SYMBOLS = ["LanguageDetector"]; michael@0: michael@0: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); michael@0: michael@0: XPCOMUtils.defineLazyModuleGetter(this, "Promise", michael@0: "resource://gre/modules/Promise.jsm"); michael@0: michael@0: const WORKER_URL = "resource:///modules/translation/cld-worker.js"; michael@0: michael@0: let detectionQueue = []; michael@0: michael@0: let workerReady = false; michael@0: let pendingStrings = []; michael@0: michael@0: XPCOMUtils.defineLazyGetter(this, "worker", () => { michael@0: let worker = new Worker(WORKER_URL); michael@0: worker.onmessage = function(aMsg) { michael@0: if (aMsg.data == "ready") { michael@0: workerReady = true; michael@0: for (let string of pendingStrings) michael@0: worker.postMessage(string); michael@0: pendingStrings = []; michael@0: } michael@0: else michael@0: detectionQueue.shift().resolve(aMsg.data); michael@0: } michael@0: return worker; michael@0: }); michael@0: michael@0: this.LanguageDetector = { michael@0: /** michael@0: * Detect the language of a given string michael@0: * michael@0: * @returns {Promise} michael@0: * @resolves When detection is finished, with a object containing michael@0: * these fields: michael@0: * - 'language' (string with a language code) michael@0: * - 'confident' (boolean). michael@0: */ michael@0: detectLanguage: function(aString) { michael@0: let deferred = Promise.defer(); michael@0: detectionQueue.push(deferred); michael@0: if (worker && workerReady) michael@0: worker.postMessage(aString); michael@0: else michael@0: pendingStrings.push(aString); michael@0: return deferred.promise; michael@0: } michael@0: };