-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathclipboard-manager.ts
More file actions
411 lines (364 loc) · 13.4 KB
/
Copy pathclipboard-manager.ts
File metadata and controls
411 lines (364 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import type Gio from "gi://Gio";
import Meta from "gi://Meta";
import Shell from "gi://Shell";
import St from "gi://St";
import { calculateClipboardMetadata } from "../../utils/clipboard-utils.js";
import { logger } from "../../utils/logger.js";
import { SignalRegistry } from "../../utils/signal-registry.js";
import { BinaryDataStore } from "./binary-data-store.js";
import { createHandlers } from "./handlers/index.js";
import type { ClipboardContentHandler } from "./handlers/types.js";
import type { BufferLike, ClipboardEvent } from "./types.js";
export class VicinaeClipboardManager {
private eventListeners: ((event: ClipboardEvent) => void)[] = [];
private contentHandlers: ClipboardContentHandler[] = [];
private binaryStore = new BinaryDataStore();
private currentContent: string = "";
private clipboard: St.Clipboard | null = null;
private selection: Meta.Selection | null = null;
private signals = new SignalRegistry();
private settings: Gio.Settings | null = null;
private isMonitoring = false;
constructor() {
this.contentHandlers = createHandlers();
this.clipboard = St.Clipboard.get_default();
this.selection = Shell.Global.get().get_display().get_selection();
if (!this.selection) {
logger.error(
"Failed to get selection instance in clipboard manager",
);
}
}
enable() {
if (!this.isMonitoring) {
this.isMonitoring = true;
this.setupClipboardMonitoring();
}
}
disable() {
if (this.isMonitoring) {
this.signals.disconnectAll();
this.isMonitoring = false;
logger.info("Clipboard monitoring disabled");
}
}
setSettings(settings: Gio.Settings): void {
this.settings = settings;
logger.info("Settings set in clipboard manager from external source");
try {
const blockedApps = this.settings.get_strv("blocked-applications");
logger.debug(
`Current blocked applications: [${blockedApps.join(", ")}]`,
);
} catch (err) {
logger.error(
"Error reading blocked applications from settings",
err,
);
}
}
updateSettings(settings: Gio.Settings): void {
this.settings = settings;
logger.info("Settings updated in clipboard manager");
try {
const blockedApps = this.settings.get_strv("blocked-applications");
logger.debug(
`Updated blocked applications: [${blockedApps.join(", ")}]`,
);
} catch (err) {
logger.error(
"Error reading updated blocked applications from settings",
err,
);
}
}
private isApplicationBlocked(sourceApp: string): boolean {
if (!this.settings) {
logger.warn(
"No settings available in clipboard manager - blocking logic disabled",
);
return false; // If no settings, don't block anything
}
try {
const blockedApps = this.settings.get_strv("blocked-applications");
logger.debug(
`Checking if ${sourceApp} is blocked. Blocked apps list: [${blockedApps.join(
", ",
)}]`,
);
const isBlocked = blockedApps.some(
(blockedApp: string) =>
sourceApp
.toLowerCase()
.includes(blockedApp.toLowerCase()) ||
blockedApp.toLowerCase().includes(sourceApp.toLowerCase()),
);
if (isBlocked) {
logger.debug(
`Application ${sourceApp} is blocked from clipboard access`,
);
} else {
logger.debug(
`Application ${sourceApp} is NOT blocked (not in blocked apps list)`,
);
}
return isBlocked;
} catch (error) {
logger.error(
"Error checking blocked applications in clipboard manager",
error,
);
return false;
}
}
private shouldBlockContentType(
contentType: string,
mimeType: string,
): boolean {
return contentType === "text" || mimeType.startsWith("text/");
}
private setupClipboardMonitoring() {
try {
if (this.selection) {
const selectionId = this.selection.connect(
"owner-changed",
(_: unknown, selectionType: Meta.SelectionType) => {
this.onSelectionOwnerChanged(_, selectionType);
},
);
this.signals.add(() => this.selection?.disconnect(selectionId));
this.queryClipboard();
logger.info(
"Clipboard monitoring set up successfully using selection listener",
);
}
} catch (error) {
logger.error("Error setting up clipboard monitoring", error);
}
}
private onSelectionOwnerChanged(
_: unknown,
selectionType: Meta.SelectionType,
) {
if (selectionType === Meta.SelectionType.SELECTION_CLIPBOARD) {
this.queryClipboard();
}
}
private queryClipboard() {
if (!this.clipboard) return;
try {
const mimeTypes = this.clipboard.get_mimetypes(
St.ClipboardType.CLIPBOARD,
);
const handler = this.contentHandlers
.slice()
.sort((a, b) => b.priority - a.priority)
.find((h) => h.matchesMimeTypes(mimeTypes));
if (handler) {
const context =
handler.priority >= 1
? {
storeBinaryData: (
marker: string,
data: unknown,
mimeType: string,
) => {
this.binaryStore.set(
marker,
data as BufferLike,
mimeType,
);
logger.debug(`Stored binary data: ${marker}`);
},
}
: undefined;
handler.capture(
this.clipboard,
(content) =>
this.processClipboardContent(content, "system"),
context,
);
}
} catch (error) {
logger.error("Error querying clipboard", error);
}
}
getBinaryData(
marker: string,
): { data: BufferLike; mimeType: string } | null {
return this.binaryStore.get(marker);
}
clearBinaryDataStore(marker?: string): void {
if (marker) {
logger.debug(
`clearBinaryDataStore: clearing marker "${marker}", store size: ${this.binaryStore.size}`,
);
this.binaryStore.delete(marker);
} else {
logger.debug(
`clearBinaryDataStore: clearing all ${this.binaryStore.size} entries`,
);
this.binaryStore.clear();
}
}
private processClipboardContent(
text: string,
source: "user" | "system" | "image",
) {
if (!text || text === this.currentContent) {
if (this.binaryStore.has(text)) {
this.binaryStore.delete(text);
}
return;
}
this.currentContent = text;
this.emitClipboardEvent(text, source);
}
// Method to emit clipboard change events
private emitClipboardEvent(
content: string | Uint8Array,
source: "user" | "system" | "image" = "user",
mimeType?: string,
) {
// Convert content to string for the event, handling binary data
let contentString: string;
let contentType: "text" | "image" = "text";
if (content instanceof Uint8Array) {
// For binary data, create a marker similar to how we handle images
if (mimeType?.startsWith("image/")) {
contentType = "image";
contentString = `[BINARY_IMAGE:${mimeType}:${content.length}]`;
} else {
contentString = `[BINARY_DATA:${mimeType}:${content.length}]`;
}
} else {
contentString = content;
contentType = source === "image" ? "image" : "text";
}
const event: ClipboardEvent = {
type: "clipboard-changed",
content: contentString,
timestamp: Date.now(),
source,
contentType,
};
// Get comprehensive metadata using the utility function
const metadata = calculateClipboardMetadata(event);
// Check blocking status for logging purposes
const isBlocked = this.isApplicationBlocked(metadata.sourceApp);
const shouldBlock =
isBlocked &&
this.shouldBlockContentType(event.contentType, metadata.mimeType);
logger.debug("🎯 CLIPBOARD EVENT EMITTED", {
type: event.type,
content:
contentString.length > 100
? `${contentString.substring(0, 100)}...`
: contentString,
contentLength:
content instanceof Uint8Array
? content.length
: contentString.length,
originalContentType:
content instanceof Uint8Array ? "binary" : "string",
timestamp: new Date(event.timestamp).toISOString(),
source: event.source,
listeners: this.eventListeners.length,
mimeType: metadata.mimeType,
contentType: event.contentType,
sourceApp: metadata.sourceApp,
isBlocked: isBlocked,
shouldBlock: shouldBlock,
note: shouldBlock
? "⚠️ This event will be blocked by clipboard manager"
: "✅ Event will be processed normally",
});
if (shouldBlock) {
logger.debug(
`🚫 Clipboard access blocked for application: ${metadata.sourceApp} (${event.contentType}) - Event not forwarded to listeners`,
);
return;
}
this.eventListeners.forEach((listener) => {
try {
listener(event);
} catch (error) {
logger.error("❌ Error in clipboard event listener", error);
}
});
}
onClipboardChange(listener: (event: ClipboardEvent) => void): void {
this.eventListeners.push(listener);
logger.debug("👂 Clipboard change listener added");
}
removeClipboardListener(listener: (event: ClipboardEvent) => void): void {
const index = this.eventListeners.indexOf(listener);
if (index > -1) {
this.eventListeners.splice(index, 1);
logger.debug("Clipboard change listener removed");
}
}
getCurrentContent(): string {
return this.currentContent;
}
setContent(content: string): void {
if (!this.clipboard) return;
try {
const handler = this.contentHandlers
.slice()
.sort((a, b) => b.priority - a.priority)
.find((h) => h.matchesContent(content));
if (handler?.set(this.clipboard, content)) {
this.currentContent = content;
this.emitClipboardEvent(content, "user");
}
} catch (error) {
logger.error("Error setting clipboard content", error);
}
}
setContentBinary(data: Uint8Array, mimeType: string): void {
if (this.clipboard) {
try {
logger.debug(
`Setting binary clipboard content: ${mimeType}, ${data.length} bytes`,
);
this.clipboard.set_content(
St.ClipboardType.CLIPBOARD,
mimeType,
data,
);
this.clipboard.set_content(
St.ClipboardType.PRIMARY,
mimeType,
data,
);
this.emitClipboardEvent(data, "user", mimeType);
logger.debug(
`Binary clipboard content set successfully for ${mimeType}`,
);
} catch (error) {
logger.error("Error setting binary clipboard content", error);
}
} else {
logger.error("Clipboard not available for setContentBinary");
}
}
triggerClipboardChange(
content: string,
source: "user" | "system" | "image" = "user",
): void {
this.emitClipboardEvent(content, source);
}
destroy(): void {
this.disable();
this.eventListeners = [];
this.currentContent = "";
logger.debug(
`destroy: clearing binary store with ${this.binaryStore.size} entries`,
);
this.binaryStore.clear();
this.clipboard = null;
this.selection = null;
logger.info("Clipboard manager destroyed");
}
}