qwebchannel.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2016 The Qt Company Ltd.
  4. ** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected], author Milian Wolff <[email protected]>
  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:BSD$
  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. ** BSD License Usage
  19. ** Alternatively, you may use this file under the terms of the BSD license
  20. ** as follows:
  21. **
  22. ** "Redistribution and use in source and binary forms, with or without
  23. ** modification, are permitted provided that the following conditions are
  24. ** met:
  25. ** * Redistributions of source code must retain the above copyright
  26. ** notice, this list of conditions and the following disclaimer.
  27. ** * Redistributions in binary form must reproduce the above copyright
  28. ** notice, this list of conditions and the following disclaimer in
  29. ** the documentation and/or other materials provided with the
  30. ** distribution.
  31. ** * Neither the name of The Qt Company Ltd nor the names of its
  32. ** contributors may be used to endorse or promote products derived
  33. ** from this software without specific prior written permission.
  34. **
  35. **
  36. ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  37. ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  38. ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  39. ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  40. ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  43. ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  44. ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  45. ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  46. ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  47. **
  48. ** $QT_END_LICENSE$
  49. **
  50. ****************************************************************************/
  51. "use strict";
  52. var QWebChannelMessageTypes = {
  53. signal: 1,
  54. propertyUpdate: 2,
  55. init: 3,
  56. idle: 4,
  57. debug: 5,
  58. invokeMethod: 6,
  59. connectToSignal: 7,
  60. disconnectFromSignal: 8,
  61. setProperty: 9,
  62. response: 10,
  63. };
  64. var QWebChannel = function(transport, initCallback)
  65. {
  66. if (typeof transport !== "object" || typeof transport.send !== "function") {
  67. console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
  68. " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
  69. return;
  70. }
  71. var channel = this;
  72. this.transport = transport;
  73. this.send = function(data)
  74. {
  75. if (typeof(data) !== "string") {
  76. data = JSON.stringify(data);
  77. }
  78. channel.transport.send(data);
  79. }
  80. this.transport.onmessage = function(message)
  81. {
  82. var data = message.data;
  83. if (typeof data === "string") {
  84. data = JSON.parse(data);
  85. }
  86. switch (data.type) {
  87. case QWebChannelMessageTypes.signal:
  88. channel.handleSignal(data);
  89. break;
  90. case QWebChannelMessageTypes.response:
  91. channel.handleResponse(data);
  92. break;
  93. case QWebChannelMessageTypes.propertyUpdate:
  94. channel.handlePropertyUpdate(data);
  95. break;
  96. default:
  97. console.error("invalid message received:", message.data);
  98. break;
  99. }
  100. }
  101. this.execCallbacks = {};
  102. this.execId = 0;
  103. this.exec = function(data, callback)
  104. {
  105. if (!callback) {
  106. // if no callback is given, send directly
  107. channel.send(data);
  108. return;
  109. }
  110. if (channel.execId === Number.MAX_VALUE) {
  111. // wrap
  112. channel.execId = Number.MIN_VALUE;
  113. }
  114. if (data.hasOwnProperty("id")) {
  115. console.error("Cannot exec message with property id: " + JSON.stringify(data));
  116. return;
  117. }
  118. data.id = channel.execId++;
  119. channel.execCallbacks[data.id] = callback;
  120. channel.send(data);
  121. };
  122. this.objects = {};
  123. this.handleSignal = function(message)
  124. {
  125. var object = channel.objects[message.object];
  126. if (object) {
  127. object.signalEmitted(message.signal, message.args);
  128. } else {
  129. console.warn("Unhandled signal: " + message.object + "::" + message.signal);
  130. }
  131. }
  132. this.handleResponse = function(message)
  133. {
  134. if (!message.hasOwnProperty("id")) {
  135. console.error("Invalid response message received: ", JSON.stringify(message));
  136. return;
  137. }
  138. channel.execCallbacks[message.id](message.data);
  139. delete channel.execCallbacks[message.id];
  140. }
  141. this.handlePropertyUpdate = function(message)
  142. {
  143. for (var i in message.data) {
  144. var data = message.data[i];
  145. var object = channel.objects[data.object];
  146. if (object) {
  147. object.propertyUpdate(data.signals, data.properties);
  148. } else {
  149. console.warn("Unhandled property update: " + data.object + "::" + data.signal);
  150. }
  151. }
  152. channel.exec({type: QWebChannelMessageTypes.idle});
  153. }
  154. this.debug = function(message)
  155. {
  156. channel.send({type: QWebChannelMessageTypes.debug, data: message});
  157. };
  158. channel.exec({type: QWebChannelMessageTypes.init}, function(data) {
  159. for (var objectName in data) {
  160. var object = new QObject(objectName, data[objectName], channel);
  161. }
  162. // now unwrap properties, which might reference other registered objects
  163. for (var objectName in channel.objects) {
  164. channel.objects[objectName].unwrapProperties();
  165. }
  166. if (initCallback) {
  167. initCallback(channel);
  168. }
  169. channel.exec({type: QWebChannelMessageTypes.idle});
  170. });
  171. };
  172. function QObject(name, data, webChannel)
  173. {
  174. this.__id__ = name;
  175. webChannel.objects[name] = this;
  176. // List of callbacks that get invoked upon signal emission
  177. this.__objectSignals__ = {};
  178. // Cache of all properties, updated when a notify signal is emitted
  179. this.__propertyCache__ = {};
  180. var object = this;
  181. // ----------------------------------------------------------------------
  182. this.unwrapQObject = function(response)
  183. {
  184. if (response instanceof Array) {
  185. // support list of objects
  186. var ret = new Array(response.length);
  187. for (var i = 0; i < response.length; ++i) {
  188. ret[i] = object.unwrapQObject(response[i]);
  189. }
  190. return ret;
  191. }
  192. if (!response
  193. || !response["__QObject*__"]
  194. || response.id === undefined) {
  195. return response;
  196. }
  197. var objectId = response.id;
  198. if (webChannel.objects[objectId])
  199. return webChannel.objects[objectId];
  200. if (!response.data) {
  201. console.error("Cannot unwrap unknown QObject " + objectId + " without data.");
  202. return;
  203. }
  204. var qObject = new QObject( objectId, response.data, webChannel );
  205. qObject.destroyed.connect(function() {
  206. if (webChannel.objects[objectId] === qObject) {
  207. delete webChannel.objects[objectId];
  208. // reset the now deleted QObject to an empty {} object
  209. // just assigning {} though would not have the desired effect, but the
  210. // below also ensures all external references will see the empty map
  211. // NOTE: this detour is necessary to workaround QTBUG-40021
  212. var propertyNames = [];
  213. for (var propertyName in qObject) {
  214. propertyNames.push(propertyName);
  215. }
  216. for (var idx in propertyNames) {
  217. delete qObject[propertyNames[idx]];
  218. }
  219. }
  220. });
  221. // here we are already initialized, and thus must directly unwrap the properties
  222. qObject.unwrapProperties();
  223. return qObject;
  224. }
  225. this.unwrapProperties = function()
  226. {
  227. for (var propertyIdx in object.__propertyCache__) {
  228. object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]);
  229. }
  230. }
  231. function addSignal(signalData, isPropertyNotifySignal)
  232. {
  233. var signalName = signalData[0];
  234. var signalIndex = signalData[1];
  235. object[signalName] = {
  236. connect: function(callback) {
  237. if (typeof(callback) !== "function") {
  238. console.error("Bad callback given to connect to signal " + signalName);
  239. return;
  240. }
  241. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  242. object.__objectSignals__[signalIndex].push(callback);
  243. if (!isPropertyNotifySignal && signalName !== "destroyed") {
  244. // only required for "pure" signals, handled separately for properties in propertyUpdate
  245. // also note that we always get notified about the destroyed signal
  246. webChannel.exec({
  247. type: QWebChannelMessageTypes.connectToSignal,
  248. object: object.__id__,
  249. signal: signalIndex
  250. });
  251. }
  252. },
  253. disconnect: function(callback) {
  254. if (typeof(callback) !== "function") {
  255. console.error("Bad callback given to disconnect from signal " + signalName);
  256. return;
  257. }
  258. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  259. var idx = object.__objectSignals__[signalIndex].indexOf(callback);
  260. if (idx === -1) {
  261. console.error("Cannot find connection of signal " + signalName + " to " + callback.name);
  262. return;
  263. }
  264. object.__objectSignals__[signalIndex].splice(idx, 1);
  265. if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) {
  266. // only required for "pure" signals, handled separately for properties in propertyUpdate
  267. webChannel.exec({
  268. type: QWebChannelMessageTypes.disconnectFromSignal,
  269. object: object.__id__,
  270. signal: signalIndex
  271. });
  272. }
  273. }
  274. };
  275. }
  276. /**
  277. * Invokes all callbacks for the given signalname. Also works for property notify callbacks.
  278. */
  279. function invokeSignalCallbacks(signalName, signalArgs)
  280. {
  281. var connections = object.__objectSignals__[signalName];
  282. if (connections) {
  283. connections.forEach(function(callback) {
  284. callback.apply(callback, signalArgs);
  285. });
  286. }
  287. }
  288. this.propertyUpdate = function(signals, propertyMap)
  289. {
  290. // update property cache
  291. for (var propertyIndex in propertyMap) {
  292. var propertyValue = propertyMap[propertyIndex];
  293. object.__propertyCache__[propertyIndex] = propertyValue;
  294. }
  295. for (var signalName in signals) {
  296. // Invoke all callbacks, as signalEmitted() does not. This ensures the
  297. // property cache is updated before the callbacks are invoked.
  298. invokeSignalCallbacks(signalName, signals[signalName]);
  299. }
  300. }
  301. this.signalEmitted = function(signalName, signalArgs)
  302. {
  303. invokeSignalCallbacks(signalName, signalArgs);
  304. }
  305. function addMethod(methodData)
  306. {
  307. var methodName = methodData[0];
  308. var methodIdx = methodData[1];
  309. object[methodName] = function() {
  310. var args = [];
  311. var callback;
  312. for (var i = 0; i < arguments.length; ++i) {
  313. if (typeof arguments[i] === "function")
  314. callback = arguments[i];
  315. else
  316. args.push(arguments[i]);
  317. }
  318. webChannel.exec({
  319. "type": QWebChannelMessageTypes.invokeMethod,
  320. "object": object.__id__,
  321. "method": methodIdx,
  322. "args": args
  323. }, function(response) {
  324. if (response !== undefined) {
  325. var result = object.unwrapQObject(response);
  326. if (callback) {
  327. (callback)(result);
  328. }
  329. }
  330. });
  331. };
  332. }
  333. function bindGetterSetter(propertyInfo)
  334. {
  335. var propertyIndex = propertyInfo[0];
  336. var propertyName = propertyInfo[1];
  337. var notifySignalData = propertyInfo[2];
  338. // initialize property cache with current value
  339. // NOTE: if this is an object, it is not directly unwrapped as it might
  340. // reference other QObject that we do not know yet
  341. object.__propertyCache__[propertyIndex] = propertyInfo[3];
  342. if (notifySignalData) {
  343. if (notifySignalData[0] === 1) {
  344. // signal name is optimized away, reconstruct the actual name
  345. notifySignalData[0] = propertyName + "Changed";
  346. }
  347. addSignal(notifySignalData, true);
  348. }
  349. Object.defineProperty(object, propertyName, {
  350. configurable: true,
  351. get: function () {
  352. var propertyValue = object.__propertyCache__[propertyIndex];
  353. if (propertyValue === undefined) {
  354. // This shouldn't happen
  355. console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__);
  356. }
  357. return propertyValue;
  358. },
  359. set: function(value) {
  360. if (value === undefined) {
  361. console.warn("Property setter for " + propertyName + " called with undefined value!");
  362. return;
  363. }
  364. object.__propertyCache__[propertyIndex] = value;
  365. webChannel.exec({
  366. "type": QWebChannelMessageTypes.setProperty,
  367. "object": object.__id__,
  368. "property": propertyIndex,
  369. "value": value
  370. });
  371. }
  372. });
  373. }
  374. // ----------------------------------------------------------------------
  375. data.methods.forEach(addMethod);
  376. data.properties.forEach(bindGetterSetter);
  377. data.signals.forEach(function(signal) { addSignal(signal, false); });
  378. for (var name in data.enums) {
  379. object[name] = data.enums[name];
  380. }
  381. }
  382. //required for use with nodejs
  383. if (typeof module === 'object') {
  384. module.exports = {
  385. QWebChannel: QWebChannel
  386. };
  387. }