Debian Codegraph @

shared/gnome-extension/extension.js

raw
1 import Gio from 'gi://Gio';
2 import GLib from 'gi://GLib';
3 import Meta from 'gi://Meta';
4 import Shell from 'gi://Shell';
5 import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
6
7 const SERVICE_NAME = 'com.github.hluk.copyq.GnomeClipboard';
8 const OBJECT_PATH = '/com/github/hluk/copyq/GnomeClipboard';
9 const INTERFACE_NAME = 'com.github.hluk.CopyQ.GnomeClipboard1';
10 const CLIENT_OBJECT_PATH = '/com/github/hluk/copyq/GnomeClipboardClient';
11 const CLIENT_INTERFACE_NAME = 'com.github.hluk.CopyQ.GnomeClipboardClient1';
12 const CLIPBOARD_TYPE_CLIPBOARD = 0;
13 const CLIPBOARD_TYPE_PRIMARY = 1;
14 const CLIPBOARD_TYPE_BOTH = 2;
15 const DEBUG = GLib.getenv('COPYQ_GNOME_EXTENSION_DEBUG') === '1';
16
17 const INTERFACE_XML = `<node>
18 <interface name="${INTERFACE_NAME}">
19 <method name="RegisterClipboardClient">
20 <arg type="i" name="clipboardTypes" direction="in"/>
21 </method>
22 <method name="UnregisterClipboardClient"/>
23 <method name="SetClipboardData">
24 <arg type="i" name="clipboardType" direction="in"/>
25 <arg type="s" name="format" direction="in"/>
26 <arg type="v" name="value" direction="in"/>
27 </method>
28 <method name="GetClipboardData">
29 <arg type="i" name="clipboardType" direction="in"/>
30 <arg type="as" name="formats" direction="in"/>
31 <arg type="a{sv}" name="data" direction="out"/>
32 </method>
33 <method name="GetClipboardFormats">
34 <arg type="i" name="clipboardType" direction="in"/>
35 <arg type="as" name="formats" direction="out"/>
36 </method>
37 </interface>
38 </node>`;
39
40 function debug(message) {
41 if (DEBUG)
42 log(`[copyq-clipboard] ${message}`);
43 }
44
45 function stringToBytes(text) {
46 return new TextEncoder().encode(text);
47 }
48
49 function toBytes(value) {
50 if (value instanceof GLib.Variant) {
51 if (value.is_of_type(new GLib.VariantType('ay')))
52 return value.deepUnpack();
53 return toBytes(value.deepUnpack());
54 }
55 if (value instanceof GLib.Bytes)
56 return value.toArray();
57 if (value instanceof Uint8Array)
58 return value;
59 if (Array.isArray(value))
60 return Uint8Array.from(value);
61 if (typeof value === 'string')
62 return stringToBytes(value);
63 return null;
64 }
65
66 function toDataVariant(value) {
67 const bytes = toBytes(value);
68 return bytes ? new GLib.Variant('ay', bytes) : null;
69 }
70
71 function metaSelectionTypeFromClipboardType(clipboardType) {
72 const enumType = Meta.SelectionType ?? {};
73 const primary = enumType.PRIMARY ?? enumType.SELECTION_PRIMARY ?? 0;
74 const clipboard = enumType.CLIPBOARD ?? enumType.SELECTION_CLIPBOARD ?? 1;
75 return clipboardType === CLIPBOARD_TYPE_PRIMARY ? primary : clipboard;
76 }
77
78 function supportsClipboardType(clipboardTypes, clipboardType) {
79 const types = Number(clipboardTypes);
80 const type = Number(clipboardType);
81 return types === CLIPBOARD_TYPE_BOTH || types === type;
82 }
83
84 export default class CopyqClipboardExtension extends Extension {
85 enable() {
86 this._clients = new Map();
87 this._providedDataByType = {
88 [CLIPBOARD_TYPE_CLIPBOARD]: {},
89 [CLIPBOARD_TYPE_PRIMARY]: {},
90 };
91
92 this._setupListener();
93
94 this._dbusConnection = Gio.DBus.session;
95 this._dbusNodeInfo = Gio.DBusNodeInfo.new_for_xml(INTERFACE_XML);
96 this._dbusRegistrationId = this._dbusConnection.register_object(
97 OBJECT_PATH,
98 this._dbusNodeInfo.interfaces[0],
99 this._handleMethodCall.bind(this),
100 null,
101 null
102 );
103 this._dbusNameOwnerId = Gio.bus_own_name_on_connection(
104 this._dbusConnection,
105 SERVICE_NAME,
106 Gio.BusNameOwnerFlags.REPLACE,
107 null,
108 null
109 );
110 }
111
112 disable() {
113 if (this._selectionOwnerChangedId && this.selection) {
114 this.selection.disconnect(this._selectionOwnerChangedId);
115 this._selectionOwnerChangedId = 0;
116 }
117
118 if (this._dbusRegistrationId) {
119 this._dbusConnection.unregister_object(this._dbusRegistrationId);
120 this._dbusRegistrationId = 0;
121 }
122 if (this._dbusNameOwnerId) {
123 Gio.bus_unown_name(this._dbusNameOwnerId);
124 this._dbusNameOwnerId = 0;
125 }
126
127 this._clients?.clear();
128 this._clients = null;
129 this._providedDataByType = null;
130 this.selection = null;
131 this._dbusConnection = null;
132 this._dbusNodeInfo = null;
133 }
134
135 _setupListener() {
136 try {
137 const metaDisplay = Shell.Global.get().get_display();
138 const selection = metaDisplay?.get_selection?.();
139 if (!selection) {
140 debug('Failed to set up owner-changed listener: selection unavailable');
141 return;
142 }
143 debug('Setting up Shell selection owner-changed listener');
144 this._setupSelectionTracking(selection);
145 } catch (error) {
146 debug(`Failed to set up owner-changed listener: ${error}`);
147 }
148 }
149
150 _setupSelectionTracking(selection) {
151 this.selection = selection;
152 this._selectionOwnerChangedId = selection.connect('owner-changed',
153 (_selection, selectionType, _selectionSource) => {
154 this._onSelectionChange(selectionType);
155 });
156 }
157
158 _clipboardTypeFromSelectionType(selectionType) {
159 const enumType = Meta.SelectionType ?? {};
160 const primary = enumType.PRIMARY ?? enumType.SELECTION_PRIMARY ?? 0;
161 const clipboard = enumType.CLIPBOARD ?? enumType.SELECTION_CLIPBOARD ?? 1;
162 const value = Number(selectionType);
163 const text = String(selectionType).toLowerCase();
164 if (value === primary || text.includes('primary'))
165 return CLIPBOARD_TYPE_PRIMARY;
166 if (value === clipboard || text.includes('clipboard'))
167 return CLIPBOARD_TYPE_CLIPBOARD;
168 return CLIPBOARD_TYPE_CLIPBOARD;
169 }
170
171 _onSelectionChange(selectionType) {
172 const clipboardType = this._clipboardTypeFromSelectionType(selectionType);
173 debug(`Selection owner changed: selectionType=${selectionType}, clipboardType=${clipboardType}`);
174 this._notifyClients(clipboardType);
175 }
176
177 _handleMethodCall(_connection, sender, _objectPath, _interfaceName, methodName, parameters, invocation) {
178 if (methodName === 'RegisterClipboardClient') {
179 const [clipboardTypes] = parameters.deepUnpack();
180 const types = Number(clipboardTypes);
181 this._clients.set(sender, types);
182 debug(`Registered client ${sender} with clipboardTypes=${types}`);
183 invocation.return_value(null);
184 return;
185 }
186
187 if (methodName === 'UnregisterClipboardClient') {
188 this._clients.delete(sender);
189 debug(`Unregistered client ${sender}`);
190 invocation.return_value(null);
191 return;
192 }
193
194 if (methodName === 'SetClipboardData') {
195 const [clipboardType, format, value] = parameters.deepUnpack();
196 const type = Number(clipboardType);
197 const normalizedValue = toDataVariant(value);
198 if (!normalizedValue) {
199 debug(`SetClipboardData ignored for clipboardType=${type}, format=${format}: unsupported value`);
200 invocation.return_value(null);
201 return;
202 }
203 this._providedDataByType[type][format] = normalizedValue;
204 this._setClipboardData(type, format, normalizedValue);
205 debug(`SetClipboardData called for clipboardType=${type}, format=${format}`);
206 invocation.return_value(null);
207 return;
208 }
209
210 if (methodName === 'GetClipboardData') {
211 const [clipboardType, formats] = parameters.deepUnpack();
212 const requestedFormats = new Set(Array.isArray(formats) ? formats : []);
213 this._readClipboardData(clipboardType, requestedFormats, dataMap => {
214 invocation.return_value(new GLib.Variant('(a{sv})', [dataMap]));
215 });
216 return;
217 }
218
219 if (methodName === 'GetClipboardFormats') {
220 const [clipboardType] = parameters.deepUnpack();
221 const formats = this._getClipboardFormats(clipboardType);
222 invocation.return_value(new GLib.Variant('(as)', [formats]));
223 }
224 }
225
226 _notifyClients(clipboardType) {
227 if (!this._clients || this._clients.size === 0)
228 return;
229 debug(`Notifying clients for clipboardType=${clipboardType}, clients=${this._clients.size}`);
230
231 for (const [sender, clipboardTypes] of this._clients.entries()) {
232 if (!supportsClipboardType(clipboardTypes, clipboardType))
233 continue;
234 this._dbusConnection.call(
235 sender,
236 CLIENT_OBJECT_PATH,
237 CLIENT_INTERFACE_NAME,
238 'ClipboardChanged',
239 new GLib.Variant('(i)', [clipboardType]),
240 null,
241 Gio.DBusCallFlags.NO_AUTO_START,
242 1000,
243 null,
244 (_conn, result) => {
245 try {
246 _conn.call_finish(result);
247 } catch (error) {
248 log(`[copyq-clipboard] Broadcast failed for ${sender}: ${error}`);
249 this._clients.delete(sender);
250 }
251 }
252 );
253 }
254 }
255
256 _readClipboardData(clipboardType, requestedFormats, onDone) {
257 if (!this.selection) {
258 const fallback = this._providedDataByType[clipboardType] ?? {};
259 onDone({...fallback});
260 return;
261 }
262
263 const selectionType = metaSelectionTypeFromClipboardType(clipboardType);
264 const advertisedFormats = this.selection.get_mimetypes(selectionType) ?? [];
265 const formats = requestedFormats && requestedFormats.size > 0
266 ? [...requestedFormats]
267 : advertisedFormats;
268
269 if (formats.length === 0) {
270 onDone({});
271 return;
272 }
273
274 const data = {};
275 let pending = formats.length;
276 const complete = () => {
277 pending--;
278 if (pending !== 0)
279 return;
280 for (const format of formats) {
281 if (!Object.prototype.hasOwnProperty.call(data, format)
282 && Object.prototype.hasOwnProperty.call(this._providedDataByType[clipboardType], format))
283 {
284 data[format] = this._providedDataByType[clipboardType][format];
285 }
286 }
287 onDone(data);
288 };
289
290 for (const format of formats) {
291 const output = Gio.MemoryOutputStream.new_resizable();
292 this.selection.transfer_async(
293 selectionType,
294 format,
295 -1,
296 output,
297 null,
298 (_selection, result) => {
299 try {
300 this.selection.transfer_finish(result);
301 const bytes = output.steal_as_bytes()?.toArray?.() ?? [];
302 if (bytes.length > 0)
303 data[format] = new GLib.Variant('ay', Uint8Array.from(bytes));
304 } catch (_error) {
305 // Ignore unavailable format and keep fallback behavior.
306 }
307 complete();
308 });
309 }
310 }
311
312 _getClipboardFormats(clipboardType) {
313 const provided = Object.keys(this._providedDataByType[clipboardType] ?? {});
314 if (!this.selection)
315 return provided;
316
317 const selectionType = metaSelectionTypeFromClipboardType(clipboardType);
318 const selectionFormats = this.selection.get_mimetypes(selectionType) ?? [];
319 const all = new Set([...selectionFormats, ...provided]);
320 return [...all];
321 }
322
323 _setClipboardData(clipboardType, format, value) {
324 if (!this.selection)
325 this._setupListener();
326
327 if (!this.selection) {
328 debug(`Failed to set clipboard content: Meta selection unavailable for clipboardType=${clipboardType}`);
329 return;
330 }
331
332 const bytes = toBytes(value);
333 if (!bytes)
334 return;
335
336 try {
337 const source = Meta.SelectionSourceMemory.new(format, GLib.Bytes.new(bytes));
338 this.selection.set_owner(metaSelectionTypeFromClipboardType(clipboardType), source);
339 debug(`Set clipboard content using Meta selection source for clipboardType=${clipboardType} format=${format}`);
340 } catch (error) {
341 debug(`Failed to set clipboard content using Meta selection source: ${error}`);
342 }
343 }
344 }