diff options
author | Arno Rehn <[email protected]> | 2025-06-10 12:35:41 +0200 |
---|---|---|
committer | Arno Rehn <[email protected]> | 2025-07-16 09:22:42 +0200 |
commit | fd817460848a2d779ac38f220ccf5c070cb89b58 (patch) | |
tree | 551b85ca830aad2de9ddee83f354fe5c1e1f368d /src/webchannel | |
parent | 21b85cfceef2d908ba59a15a974ee6d6ee002720 (diff) |
Adds all example dirs with qt_internal_add_example() so that their
source code will be installed when QT_INSTALL_EXAMPLES_SOURCES is set.
Also puts qwebchannel.js into a proper location at src/webchannel and
removes it from the examples/ tree. Adds a CMake file that will find
qwebchannel.js.
Tested configurations (CMake only):
* Out-of-source build, examples built normally
* Out-of-source build, examples built as ExternalProject
* Examples built standalone
Change-Id: Iac80602203676399a730ac4816c38bd0068e9570
Reviewed-by: Alexandru Croitor <[email protected]>
Diffstat (limited to 'src/webchannel')
-rw-r--r-- | src/webchannel/CMakeLists.txt | 36 | ||||
-rw-r--r-- | src/webchannel/Qt6WebChannelExtras.cmake.in | 6 | ||||
-rw-r--r-- | src/webchannel/qwebchannel.js | 455 |
3 files changed, 491 insertions, 6 deletions
diff --git a/src/webchannel/CMakeLists.txt b/src/webchannel/CMakeLists.txt index 54a7457..83ae035 100644 --- a/src/webchannel/CMakeLists.txt +++ b/src/webchannel/CMakeLists.txt @@ -1,6 +1,26 @@ # Copyright (C) 2022 The Qt Company Ltd. # SPDX-License-Identifier: BSD-3-Clause +if(QT6_INSTALL_QT_SHAREDIR) + set(INSTALL_WEBCHANNEL_SHAREDIR "${QT6_INSTALL_QT_SHAREDIR}/webchannel") +else() + set(INSTALL_WEBCHANNEL_SHAREDIR "${INSTALL_QT_SHAREDIR}/webchannel") +endif() + +include(CMakePackageConfigHelpers) + +set(target "WebChannel") +set(path_suffix "${INSTALL_CMAKE_NAMESPACE}${target}") +qt_path_join(config_build_dir ${QT_CONFIG_BUILD_DIR} ${path_suffix}) +qt_path_join(config_install_dir ${QT_CONFIG_INSTALL_DIR} ${path_suffix}) + +configure_package_config_file( + Qt6WebChannelExtras.cmake.in + "${config_build_dir}/Qt6WebChannelExtras.cmake" + INSTALL_DESTINATION "${config_install_dir}" + PATH_VARS INSTALL_WEBCHANNEL_SHAREDIR +) + qt_internal_add_module(WebChannel SOURCES qmetaobjectpublisher.cpp qmetaobjectpublisher_p.h @@ -8,22 +28,22 @@ qt_internal_add_module(WebChannel qwebchannelabstracttransport.cpp qwebchannelabstracttransport.h signalhandler_p.h qwebchannelglobal.h + qwebchannel.js DEFINES QT_NO_CONTEXTLESS_CONNECT LIBRARIES Qt::CorePrivate -) - -set(resource_file "../../examples/webchannel/shared/qwebchannel.js") -set_source_files_properties(${resource_file} PROPERTIES - QT_RESOURCE_ALIAS "qwebchannel.js" + EXTRA_CMAKE_FILES + "${config_build_dir}/Qt6WebChannelExtras.cmake" + EXTRA_CMAKE_INCLUDES + Qt6WebChannelExtras.cmake ) qt_internal_add_resource(WebChannel "resources" PREFIX "/qtwebchannel/" FILES - ${resource_file} + qwebchannel.js ) if(TARGET Qt::Qml) @@ -36,3 +56,7 @@ qt_internal_add_docs(WebChannel doc/qtwebchannel.qdocconf ) +install(FILES qwebchannel.js + DESTINATION "${INSTALL_WEBCHANNEL_SHAREDIR}") +file(COPY qwebchannel.js + DESTINATION "${QT_BUILD_DIR}/${INSTALL_WEBCHANNEL_SHAREDIR}/") diff --git a/src/webchannel/Qt6WebChannelExtras.cmake.in b/src/webchannel/Qt6WebChannelExtras.cmake.in new file mode 100644 index 0000000..0dd171a --- /dev/null +++ b/src/webchannel/Qt6WebChannelExtras.cmake.in @@ -0,0 +1,6 @@ +# Copyright (C) 2025 Menlo Systems GmbH; author Arno Rehn <[email protected]> +# SPDX-License-Identifier: BSD-3-Clause + +@PACKAGE_INIT@ + +set(QT_QWEBCHANNEL_JS_PATH "@PACKAGE_INSTALL_WEBCHANNEL_SHAREDIR@/qwebchannel.js") diff --git a/src/webchannel/qwebchannel.js b/src/webchannel/qwebchannel.js new file mode 100644 index 0000000..56fa66a --- /dev/null +++ b/src/webchannel/qwebchannel.js @@ -0,0 +1,455 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected], author Milian Wolff <[email protected]> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +"use strict"; + +var QWebChannelMessageTypes = { + signal: 1, + propertyUpdate: 2, + init: 3, + idle: 4, + debug: 5, + invokeMethod: 6, + connectToSignal: 7, + disconnectFromSignal: 8, + setProperty: 9, + response: 10, +}; + +var QWebChannel = function(transport, initCallback, converters) +{ + if (typeof transport !== "object" || typeof transport.send !== "function") { + console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." + + " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send)); + return; + } + + var channel = this; + this.transport = transport; + + var converterRegistry = + { + Date : function(response) { + if (typeof response === "string" + && response.match( + /^-?\d+-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?([-+\u2212](\d{2}):(\d{2})|Z)?$/)) { + var date = new Date(response); + if (!isNaN(date)) + return date; + } + return undefined; // Return undefined if current converter is not applicable + } + }; + + this.usedConverters = []; + + this.addConverter = function(converter) + { + if (typeof converter === "string") { + if (converterRegistry.hasOwnProperty(converter)) + this.usedConverters.push(converterRegistry[converter]); + else + console.error("Converter '" + converter + "' not found"); + } else if (typeof converter === "function") { + this.usedConverters.push(converter); + } else { + console.error("Invalid converter object type " + typeof converter); + } + } + + if (Array.isArray(converters)) { + for (const converter of converters) + this.addConverter(converter); + } else if (converters !== undefined) { + this.addConverter(converters); + } + + this.send = function(data) + { + if (typeof(data) !== "string") { + data = JSON.stringify(data); + } + channel.transport.send(data); + } + + this.transport.onmessage = function(message) + { + var data = message.data; + if (typeof data === "string") { + data = JSON.parse(data); + } + switch (data.type) { + case QWebChannelMessageTypes.signal: + channel.handleSignal(data); + break; + case QWebChannelMessageTypes.response: + channel.handleResponse(data); + break; + case QWebChannelMessageTypes.propertyUpdate: + channel.handlePropertyUpdate(data); + break; + default: + console.error("invalid message received:", message.data); + break; + } + } + + this.execCallbacks = {}; + this.execId = 0; + this.exec = function(data, callback) + { + if (!callback) { + // if no callback is given, send directly + channel.send(data); + return; + } + if (channel.execId === Number.MAX_VALUE) { + // wrap + channel.execId = Number.MIN_VALUE; + } + if (data.hasOwnProperty("id")) { + console.error("Cannot exec message with property id: " + JSON.stringify(data)); + return; + } + data.id = channel.execId++; + channel.execCallbacks[data.id] = callback; + channel.send(data); + }; + + this.objects = {}; + + this.handleSignal = function(message) + { + var object = channel.objects[message.object]; + if (object) { + object.signalEmitted(message.signal, message.args); + } else { + console.warn("Unhandled signal: " + message.object + "::" + message.signal); + } + } + + this.handleResponse = function(message) + { + if (!message.hasOwnProperty("id")) { + console.error("Invalid response message received: ", JSON.stringify(message)); + return; + } + channel.execCallbacks[message.id](message.data); + delete channel.execCallbacks[message.id]; + } + + this.handlePropertyUpdate = function(message) + { + message.data.forEach(data => { + var object = channel.objects[data.object]; + if (object) { + object.propertyUpdate(data.signals, data.properties); + } else { + console.warn("Unhandled property update: " + data.object + "::" + data.signal); + } + }); + channel.exec({type: QWebChannelMessageTypes.idle}); + } + + this.debug = function(message) + { + channel.send({type: QWebChannelMessageTypes.debug, data: message}); + }; + + channel.exec({type: QWebChannelMessageTypes.init}, function(data) { + for (const objectName of Object.keys(data)) { + new QObject(objectName, data[objectName], channel); + } + + // now unwrap properties, which might reference other registered objects + for (const objectName of Object.keys(channel.objects)) { + channel.objects[objectName].unwrapProperties(); + } + + if (initCallback) { + initCallback(channel); + } + channel.exec({type: QWebChannelMessageTypes.idle}); + }); +}; + +function QObject(name, data, webChannel) +{ + this.__id__ = name; + webChannel.objects[name] = this; + + // List of callbacks that get invoked upon signal emission + this.__objectSignals__ = {}; + + // Cache of all properties, updated when a notify signal is emitted + this.__propertyCache__ = {}; + + var object = this; + + // ---------------------------------------------------------------------- + + this.unwrapQObject = function(response) + { + for (const converter of webChannel.usedConverters) { + var result = converter(response); + if (result !== undefined) + return result; + } + + if (response instanceof Array) { + // support list of objects + return response.map(qobj => object.unwrapQObject(qobj)) + } + if (!(response instanceof Object)) + return response; + + if (!response["__QObject*__"] || response.id === undefined) { + var jObj = {}; + for (const propName of Object.keys(response)) { + jObj[propName] = object.unwrapQObject(response[propName]); + } + return jObj; + } + + var objectId = response.id; + if (webChannel.objects[objectId]) + return webChannel.objects[objectId]; + + if (!response.data) { + console.error("Cannot unwrap unknown QObject " + objectId + " without data."); + return; + } + + var qObject = new QObject( objectId, response.data, webChannel ); + qObject.destroyed.connect(function() { + if (webChannel.objects[objectId] === qObject) { + delete webChannel.objects[objectId]; + // reset the now deleted QObject to an empty {} object + // just assigning {} though would not have the desired effect, but the + // below also ensures all external references will see the empty map + // NOTE: this detour is necessary to workaround QTBUG-40021 + Object.keys(qObject).forEach(name => delete qObject[name]); + } + }); + // here we are already initialized, and thus must directly unwrap the properties + qObject.unwrapProperties(); + return qObject; + } + + this.unwrapProperties = function() + { + for (const propertyIdx of Object.keys(object.__propertyCache__)) { + object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]); + } + } + + function addSignal(signalData, isPropertyNotifySignal) + { + var signalName = signalData[0]; + var signalIndex = signalData[1]; + object[signalName] = { + connect: function(callback) { + if (typeof(callback) !== "function") { + console.error("Bad callback given to connect to signal " + signalName); + return; + } + + object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || []; + object.__objectSignals__[signalIndex].push(callback); + + // only required for "pure" signals, handled separately for properties in propertyUpdate + if (isPropertyNotifySignal) + return; + + // also note that we always get notified about the destroyed signal + if (signalName === "destroyed" || signalName === "destroyed()" || signalName === "destroyed(QObject*)") + return; + + // and otherwise we only need to be connected only once + if (object.__objectSignals__[signalIndex].length == 1) { + webChannel.exec({ + type: QWebChannelMessageTypes.connectToSignal, + object: object.__id__, + signal: signalIndex + }); + } + }, + disconnect: function(callback) { + if (typeof(callback) !== "function") { + console.error("Bad callback given to disconnect from signal " + signalName); + return; + } + // This makes a new list. This is important because it won't interfere with + // signal processing if a disconnection happens while emittig a signal + object.__objectSignals__[signalIndex] = (object.__objectSignals__[signalIndex] || []).filter(function(c) { + return c != callback; + }); + if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) { + // only required for "pure" signals, handled separately for properties in propertyUpdate + webChannel.exec({ + type: QWebChannelMessageTypes.disconnectFromSignal, + object: object.__id__, + signal: signalIndex + }); + } + } + }; + } + + /** + * Invokes all callbacks for the given signalname. Also works for property notify callbacks. + */ + function invokeSignalCallbacks(signalName, signalArgs) + { + var connections = object.__objectSignals__[signalName]; + if (connections) { + connections.forEach(function(callback) { + callback.apply(callback, signalArgs); + }); + } + } + + this.propertyUpdate = function(signals, propertyMap) + { + // update property cache + for (const propertyIndex of Object.keys(propertyMap)) { + var propertyValue = propertyMap[propertyIndex]; + object.__propertyCache__[propertyIndex] = this.unwrapQObject(propertyValue); + } + + for (const signalName of Object.keys(signals)) { + // Invoke all callbacks, as signalEmitted() does not. This ensures the + // property cache is updated before the callbacks are invoked. + invokeSignalCallbacks(signalName, signals[signalName]); + } + } + + this.signalEmitted = function(signalName, signalArgs) + { + invokeSignalCallbacks(signalName, this.unwrapQObject(signalArgs)); + } + + function addMethod(methodData) + { + var methodName = methodData[0]; + var methodIdx = methodData[1]; + + // Fully specified methods are invoked by id, others by name for host-side overload resolution + var invokedMethod = methodName[methodName.length - 1] === ')' ? methodIdx : methodName + + object[methodName] = function() { + var args = []; + var callback; + var errCallback; + for (var i = 0; i < arguments.length; ++i) { + var argument = arguments[i]; + if (typeof argument === "function") + callback = argument; + else + args.push(argument); + } + + var result; + // during test, webChannel.exec synchronously calls the callback + // therefore, the promise must be constucted before calling + // webChannel.exec to ensure the callback is set up + if (!callback && (typeof(Promise) === 'function')) { + result = new Promise(function(resolve, reject) { + callback = resolve; + errCallback = reject; + }); + } + + webChannel.exec({ + "type": QWebChannelMessageTypes.invokeMethod, + "object": object.__id__, + "method": invokedMethod, + "args": args + }, function(response) { + if (response !== undefined) { + var result = object.unwrapQObject(response); + if (callback) { + (callback)(result); + } + } else if (errCallback) { + (errCallback)(); + } + }); + + return result; + }; + } + + function bindGetterSetter(propertyInfo) + { + var propertyIndex = propertyInfo[0]; + var propertyName = propertyInfo[1]; + var notifySignalData = propertyInfo[2]; + // initialize property cache with current value + // NOTE: if this is an object, it is not directly unwrapped as it might + // reference other QObject that we do not know yet + object.__propertyCache__[propertyIndex] = propertyInfo[3]; + + if (notifySignalData) { + if (notifySignalData[0] === 1) { + // signal name is optimized away, reconstruct the actual name + notifySignalData[0] = propertyName + "Changed"; + } + addSignal(notifySignalData, true); + } + + Object.defineProperty(object, propertyName, { + configurable: true, + get: function () { + var propertyValue = object.__propertyCache__[propertyIndex]; + if (propertyValue === undefined) { + // This shouldn't happen + console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__); + } + + return propertyValue; + }, + set: function(value) { + if (value === undefined) { + console.warn("Property setter for " + propertyName + " called with undefined value!"); + return; + } + object.__propertyCache__[propertyIndex] = value; + var valueToSend = value; + webChannel.exec({ + "type": QWebChannelMessageTypes.setProperty, + "object": object.__id__, + "property": propertyIndex, + "value": valueToSend + }); + } + }); + + } + + // ---------------------------------------------------------------------- + + data.methods.forEach(addMethod); + + data.properties.forEach(bindGetterSetter); + + data.signals.forEach(function(signal) { addSignal(signal, false); }); + + Object.assign(object, data.enums); +} + +QObject.prototype.toJSON = function() { + if (this.__id__ === undefined) return {}; + return { + id: this.__id__, + "__QObject*__": true + }; +}; + +//required for use with nodejs +if (typeof module === 'object') { + module.exports = { + QWebChannel: QWebChannel + }; +} |