diff options
Diffstat (limited to 'js/dbusServices')
-rw-r--r-- | js/dbusServices/dbus-service.in | 5 | ||||
-rw-r--r-- | js/dbusServices/dbus-service.service.in | 3 | ||||
-rw-r--r-- | js/dbusServices/dbusService.js | 179 | ||||
-rw-r--r-- | js/dbusServices/extensions/css/application.css | 2 | ||||
-rw-r--r-- | js/dbusServices/extensions/extensionsService.js | 274 | ||||
-rw-r--r-- | js/dbusServices/extensions/main.js | 20 | ||||
-rw-r--r-- | js/dbusServices/extensions/ui/extension-prefs-dialog.ui | 197 | ||||
-rw-r--r-- | js/dbusServices/meson.build | 48 | ||||
-rw-r--r-- | js/dbusServices/notifications/main.js | 11 | ||||
-rw-r--r-- | js/dbusServices/notifications/notificationDaemon.js | 105 | ||||
-rw-r--r-- | js/dbusServices/org.gnome.Shell.Extensions.src.gresource.xml | 18 | ||||
-rw-r--r-- | js/dbusServices/org.gnome.Shell.Notifications.src.gresource.xml | 11 | ||||
-rw-r--r-- | js/dbusServices/org.gnome.Shell.Screencast.src.gresource.xml | 11 | ||||
-rw-r--r-- | js/dbusServices/screencast/main.js | 11 | ||||
-rw-r--r-- | js/dbusServices/screencast/screencastService.js | 467 |
15 files changed, 1362 insertions, 0 deletions
diff --git a/js/dbusServices/dbus-service.in b/js/dbusServices/dbus-service.in new file mode 100644 index 0000000..5241661 --- /dev/null +++ b/js/dbusServices/dbus-service.in @@ -0,0 +1,5 @@ +imports.package.start({ + name: '@PACKAGE_NAME@', + prefix: '@prefix@', + libdir: '@libdir@', +}); diff --git a/js/dbusServices/dbus-service.service.in b/js/dbusServices/dbus-service.service.in new file mode 100644 index 0000000..3b0d09a --- /dev/null +++ b/js/dbusServices/dbus-service.service.in @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=@service@ +Exec=@gjs@ @pkgdatadir@/@service@ diff --git a/js/dbusServices/dbusService.js b/js/dbusServices/dbusService.js new file mode 100644 index 0000000..71b1e35 --- /dev/null +++ b/js/dbusServices/dbusService.js @@ -0,0 +1,179 @@ +/* exported DBusService, ServiceImplementation */ + +const { Gio, GLib } = imports.gi; + +const Signals = imports.signals; + +const IDLE_SHUTDOWN_TIME = 2; // s + +var ServiceImplementation = class { + constructor(info, objectPath) { + this._objectPath = objectPath; + this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(info, this); + + this._injectTracking('return_dbus_error'); + this._injectTracking('return_error_literal'); + this._injectTracking('return_gerror'); + this._injectTracking('return_value'); + this._injectTracking('return_value_with_unix_fd_list'); + + this._senders = new Map(); + this._holdCount = 0; + + this._hasSignals = this._dbusImpl.get_info().signals.length > 0; + this._shutdownTimeoutId = 0; + + // subclasses may override this to disable automatic shutdown + this._autoShutdown = true; + + this._queueShutdownCheck(); + } + + // subclasses may override this to own additional names + register() { + } + + export() { + this._dbusImpl.export(Gio.DBus.session, this._objectPath); + } + + unexport() { + this._dbusImpl.unexport(); + } + + hold() { + this._holdCount++; + } + + release() { + if (this._holdCount === 0) { + logError(new Error('Unmatched call to release()')); + return; + } + + this._holdCount--; + + if (this._holdCount === 0) + this._queueShutdownCheck(); + } + + /** + * _handleError: + * @param {Gio.DBusMethodInvocation} + * @param {Error} + * + * Complete @invocation with an appropriate error if @error is set; + * useful for implementing early returns from method implementations. + * + * @returns {bool} - true if @invocation was completed + */ + + _handleError(invocation, error) { + if (error === null) + return false; + + if (error instanceof GLib.Error) { + invocation.return_gerror(error); + } else { + let name = error.name; + if (!name.includes('.')) // likely a normal JS error + name = `org.gnome.gjs.JSError.${name}`; + invocation.return_dbus_error(name, error.message); + } + + return true; + } + + _maybeShutdown() { + if (!this._autoShutdown) + return; + + if (this._holdCount > 0) + return; + + this.emit('shutdown'); + } + + _queueShutdownCheck() { + if (this._shutdownTimeoutId) + GLib.source_remove(this._shutdownTimeoutId); + + this._shutdownTimeoutId = GLib.timeout_add_seconds( + GLib.PRIORITY_DEFAULT, IDLE_SHUTDOWN_TIME, + () => { + this._shutdownTimeoutId = 0; + this._maybeShutdown(); + + return GLib.SOURCE_REMOVE; + }); + } + + _trackSender(sender) { + if (this._senders.has(sender)) + return; + + this.hold(); + this._senders.set(sender, + this._dbusImpl.get_connection().watch_name( + sender, + Gio.BusNameWatcherFlags.NONE, + null, + () => this._untrackSender(sender))); + } + + _untrackSender(sender) { + const id = this._senders.get(sender); + + if (id) + this._dbusImpl.get_connection().unwatch_name(id); + + if (this._senders.delete(sender)) + this.release(); + } + + _injectTracking(methodName) { + const { prototype } = Gio.DBusMethodInvocation; + const origMethod = prototype[methodName]; + const that = this; + + prototype[methodName] = function (...args) { + origMethod.apply(this, args); + + if (that._hasSignals) + that._trackSender(this.get_sender()); + + that._queueShutdownCheck(); + }; + } +}; +Signals.addSignalMethods(ServiceImplementation.prototype); + +var DBusService = class { + constructor(name, service) { + this._name = name; + this._service = service; + this._loop = new GLib.MainLoop(null, false); + + this._service.connect('shutdown', () => this._loop.quit()); + } + + run() { + // Bail out when not running under gnome-shell + Gio.DBus.watch_name(Gio.BusType.SESSION, + 'org.gnome.Shell', + Gio.BusNameWatcherFlags.NONE, + null, + () => this._loop.quit()); + + this._service.register(); + + Gio.DBus.own_name(Gio.BusType.SESSION, + this._name, + Gio.BusNameOwnerFlags.REPLACE, + () => this._service.export(), + null, + () => this._loop.quit()); + + this._loop.run(); + } +}; diff --git a/js/dbusServices/extensions/css/application.css b/js/dbusServices/extensions/css/application.css new file mode 100644 index 0000000..06914ea --- /dev/null +++ b/js/dbusServices/extensions/css/application.css @@ -0,0 +1,2 @@ +.expander-frame > * { border-top-width: 0; } +.expander-toolbar { border: 0 solid @borders; border-top-width: 1px; } diff --git a/js/dbusServices/extensions/extensionsService.js b/js/dbusServices/extensions/extensionsService.js new file mode 100644 index 0000000..9d444c5 --- /dev/null +++ b/js/dbusServices/extensions/extensionsService.js @@ -0,0 +1,274 @@ +// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- +/* exported ExtensionsService */ + +const { Gdk, Gio, GLib, GObject, Gtk, Shew } = imports.gi; + +const ExtensionUtils = imports.misc.extensionUtils; + +const { loadInterfaceXML } = imports.misc.fileUtils; +const { ServiceImplementation } = imports.dbusService; + +const ExtensionsIface = loadInterfaceXML('org.gnome.Shell.Extensions'); +const ExtensionsProxy = Gio.DBusProxy.makeProxyWrapper(ExtensionsIface); + +var ExtensionsService = class extends ServiceImplementation { + constructor() { + super(ExtensionsIface, '/org/gnome/Shell/Extensions'); + + this._proxy = new ExtensionsProxy(Gio.DBus.session, + 'org.gnome.Shell', '/org/gnome/Shell'); + + this._proxy.connectSignal('ExtensionStateChanged', + (proxy, sender, params) => { + this._dbusImpl.emit_signal('ExtensionStateChanged', + new GLib.Variant('(sa{sv})', params)); + }); + + this._proxy.connect('g-properties-changed', () => { + this._dbusImpl.emit_property_changed('UserExtensionsEnabled', + new GLib.Variant('b', this._proxy.UserExtensionsEnabled)); + }); + } + + get ShellVersion() { + return this._proxy.ShellVersion; + } + + get UserExtensionsEnabled() { + return this._proxy.UserExtensionsEnabled; + } + + set UserExtensionsEnabled(enable) { + this._proxy.UserExtensionsEnabled = enable; + } + + ListExtensionsAsync(params, invocation) { + this._proxy.ListExtensionsRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(a{sa{sv}})', res)); + }); + } + + GetExtensionInfoAsync(params, invocation) { + this._proxy.GetExtensionInfoRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(a{sv})', res)); + }); + } + + GetExtensionErrorsAsync(params, invocation) { + this._proxy.GetExtensionErrorsRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(as)', res)); + }); + } + + InstallRemoteExtensionAsync(params, invocation) { + this._proxy.InstallRemoteExtensionRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(s)', res)); + }); + } + + UninstallExtensionAsync(params, invocation) { + this._proxy.UninstallExtensionRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(b)', res)); + }); + } + + EnableExtensionAsync(params, invocation) { + this._proxy.EnableExtensionRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(b)', res)); + }); + } + + DisableExtensionAsync(params, invocation) { + this._proxy.DisableExtensionRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(b)', res)); + }); + } + + LaunchExtensionPrefsAsync([uuid], invocation) { + this.OpenExtensionPrefsAsync([uuid, '', {}], invocation); + } + + OpenExtensionPrefsAsync(params, invocation) { + const [uuid, parentWindow, options] = params; + + this._proxy.GetExtensionInfoRemote(uuid, (res, error) => { + if (this._handleError(invocation, error)) + return; + + const [serialized] = res; + const extension = ExtensionUtils.deserializeExtension(serialized); + + const window = new ExtensionPrefsDialog(extension); + window.realize(); + + let externalWindow = null; + + if (parentWindow) + externalWindow = Shew.ExternalWindow.new_from_handle(parentWindow); + + if (externalWindow) + externalWindow.set_parent_of(window.window); + + if (options.modal) + window.modal = options.modal.get_boolean(); + + window.connect('destroy', () => this.release()); + this.hold(); + + window.show(); + + invocation.return_value(null); + }); + } + + CheckForUpdatesAsync(params, invocation) { + this._proxy.CheckForUpdatesRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(null); + }); + } +}; + +var ExtensionPrefsDialog = GObject.registerClass({ + GTypeName: 'ExtensionPrefsDialog', + Template: 'resource:///org/gnome/Shell/Extensions/ui/extension-prefs-dialog.ui', + InternalChildren: [ + 'headerBar', + 'stack', + 'expander', + 'expanderArrow', + 'revealer', + 'errorView', + ], +}, class ExtensionPrefsDialog extends Gtk.Window { + _init(extension) { + super._init(); + + this._uuid = extension.uuid; + this._url = extension.metadata.url || ''; + + this._headerBar.title = extension.metadata.name; + + this._actionGroup = new Gio.SimpleActionGroup(); + this.insert_action_group('win', this._actionGroup); + + this._initActions(); + this._addCustomStylesheet(); + + this._gesture = new Gtk.GestureMultiPress({ + widget: this._expander, + button: 0, + exclusive: true, + }); + + this._gesture.connect('released', (gesture, nPress) => { + if (nPress === 1) + this._revealer.reveal_child = !this._revealer.reveal_child; + }); + + this._revealer.connect('notify::reveal-child', () => { + this._expanderArrow.icon_name = this._revealer.reveal_child + ? 'pan-down-symbolic' + : 'pan-end-symbolic'; + }); + + try { + ExtensionUtils.installImporter(extension); + + // give extension prefs access to their own extension object + ExtensionUtils.getCurrentExtension = () => extension; + + const prefsModule = extension.imports.prefs; + prefsModule.init(extension.metadata); + + const widget = prefsModule.buildPrefsWidget(); + this._stack.add(widget); + this._stack.visible_child = widget; + } catch (e) { + this._setError(e); + } + } + + _setError(exc) { + this._errorView.buffer.text = `${exc}\n\nStack trace:\n`; + // Indent stack trace. + this._errorView.buffer.text += + exc.stack.split('\n').map(line => ` ${line}`).join('\n'); + + // markdown for pasting in gitlab issues + let lines = [ + `The settings of extension ${this._uuid} had an error:`, + '```', + `${exc}`, + '```', + '', + 'Stack trace:', + '```', + exc.stack.replace(/\n$/, ''), // stack without trailing newline + '```', + '', + ]; + this._errorMarkdown = lines.join('\n'); + this._actionGroup.lookup('copy-error').enabled = true; + } + + _initActions() { + let action; + + action = new Gio.SimpleAction({ + name: 'copy-error', + enabled: false, + }); + action.connect('activate', () => { + const clipboard = Gtk.Clipboard.get_default(this.get_display()); + clipboard.set_text(this._errorMarkdown, -1); + }); + this._actionGroup.add_action(action); + + action = new Gio.SimpleAction({ + name: 'show-url', + enabled: this._url !== '', + }); + action.connect('activate', () => { + Gio.AppInfo.launch_default_for_uri(this._url, + this.get_display().get_app_launch_context()); + }); + this._actionGroup.add_action(action); + } + + _addCustomStylesheet() { + let provider = new Gtk.CssProvider(); + let uri = 'resource:///org/gnome/Shell/Extensions/css/application.css'; + try { + provider.load_from_file(Gio.File.new_for_uri(uri)); + } catch (e) { + logError(e, 'Failed to add application style'); + } + Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), + provider, + Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION); + } +}); diff --git a/js/dbusServices/extensions/main.js b/js/dbusServices/extensions/main.js new file mode 100644 index 0000000..9cc4bc5 --- /dev/null +++ b/js/dbusServices/extensions/main.js @@ -0,0 +1,20 @@ +/* exported main */ + +imports.gi.versions.Gdk = '3.0'; +imports.gi.versions.Gtk = '3.0'; + +const { Gtk } = imports.gi; +const pkg = imports.package; + +const { DBusService } = imports.dbusService; +const { ExtensionsService } = imports.extensionsService; + +function main() { + Gtk.init(null); + pkg.initFormat(); + + const service = new DBusService( + 'org.gnome.Shell.Extensions', + new ExtensionsService()); + service.run(); +} diff --git a/js/dbusServices/extensions/ui/extension-prefs-dialog.ui b/js/dbusServices/extensions/ui/extension-prefs-dialog.ui new file mode 100644 index 0000000..fc08eae --- /dev/null +++ b/js/dbusServices/extensions/ui/extension-prefs-dialog.ui @@ -0,0 +1,197 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Generated with glade 3.22.1 --> +<interface> + <requires lib="gtk+" version="3.20"/> + <template class="ExtensionPrefsDialog" parent="GtkWindow"> + <property name="default_width">600</property> + <property name="default_height">400</property> + <child type="titlebar"> + <object class="GtkHeaderBar" id="headerBar"> + <property name="visible">True</property> + <property name="show_close_button">True</property> + </object> + </child> + <child> + <object class="GtkStack" id="stack"> + <property name="visible">True</property> + <property name="can_focus">False</property> + <child> + <object class="GtkScrolledWindow"> + <property name="visible">True</property> + <property name="hscrollbar_policy">never</property> + <property name="propagate_natural_height">True</property> + <child> + <object class="GtkViewport"> + <property name="visible">True</property> + <child> + <object class="GtkBox"> + <property name="visible">True</property> + <property name="orientation">vertical</property> + <property name="margin">100</property> + <property name="margin_bottom">60</property> + <property name="spacing">12</property> + <child> + <object class="GtkLabel"> + <property name="visible">True</property> + <property name="label" translatable="yes">Something’s gone wrong</property> + <attributes> + <attribute name="scale" value="1.44"/> <!-- x-large --> + </attributes> + <style> + <class name="dim-label"/> + </style> + </object> + </child> + <child> + <object class="GtkLabel"> + <property name="visible">True</property> + <property name="label" translatable="yes">We’re very sorry, but there’s been a problem: the settings for this extension can’t be displayed. We recommend that you report the issue to the extension authors.</property> + <property name="justify">center</property> + <property name="wrap">True</property> + <property name="xalign">0.5</property> + <property name="yalign">0.5</property> + </object> + </child> + <child> + <object class="GtkBox"> + <property name="visible">True</property> + <property name="orientation">vertical</property> + <property name="margin_top">12</property> + <child> + <object class="GtkFrame" id="expander"> + <property name="visible">True</property> + <property name="hexpand">True</property> + <property name="shadow_type">in</property> + <child> + <object class="GtkEventBox"> + <property name="visible">True</property> + <child> + <object class="GtkBox"> + <property name="visible">True</property> + <property name="margin">12</property> + <property name="spacing">6</property> + <child> + <object class="GtkImage" id="expanderArrow"> + <property name="visible">True</property> + <property name="icon_name">pan-end-symbolic</property> + </object> + </child> + <child> + <object class="GtkLabel"> + <property name="visible">True</property> + <property name="label" translatable="yes">Technical Details</property> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + <child> + <object class="GtkRevealer" id="revealer"> + <property name="visible">True</property> + <child> + <object class="GtkFrame"> + <property name="visible">True</property> + <property name="shadow_type">in</property> + <style> + <class name="expander-frame"/> + </style> + <child> + <object class="GtkBox"> + <property name="visible">True</property> + <property name="orientation">vertical</property> + <child> + <object class="GtkTextView" id="errorView"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="monospace">True</property> + <property name="editable">False</property> + <property name="wrap_mode">word</property> + <property name="left_margin">12</property> + <property name="right_margin">12</property> + <property name="top_margin">12</property> + <property name="bottom_margin">12</property> + </object> + </child> + <child> + <object class="GtkToolbar"> + <property name="visible">True</property> + <style> + <class name="expander-toolbar"/> + </style> + <child> + <object class="GtkToolItem"> + <property name="visible">True</property> + <child> + <object class="GtkButton"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="action_name">win.copy-error</property> + <style> + <class name="flat"/> + <class name="image-button"/> + </style> + <child> + <object class="GtkImage"> + <property name="visible">True</property> + <property name="icon_name">edit-copy-symbolic</property> + </object> + </child> + </object> + </child> + </object> + </child> + <child> + <object class="GtkSeparatorToolItem"> + <property name="visible">True</property> + <property name="draw">False</property> + </object> + <packing> + <property name="expand">True</property> + </packing> + </child> + <child> + <object class="GtkToolItem"> + <property name="visible">True</property> + <child> + <object class="GtkButton" id="homeButton"> + <property name="visible" + bind-source="homeButton" + bind-property="sensitive" + bind-flags="sync-create"/> + <property name="label" translatable="yes">Homepage</property> + <property name="tooltip_text" translatable="yes">Visit extension homepage</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="no_show_all">True</property> + <property name="action_name">win.show-url</property> + <style> + <class name="flat"/> + </style> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </object> + </child> + </template> +</interface> diff --git a/js/dbusServices/meson.build b/js/dbusServices/meson.build new file mode 100644 index 0000000..2f047bb --- /dev/null +++ b/js/dbusServices/meson.build @@ -0,0 +1,48 @@ +launcherconf = configuration_data() +launcherconf.set('PACKAGE_NAME', meson.project_name()) +launcherconf.set('prefix', prefix) +launcherconf.set('libdir', libdir) + +dbus_services = { + 'org.gnome.Shell.Extensions': 'extensions', + 'org.gnome.Shell.Notifications': 'notifications', +} + +if enable_recorder + dbus_services += { + 'org.gnome.Shell.Screencast': 'screencast', + } +endif + +config_dir = '@0@/..'.format(meson.current_build_dir()) + +foreach service, dir : dbus_services + configure_file( + input: 'dbus-service.in', + output: service, + configuration: launcherconf, + install_dir: pkgdatadir, + ) + + serviceconf = configuration_data() + serviceconf.set('service', service) + serviceconf.set('gjs', gjs.path()) + serviceconf.set('pkgdatadir', pkgdatadir) + + configure_file( + input: 'dbus-service.service.in', + output: service + '.service', + configuration: serviceconf, + install_dir: servicedir + ) + + gnome.compile_resources( + service + '.src', + service + '.src.gresource.xml', + dependencies: [config_js], + source_dir: ['.', '..', dir, config_dir], + gresource_bundle: true, + install: true, + install_dir: pkgdatadir + ) +endforeach diff --git a/js/dbusServices/notifications/main.js b/js/dbusServices/notifications/main.js new file mode 100644 index 0000000..7944cd1 --- /dev/null +++ b/js/dbusServices/notifications/main.js @@ -0,0 +1,11 @@ +/* exported main */ + +const { DBusService } = imports.dbusService; +const { NotificationDaemon } = imports.notificationDaemon; + +function main() { + const service = new DBusService( + 'org.gnome.Shell.Notifications', + new NotificationDaemon()); + service.run(); +} diff --git a/js/dbusServices/notifications/notificationDaemon.js b/js/dbusServices/notifications/notificationDaemon.js new file mode 100644 index 0000000..bf0f85b --- /dev/null +++ b/js/dbusServices/notifications/notificationDaemon.js @@ -0,0 +1,105 @@ +// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- +/* exported NotificationDaemon */ + +const { Gio, GLib } = imports.gi; + +const { loadInterfaceXML } = imports.misc.fileUtils; +const { ServiceImplementation } = imports.dbusService; + +const NotificationsIface = loadInterfaceXML('org.freedesktop.Notifications'); +const NotificationsProxy = Gio.DBusProxy.makeProxyWrapper(NotificationsIface); + +Gio._promisify(Gio.DBusConnection.prototype, 'call', 'call_finish'); + +var NotificationDaemon = class extends ServiceImplementation { + constructor() { + super(NotificationsIface, '/org/freedesktop/Notifications'); + + this._autoShutdown = false; + + this._proxy = new NotificationsProxy(Gio.DBus.session, + 'org.gnome.Shell', + '/org/freedesktop/Notifications', + (proxy, error) => { + if (error) + log(error.message); + }); + + this._proxy.connectSignal('ActionInvoked', + (proxy, sender, params) => { + this._dbusImpl.emit_signal('ActionInvoked', + new GLib.Variant('(us)', params)); + }); + this._proxy.connectSignal('NotificationClosed', + (proxy, sender, params) => { + this._dbusImpl.emit_signal('NotificationClosed', + new GLib.Variant('(uu)', params)); + }); + } + + register() { + Gio.DBus.session.own_name( + 'org.freedesktop.Notifications', + Gio.BusNameOwnerFlags.REPLACE, + null, null); + } + + async NotifyAsync(params, invocation) { + const pid = await this._getSenderPid(invocation.get_sender()); + const hints = params[6]; + + params[6] = { + ...hints, + 'sender-pid': new GLib.Variant('u', pid), + }; + + this._proxy.NotifyRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(u)', res)); + }); + } + + CloseNotificationAsync(params, invocation) { + this._proxy.CloseNotificationRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(null); + }); + } + + GetCapabilitiesAsync(params, invocation) { + this._proxy.GetCapabilitiesRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(as)', res)); + }); + } + + GetServerInformationAsync(params, invocation) { + this._proxy.GetServerInformationRemote(...params, (res, error) => { + if (this._handleError(invocation, error)) + return; + + invocation.return_value(new GLib.Variant('(ssss)', res)); + }); + } + + async _getSenderPid(sender) { + const res = await Gio.DBus.session.call( + 'org.freedesktop.DBus', + '/', + 'org.freedesktop.DBus', + 'GetConnectionUnixProcessID', + new GLib.Variant('(s)', [sender]), + new GLib.VariantType('(u)'), + Gio.DBusCallFlags.NONE, + -1, + null); + const [pid] = res.deepUnpack(); + return pid; + } +}; diff --git a/js/dbusServices/org.gnome.Shell.Extensions.src.gresource.xml b/js/dbusServices/org.gnome.Shell.Extensions.src.gresource.xml new file mode 100644 index 0000000..5a7c087 --- /dev/null +++ b/js/dbusServices/org.gnome.Shell.Extensions.src.gresource.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<gresources> + <gresource prefix="/org/gnome/Shell/Extensions/js"> + <file>main.js</file> + <file>extensionsService.js</file> + <file>dbusService.js</file> + + <file>misc/config.js</file> + <file>misc/extensionUtils.js</file> + <file>misc/fileUtils.js</file> + <file>misc/params.js</file> + </gresource> + + <gresource prefix="/org/gnome/Shell/Extensions"> + <file>css/application.css</file> + <file>ui/extension-prefs-dialog.ui</file> + </gresource> +</gresources> diff --git a/js/dbusServices/org.gnome.Shell.Notifications.src.gresource.xml b/js/dbusServices/org.gnome.Shell.Notifications.src.gresource.xml new file mode 100644 index 0000000..ccf0e98 --- /dev/null +++ b/js/dbusServices/org.gnome.Shell.Notifications.src.gresource.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<gresources> + <gresource prefix="/org/gnome/Shell/Notifications/js"> + <file>main.js</file> + <file>notificationDaemon.js</file> + <file>dbusService.js</file> + + <file>misc/config.js</file> + <file>misc/fileUtils.js</file> + </gresource> +</gresources> diff --git a/js/dbusServices/org.gnome.Shell.Screencast.src.gresource.xml b/js/dbusServices/org.gnome.Shell.Screencast.src.gresource.xml new file mode 100644 index 0000000..e99b1ac --- /dev/null +++ b/js/dbusServices/org.gnome.Shell.Screencast.src.gresource.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<gresources> + <gresource prefix="/org/gnome/Shell/Screencast/js"> + <file>main.js</file> + <file>screencastService.js</file> + <file>dbusService.js</file> + + <file>misc/config.js</file> + <file>misc/fileUtils.js</file> + </gresource> +</gresources> diff --git a/js/dbusServices/screencast/main.js b/js/dbusServices/screencast/main.js new file mode 100644 index 0000000..4a24426 --- /dev/null +++ b/js/dbusServices/screencast/main.js @@ -0,0 +1,11 @@ +/* exported main */ + +const { DBusService } = imports.dbusService; +const { ScreencastService } = imports.screencastService; + +function main() { + const service = new DBusService( + 'org.gnome.Shell.Screencast', + new ScreencastService()); + service.run(); +} diff --git a/js/dbusServices/screencast/screencastService.js b/js/dbusServices/screencast/screencastService.js new file mode 100644 index 0000000..e980896 --- /dev/null +++ b/js/dbusServices/screencast/screencastService.js @@ -0,0 +1,467 @@ +// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- +/* exported ScreencastService */ + +imports.gi.versions.Gtk = '3.0'; + +const { Gio, GLib, Gst, Gtk } = imports.gi; + +const { loadInterfaceXML, loadSubInterfaceXML } = imports.misc.fileUtils; +const { ServiceImplementation } = imports.dbusService; + +const ScreencastIface = loadInterfaceXML('org.gnome.Shell.Screencast'); + +const IntrospectIface = loadInterfaceXML('org.gnome.Shell.Introspect'); +const IntrospectProxy = Gio.DBusProxy.makeProxyWrapper(IntrospectIface); + +const ScreenCastIface = loadSubInterfaceXML( + 'org.gnome.Mutter.ScreenCast', 'org.gnome.Mutter.ScreenCast'); +const ScreenCastSessionIface = loadSubInterfaceXML( + 'org.gnome.Mutter.ScreenCast.Session', 'org.gnome.Mutter.ScreenCast'); +const ScreenCastStreamIface = loadSubInterfaceXML( + 'org.gnome.Mutter.ScreenCast.Stream', 'org.gnome.Mutter.ScreenCast'); +const ScreenCastProxy = Gio.DBusProxy.makeProxyWrapper(ScreenCastIface); +const ScreenCastSessionProxy = Gio.DBusProxy.makeProxyWrapper(ScreenCastSessionIface); +const ScreenCastStreamProxy = Gio.DBusProxy.makeProxyWrapper(ScreenCastStreamIface); + +const DEFAULT_PIPELINE = 'vp8enc min_quantizer=13 max_quantizer=13 cpu-used=5 deadline=1000000 threads=%T ! queue ! webmmux'; +const DEFAULT_FRAMERATE = 30; +const DEFAULT_DRAW_CURSOR = true; + +const PipelineState = { + INIT: 0, + PLAYING: 1, + FLUSHING: 2, + STOPPED: 3, +}; + +const SessionState = { + INIT: 0, + ACTIVE: 1, + STOPPED: 2, +}; + +var Recorder = class { + constructor(sessionPath, x, y, width, height, filePath, options, + invocation, + onErrorCallback) { + this._startInvocation = invocation; + this._dbusConnection = invocation.get_connection(); + this._onErrorCallback = onErrorCallback; + this._stopInvocation = null; + + this._pipelineIsPlaying = false; + this._sessionIsActive = false; + + this._x = x; + this._y = y; + this._width = width; + this._height = height; + this._filePath = filePath; + + this._pipelineString = DEFAULT_PIPELINE; + this._framerate = DEFAULT_FRAMERATE; + this._drawCursor = DEFAULT_DRAW_CURSOR; + + this._applyOptions(options); + this._watchSender(invocation.get_sender()); + + this._initSession(sessionPath); + } + + _applyOptions(options) { + for (const option in options) + options[option] = options[option].deep_unpack(); + + if (options['pipeline'] !== undefined) + this._pipelineString = options['pipeline']; + if (options['framerate'] !== undefined) + this._framerate = options['framerate']; + if ('draw-cursor' in options) + this._drawCursor = options['draw-cursor']; + } + + _addRecentItem() { + const file = Gio.File.new_for_path(this._filePath); + Gtk.RecentManager.get_default().add_item(file.get_uri()); + } + + _watchSender(sender) { + this._nameWatchId = this._dbusConnection.watch_name( + sender, + Gio.BusNameWatcherFlags.NONE, + null, + this._senderVanished.bind(this)); + } + + _unwatchSender() { + if (this._nameWatchId !== 0) { + this._dbusConnection.unwatch_name(this._nameWatchId); + this._nameWatchId = 0; + } + } + + _senderVanished() { + this._unwatchSender(); + + this.stopRecording(null); + } + + _notifyStopped() { + this._unwatchSender(); + if (this._onStartedCallback) + this._onStartedCallback(this, false); + else if (this._onStoppedCallback) + this._onStoppedCallback(this); + else + this._onErrorCallback(this); + } + + _onSessionClosed() { + switch (this._pipelineState) { + case PipelineState.STOPPED: + break; + default: + this._pipeline.set_state(Gst.State.NULL); + log(`Unexpected pipeline state: ${this._pipelineState}`); + break; + } + this._notifyStopped(); + } + + _initSession(sessionPath) { + this._sessionProxy = new ScreenCastSessionProxy(Gio.DBus.session, + 'org.gnome.Mutter.ScreenCast', + sessionPath); + this._sessionProxy.connectSignal('Closed', this._onSessionClosed.bind(this)); + } + + _startPipeline(nodeId) { + this._ensurePipeline(nodeId); + + const bus = this._pipeline.get_bus(); + bus.add_watch(bus, this._onBusMessage.bind(this)); + + this._pipeline.set_state(Gst.State.PLAYING); + this._pipelineState = PipelineState.PLAYING; + + this._onStartedCallback(this, true); + this._onStartedCallback = null; + } + + startRecording(onStartedCallback) { + this._onStartedCallback = onStartedCallback; + + const [streamPath] = this._sessionProxy.RecordAreaSync( + this._x, this._y, + this._width, this._height, + { + 'is-recording': GLib.Variant.new('b', true), + 'cursor-mode': GLib.Variant.new('u', this._drawCursor ? 1 : 0), + }); + + this._streamProxy = new ScreenCastStreamProxy(Gio.DBus.session, + 'org.gnome.ScreenCast.Stream', + streamPath); + + this._streamProxy.connectSignal('PipeWireStreamAdded', + (proxy, sender, params) => { + const [nodeId] = params; + this._startPipeline(nodeId); + }); + this._sessionProxy.StartSync(); + this._sessionState = SessionState.ACTIVE; + } + + stopRecording(onStoppedCallback) { + this._pipelineState = PipelineState.FLUSHING; + this._onStoppedCallback = onStoppedCallback; + this._pipeline.send_event(Gst.Event.new_eos()); + } + + _stopSession() { + this._sessionProxy.StopSync(); + this._sessionState = SessionState.STOPPED; + } + + _onBusMessage(bus, message, _) { + switch (message.type) { + case Gst.MessageType.EOS: + this._pipeline.set_state(Gst.State.NULL); + this._addRecentItem(); + + switch (this._pipelineState) { + case PipelineState.FLUSHING: + this._pipelineState = PipelineState.STOPPED; + break; + default: + break; + } + + switch (this._sessionState) { + case SessionState.ACTIVE: + this._stopSession(); + break; + case SessionState.STOPPED: + this._notifyStopped(); + break; + default: + break; + } + + break; + default: + break; + } + return true; + } + + _substituteThreadCount(pipelineDescr) { + const numProcessors = GLib.get_num_processors(); + const numThreads = Math.min(Math.max(1, numProcessors), 64); + return pipelineDescr.replace(/%T/, numThreads); + } + + _ensurePipeline(nodeId) { + const framerate = this._framerate; + + let fullPipeline = ` + pipewiresrc path=${nodeId} + do-timestamp=true + keepalive-time=1000 + resend-last=true ! + video/x-raw,max-framerate=${framerate}/1 ! + videoconvert ! + ${this._pipelineString} ! + filesink location="${this._filePath}"`; + fullPipeline = this._substituteThreadCount(fullPipeline); + + this._pipeline = Gst.parse_launch_full(fullPipeline, + null, + Gst.ParseFlags.FATAL_ERRORS); + } +}; + +var ScreencastService = class extends ServiceImplementation { + constructor() { + super(ScreencastIface, '/org/gnome/Shell/Screencast'); + + Gst.init(null); + Gtk.init(null); + + this._recorders = new Map(); + this._senders = new Map(); + + this._lockdownSettings = new Gio.Settings({ + schema_id: 'org.gnome.desktop.lockdown', + }); + + this._proxy = new ScreenCastProxy(Gio.DBus.session, + 'org.gnome.Mutter.ScreenCast', + '/org/gnome/Mutter/ScreenCast'); + + this._introspectProxy = new IntrospectProxy(Gio.DBus.session, + 'org.gnome.Shell.Introspect', + '/org/gnome/Shell/Introspect'); + } + + _removeRecorder(sender) { + this._recorders.delete(sender); + if (this._recorders.size === 0) + this.release(); + } + + _addRecorder(sender, recorder) { + this._recorders.set(sender, recorder); + if (this._recorders.size === 1) + this.hold(); + } + + _getAbsolutePath(filename) { + if (GLib.path_is_absolute(filename)) + return filename; + + let videoDir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_VIDEOS); + if (!GLib.file_test(videoDir, GLib.FileTest.EXISTS)) + videoDir = GLib.get_home_dir(); + + return GLib.build_filenamev([videoDir, filename]); + } + + _generateFilePath(template) { + let filename = ''; + let escape = false; + + [...template].forEach(c => { + if (escape) { + switch (c) { + case '%': + filename += '%'; + break; + case 'd': { + const datetime = GLib.DateTime.new_now_local(); + const datestr = datetime.format('%0x'); + const datestrEscaped = datestr.replace(/\//g, '-'); + + filename += datestrEscaped; + break; + } + + case 't': { + const datetime = GLib.DateTime.new_now_local(); + const datestr = datetime.format('%0X'); + const datestrEscaped = datestr.replace(/\//g, ':'); + + filename += datestrEscaped; + break; + } + + default: + log(`Warning: Unknown escape ${c}`); + } + + escape = false; + } else if (c === '%') { + escape = true; + } else { + filename += c; + } + }); + + if (escape) + filename += '%'; + + return this._getAbsolutePath(filename); + } + + ScreencastAsync(params, invocation) { + let returnValue = [false, '']; + + if (this._lockdownSettings.get_boolean('disable-save-to-disk')) { + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + return; + } + + const sender = invocation.get_sender(); + + if (this._recorders.get(sender)) { + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + return; + } + + const [sessionPath] = this._proxy.CreateSessionSync({}); + + const [fileTemplate, options] = params; + const [screenWidth, screenHeight] = this._introspectProxy.ScreenSize; + const filePath = this._generateFilePath(fileTemplate); + + let recorder; + + try { + recorder = new Recorder( + sessionPath, + 0, 0, + screenWidth, screenHeight, + filePath, + options, + invocation, + _recorder => this._removeRecorder(sender)); + } catch (error) { + log(`Failed to create recorder: ${error.message}`); + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + return; + } + + this._addRecorder(sender, recorder); + + try { + recorder.startRecording( + (_, result) => { + if (result) { + returnValue = [true, filePath]; + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + } else { + this._removeRecorder(sender); + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + } + + }); + } catch (error) { + log(`Failed to start recorder: ${error.message}`); + this._removeRecorder(sender); + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + } + } + + ScreencastAreaAsync(params, invocation) { + let returnValue = [false, '']; + + if (this._lockdownSettings.get_boolean('disable-save-to-disk')) { + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + return; + } + + const sender = invocation.get_sender(); + + if (this._recorders.get(sender)) { + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + return; + } + + const [sessionPath] = this._proxy.CreateSessionSync({}); + + const [x, y, width, height, fileTemplate, options] = params; + const filePath = this._generateFilePath(fileTemplate); + + let recorder; + + try { + recorder = new Recorder( + sessionPath, + x, y, + width, height, + filePath, + options, + invocation, + _recorder => this._removeRecorder(sender)); + } catch (error) { + log(`Failed to create recorder: ${error.message}`); + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + return; + } + + this._addRecorder(sender, recorder); + + try { + recorder.startRecording( + (_, result) => { + if (result) { + returnValue = [true, filePath]; + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + } else { + this._removeRecorder(sender); + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + } + + }); + } catch (error) { + log(`Failed to start recorder: ${error.message}`); + this._removeRecorder(sender); + invocation.return_value(GLib.Variant.new('(bs)', returnValue)); + } + } + + StopScreencastAsync(params, invocation) { + const sender = invocation.get_sender(); + + const recorder = this._recorders.get(sender); + if (!recorder) { + invocation.return_value(GLib.Variant.new('(b)', [false])); + return; + } + + recorder.stopRecording(() => { + this._removeRecorder(sender); + invocation.return_value(GLib.Variant.new('(b)', [true])); + }); + } +}; |