worker_client.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Distributed under the BSD license:
  3. *
  4. * Copyright (c) 2010, Ajax.org B.V.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Ajax.org B.V. nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * ***** END LICENSE BLOCK ***** */
  30. define(function(require, exports, module) {
  31. "use strict";
  32. var oop = require("../lib/oop");
  33. var EventEmitter = require("../lib/event_emitter").EventEmitter;
  34. var config = require("../config");
  35. var WorkerClient = function(topLevelNamespaces, mod, classname) {
  36. this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
  37. this.changeListener = this.changeListener.bind(this);
  38. this.onMessage = this.onMessage.bind(this);
  39. // nameToUrl is renamed to toUrl in requirejs 2
  40. if (require.nameToUrl && !require.toUrl)
  41. require.toUrl = require.nameToUrl;
  42. var workerUrl;
  43. if (config.get("packaged") || !require.toUrl) {
  44. workerUrl = config.moduleUrl(mod, "worker");
  45. } else {
  46. var normalizePath = this.$normalizePath;
  47. workerUrl = normalizePath(require.toUrl("ace/worker/worker.js", null, "_"));
  48. var tlns = {};
  49. topLevelNamespaces.forEach(function(ns) {
  50. tlns[ns] = normalizePath(require.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, ""));
  51. });
  52. }
  53. this.$worker = new Worker(workerUrl);
  54. this.$worker.postMessage({
  55. init : true,
  56. tlns: tlns,
  57. module: mod,
  58. classname: classname
  59. });
  60. this.callbackId = 1;
  61. this.callbacks = {};
  62. this.$worker.onmessage = this.onMessage;
  63. };
  64. (function(){
  65. oop.implement(this, EventEmitter);
  66. this.onMessage = function(e) {
  67. var msg = e.data;
  68. switch(msg.type) {
  69. case "log":
  70. window.console && console.log && console.log.apply(console, msg.data);
  71. break;
  72. case "event":
  73. this._emit(msg.name, {data: msg.data});
  74. break;
  75. case "call":
  76. var callback = this.callbacks[msg.id];
  77. if (callback) {
  78. callback(msg.data);
  79. delete this.callbacks[msg.id];
  80. }
  81. break;
  82. }
  83. };
  84. this.$normalizePath = function(path) {
  85. if (!location.host) // needed for file:// protocol
  86. return path;
  87. path = path.replace(/^[a-z]+:\/\/[^\/]+/, ""); // Remove domain name and rebuild it
  88. path = location.protocol + "//" + location.host
  89. // paths starting with a slash are relative to the root (host)
  90. + (path.charAt(0) == "/" ? "" : location.pathname.replace(/\/[^\/]*$/, ""))
  91. + "/" + path.replace(/^[\/]+/, "");
  92. return path;
  93. };
  94. this.terminate = function() {
  95. this._emit("terminate", {});
  96. this.deltaQueue = null;
  97. this.$worker.terminate();
  98. this.$worker = null;
  99. this.$doc.removeEventListener("change", this.changeListener);
  100. this.$doc = null;
  101. };
  102. this.send = function(cmd, args) {
  103. this.$worker.postMessage({command: cmd, args: args});
  104. };
  105. this.call = function(cmd, args, callback) {
  106. if (callback) {
  107. var id = this.callbackId++;
  108. this.callbacks[id] = callback;
  109. args.push(id);
  110. }
  111. this.send(cmd, args);
  112. };
  113. this.emit = function(event, data) {
  114. try {
  115. // firefox refuses to clone objects which have function properties
  116. // TODO: cleanup event
  117. this.$worker.postMessage({event: event, data: {data: data.data}});
  118. }
  119. catch(ex) {}
  120. };
  121. this.attachToDocument = function(doc) {
  122. if(this.$doc)
  123. this.terminate();
  124. this.$doc = doc;
  125. this.call("setValue", [doc.getValue()]);
  126. doc.on("change", this.changeListener);
  127. };
  128. this.changeListener = function(e) {
  129. if (!this.deltaQueue) {
  130. this.deltaQueue = [e.data];
  131. setTimeout(this.$sendDeltaQueue, 0);
  132. } else
  133. this.deltaQueue.push(e.data);
  134. };
  135. this.$sendDeltaQueue = function() {
  136. var q = this.deltaQueue;
  137. if (!q) return;
  138. this.deltaQueue = null;
  139. if (q.length > 20 && q.length > this.$doc.getLength() >> 1) {
  140. this.call("setValue", [this.$doc.getValue()]);
  141. } else
  142. this.emit("change", {data: q});
  143. }
  144. }).call(WorkerClient.prototype);
  145. var UIWorkerClient = function(topLevelNamespaces, mod, classname) {
  146. this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
  147. this.changeListener = this.changeListener.bind(this);
  148. this.callbackId = 1;
  149. this.callbacks = {};
  150. this.messageBuffer = [];
  151. var main = null;
  152. var sender = Object.create(EventEmitter);
  153. var _self = this;
  154. this.$worker = {};
  155. this.$worker.terminate = function() {};
  156. this.$worker.postMessage = function(e) {
  157. _self.messageBuffer.push(e);
  158. main && setTimeout(processNext);
  159. };
  160. var processNext = function() {
  161. var msg = _self.messageBuffer.shift();
  162. if (msg.command)
  163. main[msg.command].apply(main, msg.args);
  164. else if (msg.event)
  165. sender._emit(msg.event, msg.data);
  166. };
  167. sender.postMessage = function(msg) {
  168. _self.onMessage({data: msg});
  169. };
  170. sender.callback = function(data, callbackId) {
  171. this.postMessage({type: "call", id: callbackId, data: data});
  172. };
  173. sender.emit = function(name, data) {
  174. this.postMessage({type: "event", name: name, data: data});
  175. };
  176. config.loadModule(["worker", mod], function(Main) {
  177. main = new Main[classname](sender);
  178. while (_self.messageBuffer.length)
  179. processNext();
  180. });
  181. };
  182. UIWorkerClient.prototype = WorkerClient.prototype;
  183. exports.UIWorkerClient = UIWorkerClient;
  184. exports.WorkerClient = WorkerClient;
  185. });