qwebchannel.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2015 The Qt Company Ltd.
  4. ** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
  5. ** Contact: http://www.qt.io/licensing/
  6. **
  7. ** This file is part of the QtWebChannel module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL21$
  10. ** Commercial License Usage
  11. ** Licensees holding valid commercial Qt licenses may use this file in
  12. ** accordance with the commercial license agreement provided with the
  13. ** Software or, alternatively, in accordance with the terms contained in
  14. ** a written agreement between you and The Qt Company. For licensing terms
  15. ** and conditions see http://www.qt.io/terms-conditions. For further
  16. ** information use the contact form at http://www.qt.io/contact-us.
  17. **
  18. ** GNU Lesser General Public License Usage
  19. ** Alternatively, this file may be used under the terms of the GNU Lesser
  20. ** General Public License version 2.1 or version 3 as published by the Free
  21. ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
  22. ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
  23. ** following information to ensure the GNU Lesser General Public License
  24. ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
  25. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  26. **
  27. ** As a special exception, The Qt Company gives you certain additional
  28. ** rights. These rights are described in The Qt Company LGPL Exception
  29. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  30. **
  31. ** $QT_END_LICENSE$
  32. **
  33. ****************************************************************************/
  34. "use strict";
  35. var QWebChannelMessageTypes = {
  36. signal: 1,
  37. propertyUpdate: 2,
  38. init: 3,
  39. idle: 4,
  40. debug: 5,
  41. invokeMethod: 6,
  42. connectToSignal: 7,
  43. disconnectFromSignal: 8,
  44. setProperty: 9,
  45. response: 10,
  46. };
  47. var QWebChannel = function(transport, initCallback)
  48. {
  49. if (typeof transport !== "object" || typeof transport.send !== "function") {
  50. console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
  51. " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
  52. return;
  53. }
  54. var channel = this;
  55. this.transport = transport;
  56. this.send = function(data)
  57. {
  58. if (typeof(data) !== "string") {
  59. data = JSON.stringify(data);
  60. }
  61. channel.transport.send(data);
  62. }
  63. this.transport.onmessage = function(message)
  64. {
  65. var data = message.data;
  66. if (typeof data === "string") {
  67. data = JSON.parse(data);
  68. }
  69. switch (data.type) {
  70. case QWebChannelMessageTypes.signal:
  71. channel.handleSignal(data);
  72. break;
  73. case QWebChannelMessageTypes.response:
  74. channel.handleResponse(data);
  75. break;
  76. case QWebChannelMessageTypes.propertyUpdate:
  77. channel.handlePropertyUpdate(data);
  78. break;
  79. default:
  80. console.error("invalid message received:", message.data);
  81. break;
  82. }
  83. }
  84. this.execCallbacks = {};
  85. this.execId = 0;
  86. this.exec = function(data, callback)
  87. {
  88. if (!callback) {
  89. // if no callback is given, send directly
  90. channel.send(data);
  91. return;
  92. }
  93. if (channel.execId === Number.MAX_VALUE) {
  94. // wrap
  95. channel.execId = Number.MIN_VALUE;
  96. }
  97. if (data.hasOwnProperty("id")) {
  98. console.error("Cannot exec message with property id: " + JSON.stringify(data));
  99. return;
  100. }
  101. data.id = channel.execId++;
  102. channel.execCallbacks[data.id] = callback;
  103. channel.send(data);
  104. };
  105. this.objects = {};
  106. this.handleSignal = function(message)
  107. {
  108. var object = channel.objects[message.object];
  109. if (object) {
  110. object.signalEmitted(message.signal, message.args);
  111. } else {
  112. console.warn("Unhandled signal: " + message.object + "::" + message.signal);
  113. }
  114. }
  115. this.handleResponse = function(message)
  116. {
  117. if (!message.hasOwnProperty("id")) {
  118. console.error("Invalid response message received: ", JSON.stringify(message));
  119. return;
  120. }
  121. channel.execCallbacks[message.id](message.data);
  122. delete channel.execCallbacks[message.id];
  123. }
  124. this.handlePropertyUpdate = function(message)
  125. {
  126. for (var i in message.data) {
  127. var data = message.data[i];
  128. var object = channel.objects[data.object];
  129. if (object) {
  130. object.propertyUpdate(data.signals, data.properties);
  131. } else {
  132. console.warn("Unhandled property update: " + data.object + "::" + data.signal);
  133. }
  134. }
  135. channel.exec({type: QWebChannelMessageTypes.idle});
  136. }
  137. this.debug = function(message)
  138. {
  139. channel.send({type: QWebChannelMessageTypes.debug, data: message});
  140. };
  141. channel.exec({type: QWebChannelMessageTypes.init}, function(data) {
  142. for (var objectName in data) {
  143. var object = new QObject(objectName, data[objectName], channel);
  144. }
  145. // now unwrap properties, which might reference other registered objects
  146. for (var objectName in channel.objects) {
  147. channel.objects[objectName].unwrapProperties();
  148. }
  149. if (initCallback) {
  150. initCallback(channel);
  151. }
  152. channel.exec({type: QWebChannelMessageTypes.idle});
  153. });
  154. };
  155. function QObject(name, data, webChannel)
  156. {
  157. this.__id__ = name;
  158. webChannel.objects[name] = this;
  159. // List of callbacks that get invoked upon signal emission
  160. this.__objectSignals__ = {};
  161. // Cache of all properties, updated when a notify signal is emitted
  162. this.__propertyCache__ = {};
  163. var object = this;
  164. // ----------------------------------------------------------------------
  165. this.unwrapQObject = function(response)
  166. {
  167. if (response instanceof Array) {
  168. // support list of objects
  169. var ret = new Array(response.length);
  170. for (var i = 0; i < response.length; ++i) {
  171. ret[i] = object.unwrapQObject(response[i]);
  172. }
  173. return ret;
  174. }
  175. if (!response
  176. || !response["__QObject*__"]
  177. || response["id"] === undefined) {
  178. return response;
  179. }
  180. var objectId = response.id;
  181. if (webChannel.objects[objectId])
  182. return webChannel.objects[objectId];
  183. if (!response.data) {
  184. console.error("Cannot unwrap unknown QObject " + objectId + " without data.");
  185. return;
  186. }
  187. var qObject = new QObject( objectId, response.data, webChannel );
  188. qObject.destroyed.connect(function() {
  189. if (webChannel.objects[objectId] === qObject) {
  190. delete webChannel.objects[objectId];
  191. // reset the now deleted QObject to an empty {} object
  192. // just assigning {} though would not have the desired effect, but the
  193. // below also ensures all external references will see the empty map
  194. // NOTE: this detour is necessary to workaround QTBUG-40021
  195. var propertyNames = [];
  196. for (var propertyName in qObject) {
  197. propertyNames.push(propertyName);
  198. }
  199. for (var idx in propertyNames) {
  200. delete qObject[propertyNames[idx]];
  201. }
  202. }
  203. });
  204. // here we are already initialized, and thus must directly unwrap the properties
  205. qObject.unwrapProperties();
  206. return qObject;
  207. }
  208. this.unwrapProperties = function()
  209. {
  210. for (var propertyIdx in object.__propertyCache__) {
  211. object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]);
  212. }
  213. }
  214. function addSignal(signalData, isPropertyNotifySignal)
  215. {
  216. var signalName = signalData[0];
  217. var signalIndex = signalData[1];
  218. object[signalName] = {
  219. connect: function(callback) {
  220. if (typeof(callback) !== "function") {
  221. console.error("Bad callback given to connect to signal " + signalName);
  222. return;
  223. }
  224. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  225. object.__objectSignals__[signalIndex].push(callback);
  226. if (!isPropertyNotifySignal && signalName !== "destroyed") {
  227. // only required for "pure" signals, handled separately for properties in propertyUpdate
  228. // also note that we always get notified about the destroyed signal
  229. webChannel.exec({
  230. type: QWebChannelMessageTypes.connectToSignal,
  231. object: object.__id__,
  232. signal: signalIndex
  233. });
  234. }
  235. },
  236. disconnect: function(callback) {
  237. if (typeof(callback) !== "function") {
  238. console.error("Bad callback given to disconnect from signal " + signalName);
  239. return;
  240. }
  241. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  242. var idx = object.__objectSignals__[signalIndex].indexOf(callback);
  243. if (idx === -1) {
  244. console.error("Cannot find connection of signal " + signalName + " to " + callback.name);
  245. return;
  246. }
  247. object.__objectSignals__[signalIndex].splice(idx, 1);
  248. if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) {
  249. // only required for "pure" signals, handled separately for properties in propertyUpdate
  250. webChannel.exec({
  251. type: QWebChannelMessageTypes.disconnectFromSignal,
  252. object: object.__id__,
  253. signal: signalIndex
  254. });
  255. }
  256. }
  257. };
  258. }
  259. /**
  260. * Invokes all callbacks for the given signalname. Also works for property notify callbacks.
  261. */
  262. function invokeSignalCallbacks(signalName, signalArgs)
  263. {
  264. var connections = object.__objectSignals__[signalName];
  265. if (connections) {
  266. connections.forEach(function(callback) {
  267. callback.apply(callback, signalArgs);
  268. });
  269. }
  270. }
  271. this.propertyUpdate = function(signals, propertyMap)
  272. {
  273. // update property cache
  274. for (var propertyIndex in propertyMap) {
  275. var propertyValue = propertyMap[propertyIndex];
  276. object.__propertyCache__[propertyIndex] = propertyValue;
  277. }
  278. for (var signalName in signals) {
  279. // Invoke all callbacks, as signalEmitted() does not. This ensures the
  280. // property cache is updated before the callbacks are invoked.
  281. invokeSignalCallbacks(signalName, signals[signalName]);
  282. }
  283. }
  284. this.signalEmitted = function(signalName, signalArgs)
  285. {
  286. invokeSignalCallbacks(signalName, signalArgs);
  287. }
  288. function addMethod(methodData)
  289. {
  290. var methodName = methodData[0];
  291. var methodIdx = methodData[1];
  292. object[methodName] = function() {
  293. var args = [];
  294. var callback;
  295. for (var i = 0; i < arguments.length; ++i) {
  296. if (typeof arguments[i] === "function")
  297. callback = arguments[i];
  298. else
  299. args.push(arguments[i]);
  300. }
  301. webChannel.exec({
  302. "type": QWebChannelMessageTypes.invokeMethod,
  303. "object": object.__id__,
  304. "method": methodIdx,
  305. "args": args
  306. }, function(response) {
  307. if (response !== undefined) {
  308. var result = object.unwrapQObject(response);
  309. if (callback) {
  310. (callback)(result);
  311. }
  312. }
  313. });
  314. };
  315. }
  316. function bindGetterSetter(propertyInfo)
  317. {
  318. var propertyIndex = propertyInfo[0];
  319. var propertyName = propertyInfo[1];
  320. var notifySignalData = propertyInfo[2];
  321. // initialize property cache with current value
  322. // NOTE: if this is an object, it is not directly unwrapped as it might
  323. // reference other QObject that we do not know yet
  324. object.__propertyCache__[propertyIndex] = propertyInfo[3];
  325. if (notifySignalData) {
  326. if (notifySignalData[0] === 1) {
  327. // signal name is optimized away, reconstruct the actual name
  328. notifySignalData[0] = propertyName + "Changed";
  329. }
  330. addSignal(notifySignalData, true);
  331. }
  332. Object.defineProperty(object, propertyName, {
  333. get: function () {
  334. var propertyValue = object.__propertyCache__[propertyIndex];
  335. if (propertyValue === undefined) {
  336. // This shouldn't happen
  337. console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__);
  338. }
  339. return propertyValue;
  340. },
  341. set: function(value) {
  342. if (value === undefined) {
  343. console.warn("Property setter for " + propertyName + " called with undefined value!");
  344. return;
  345. }
  346. object.__propertyCache__[propertyIndex] = value;
  347. webChannel.exec({
  348. "type": QWebChannelMessageTypes.setProperty,
  349. "object": object.__id__,
  350. "property": propertyIndex,
  351. "value": value
  352. });
  353. }
  354. });
  355. }
  356. // ----------------------------------------------------------------------
  357. data.methods.forEach(addMethod);
  358. data.properties.forEach(bindGetterSetter);
  359. data.signals.forEach(function(signal) { addSignal(signal, false); });
  360. for (var name in data.enums) {
  361. object[name] = data.enums[name];
  362. }
  363. }
  364. //required for use with nodejs
  365. if (typeof module === 'object') {
  366. module.exports = {
  367. QWebChannel: QWebChannel
  368. };
  369. }