Advertisement
Guest User

Untitled

a guest
Feb 14th, 2024
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.71 KB | None | 0 0
  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.  
  41. "use strict";
  42.  
  43. var QWebChannelMessageTypes = {
  44. signal: 1,
  45. propertyUpdate: 2,
  46. init: 3,
  47. idle: 4,
  48. debug: 5,
  49. invokeMethod: 6,
  50. connectToSignal: 7,
  51. disconnectFromSignal: 8,
  52. setProperty: 9,
  53. response: 10,
  54. };
  55.  
  56. var QWebChannel = function(transport, initCallback)
  57. {
  58. if (typeof transport !== "object" || typeof transport.send !== "function") {
  59. console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
  60. " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
  61. return;
  62. }
  63.  
  64. var channel = this;
  65. this.transport = transport;
  66.  
  67. this.send = function(data)
  68. {
  69. if (typeof(data) !== "string") {
  70. data = JSON.stringify(data);
  71. }
  72. channel.transport.send(data);
  73. }
  74.  
  75. this.transport.onmessage = function(message)
  76. {
  77. var data = message.data;
  78. if (typeof data === "string") {
  79. data = JSON.parse(data);
  80. }
  81. switch (data.type) {
  82. case QWebChannelMessageTypes.signal:
  83. channel.handleSignal(data);
  84. break;
  85. case QWebChannelMessageTypes.response:
  86. channel.handleResponse(data);
  87. break;
  88. case QWebChannelMessageTypes.propertyUpdate:
  89. channel.handlePropertyUpdate(data);
  90. break;
  91. default:
  92. console.error("invalid message received:", message.data);
  93. break;
  94. }
  95. }
  96.  
  97. this.execCallbacks = {};
  98. this.execId = 0;
  99. this.exec = function(data, callback)
  100. {
  101. if (!callback) {
  102. // if no callback is given, send directly
  103. channel.send(data);
  104. return;
  105. }
  106. if (channel.execId === Number.MAX_VALUE) {
  107. // wrap
  108. channel.execId = Number.MIN_VALUE;
  109. }
  110. if (data.hasOwnProperty("id")) {
  111. console.error("Cannot exec message with property id: " + JSON.stringify(data));
  112. return;
  113. }
  114. data.id = channel.execId++;
  115. channel.execCallbacks[data.id] = callback;
  116. channel.send(data);
  117. };
  118.  
  119. this.objects = {};
  120.  
  121. this.handleSignal = function(message)
  122. {
  123. var object = channel.objects[message.object];
  124. if (object) {
  125. object.signalEmitted(message.signal, message.args);
  126. } else {
  127. console.warn("Unhandled signal: " + message.object + "::" + message.signal);
  128. }
  129. }
  130.  
  131. this.handleResponse = function(message)
  132. {
  133. if (!message.hasOwnProperty("id")) {
  134. console.error("Invalid response message received: ", JSON.stringify(message));
  135. return;
  136. }
  137. channel.execCallbacks[message.id](message.data);
  138. delete channel.execCallbacks[message.id];
  139. }
  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.  
  155. this.debug = function(message)
  156. {
  157. channel.send({type: QWebChannelMessageTypes.debug, data: message});
  158. };
  159.  
  160. channel.exec({type: QWebChannelMessageTypes.init}, function(data) {
  161. for (var objectName in data) {
  162. var object = new QObject(objectName, data[objectName], channel);
  163. }
  164. // now unwrap properties, which might reference other registered objects
  165. for (var objectName in channel.objects) {
  166. channel.objects[objectName].unwrapProperties();
  167. }
  168. if (initCallback) {
  169. initCallback(channel);
  170. }
  171. channel.exec({type: QWebChannelMessageTypes.idle});
  172. });
  173. };
  174.  
  175. function QObject(name, data, webChannel)
  176. {
  177. this.__id__ = name;
  178. webChannel.objects[name] = this;
  179.  
  180. // List of callbacks that get invoked upon signal emission
  181. this.__objectSignals__ = {};
  182.  
  183. // Cache of all properties, updated when a notify signal is emitted
  184. this.__propertyCache__ = {};
  185.  
  186. var object = this;
  187.  
  188. // ----------------------------------------------------------------------
  189.  
  190. this.unwrapQObject = function(response)
  191. {
  192. if (response instanceof Array) {
  193. // support list of objects
  194. var ret = new Array(response.length);
  195. for (var i = 0; i < response.length; ++i) {
  196. ret[i] = object.unwrapQObject(response[i]);
  197. }
  198. return ret;
  199. }
  200. if (!response
  201. || !response["__QObject*__"]
  202. || response.id === undefined) {
  203. return response;
  204. }
  205.  
  206. var objectId = response.id;
  207. if (webChannel.objects[objectId])
  208. return webChannel.objects[objectId];
  209.  
  210. if (!response.data) {
  211. console.error("Cannot unwrap unknown QObject " + objectId + " without data.");
  212. return;
  213. }
  214.  
  215. var qObject = new QObject( objectId, response.data, webChannel );
  216. qObject.destroyed.connect(function() {
  217. if (webChannel.objects[objectId] === qObject) {
  218. delete webChannel.objects[objectId];
  219. // reset the now deleted QObject to an empty {} object
  220. // just assigning {} though would not have the desired effect, but the
  221. // below also ensures all external references will see the empty map
  222. // NOTE: this detour is necessary to workaround QTBUG-40021
  223. var propertyNames = [];
  224. for (var propertyName in qObject) {
  225. propertyNames.push(propertyName);
  226. }
  227. for (var idx in propertyNames) {
  228. delete qObject[propertyNames[idx]];
  229. }
  230. }
  231. });
  232. // here we are already initialized, and thus must directly unwrap the properties
  233. qObject.unwrapProperties();
  234. return qObject;
  235. }
  236.  
  237. this.unwrapProperties = function()
  238. {
  239. for (var propertyIdx in object.__propertyCache__) {
  240. object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]);
  241. }
  242. }
  243.  
  244. function addSignal(signalData, isPropertyNotifySignal)
  245. {
  246. var signalName = signalData[0];
  247. var signalIndex = signalData[1];
  248. object[signalName] = {
  249. connect: function(callback) {
  250. if (typeof(callback) !== "function") {
  251. console.error("Bad callback given to connect to signal " + signalName);
  252. return;
  253. }
  254.  
  255. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  256. object.__objectSignals__[signalIndex].push(callback);
  257.  
  258. if (!isPropertyNotifySignal && signalName !== "destroyed") {
  259. // only required for "pure" signals, handled separately for properties in propertyUpdate
  260. // also note that we always get notified about the destroyed signal
  261. webChannel.exec({
  262. type: QWebChannelMessageTypes.connectToSignal,
  263. object: object.__id__,
  264. signal: signalIndex
  265. });
  266. }
  267. },
  268. disconnect: function(callback) {
  269. if (typeof(callback) !== "function") {
  270. console.error("Bad callback given to disconnect from signal " + signalName);
  271. return;
  272. }
  273. object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
  274. var idx = object.__objectSignals__[signalIndex].indexOf(callback);
  275. if (idx === -1) {
  276. console.error("Cannot find connection of signal " + signalName + " to " + callback.name);
  277. return;
  278. }
  279. object.__objectSignals__[signalIndex].splice(idx, 1);
  280. if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) {
  281. // only required for "pure" signals, handled separately for properties in propertyUpdate
  282. webChannel.exec({
  283. type: QWebChannelMessageTypes.disconnectFromSignal,
  284. object: object.__id__,
  285. signal: signalIndex
  286. });
  287. }
  288. }
  289. };
  290. }
  291.  
  292. /**
  293. * Invokes all callbacks for the given signalname. Also works for property notify callbacks.
  294. */
  295. function invokeSignalCallbacks(signalName, signalArgs)
  296. {
  297. var connections = object.__objectSignals__[signalName];
  298. if (connections) {
  299. connections.forEach(function(callback) {
  300. callback.apply(callback, signalArgs);
  301. });
  302. }
  303. }
  304.  
  305. this.propertyUpdate = function(signals, propertyMap)
  306. {
  307. // update property cache
  308. for (var propertyIndex in propertyMap) {
  309. var propertyValue = propertyMap[propertyIndex];
  310. object.__propertyCache__[propertyIndex] = propertyValue;
  311. }
  312.  
  313. for (var signalName in signals) {
  314. // Invoke all callbacks, as signalEmitted() does not. This ensures the
  315. // property cache is updated before the callbacks are invoked.
  316. invokeSignalCallbacks(signalName, signals[signalName]);
  317. }
  318. }
  319.  
  320. this.signalEmitted = function(signalName, signalArgs)
  321. {
  322. invokeSignalCallbacks(signalName, this.unwrapQObject(signalArgs));
  323. }
  324.  
  325. function addMethod(methodData)
  326. {
  327. var methodName = methodData[0];
  328. var methodIdx = methodData[1];
  329. object[methodName] = function() {
  330. var args = [];
  331. var callback;
  332. for (var i = 0; i < arguments.length; ++i) {
  333. var argument = arguments[i];
  334. if (typeof argument === "function")
  335. callback = argument;
  336. else if (argument instanceof QObject && webChannel.objects[argument.__id__] !== undefined)
  337. args.push({
  338. "id": argument.__id__
  339. });
  340. else
  341. args.push(argument);
  342. }
  343.  
  344. webChannel.exec({
  345. "type": QWebChannelMessageTypes.invokeMethod,
  346. "object": object.__id__,
  347. "method": methodIdx,
  348. "args": args
  349. }, function(response) {
  350. if (response !== undefined) {
  351. var result = object.unwrapQObject(response);
  352. if (callback) {
  353. (callback)(result);
  354. }
  355. }
  356. });
  357. };
  358. }
  359.  
  360. function bindGetterSetter(propertyInfo)
  361. {
  362. var propertyIndex = propertyInfo[0];
  363. var propertyName = propertyInfo[1];
  364. var notifySignalData = propertyInfo[2];
  365. // initialize property cache with current value
  366. // NOTE: if this is an object, it is not directly unwrapped as it might
  367. // reference other QObject that we do not know yet
  368. object.__propertyCache__[propertyIndex] = propertyInfo[3];
  369.  
  370. if (notifySignalData) {
  371. if (notifySignalData[0] === 1) {
  372. // signal name is optimized away, reconstruct the actual name
  373. notifySignalData[0] = propertyName + "Changed";
  374. }
  375. addSignal(notifySignalData, true);
  376. }
  377.  
  378. Object.defineProperty(object, propertyName, {
  379. configurable: true,
  380. get: function () {
  381. var propertyValue = object.__propertyCache__[propertyIndex];
  382. if (propertyValue === undefined) {
  383. // This shouldn't happen
  384. console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__);
  385. }
  386.  
  387. return propertyValue;
  388. },
  389. set: function(value) {
  390. if (value === undefined) {
  391. console.warn("Property setter for " + propertyName + " called with undefined value!");
  392. return;
  393. }
  394. object.__propertyCache__[propertyIndex] = value;
  395. var valueToSend = value;
  396. if (valueToSend instanceof QObject && webChannel.objects[valueToSend.__id__] !== undefined)
  397. valueToSend = { "id": valueToSend.__id__ };
  398. webChannel.exec({
  399. "type": QWebChannelMessageTypes.setProperty,
  400. "object": object.__id__,
  401. "property": propertyIndex,
  402. "value": valueToSend
  403. });
  404. }
  405. });
  406.  
  407. }
  408.  
  409. // ----------------------------------------------------------------------
  410.  
  411. data.methods.forEach(addMethod);
  412.  
  413. data.properties.forEach(bindGetterSetter);
  414.  
  415. data.signals.forEach(function(signal) { addSignal(signal, false); });
  416.  
  417. for (var name in data.enums) {
  418. object[name] = data.enums[name];
  419. }
  420. }
  421.  
  422. //required for use with nodejs
  423. if (typeof module === 'object') {
  424. module.exports = {
  425. QWebChannel: QWebChannel
  426. };
  427. }
  428.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement