qwebchannel.js 15 KB

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