-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathsearch-service.js
More file actions
321 lines (272 loc) · 10.1 KB
/
Copy pathsearch-service.js
File metadata and controls
321 lines (272 loc) · 10.1 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
// search-service.js
const { clipboard, Notification, shell, dialog } = require('electron');
const fs = require('fs');
const path = require('path');
const { execFile, spawn, exec } = require('child_process');
const os = require('os');
const app = require('electron').app;
class SearchService {
constructor(mainWindow, switchViewCallback) {
this.mainWindow = mainWindow;
this.switchView = switchViewCallback;
this.isWindows = process.platform === 'win32';
this.isMac = process.platform === 'darwin';
this.isLinux = process.platform === 'linux';
// Check for Linux dependencies on initialization
if (this.isLinux) {
this.checkLinuxDependencies();
}
}
/**
* Check if required Linux dependencies are installed
* and notify user if they're missing
*/
checkLinuxDependencies() {
exec('which xclip', (clipError, clipStdout) => {
if (clipError || !clipStdout) {
setTimeout(() => {
this.showNotification('Linux Dependency Missing',
'Please install xclip: sudo pacman -S xclip');
}, 3000);
}
});
}
/**
* Search for the currently selected text with auto-copy feature
* Approach:
* 1. Saves the current clipboard content
* 2. Gets selected text directly from X11 selection
* 3. Performs the search
* 4. Restores the original clipboard content
*/
async searchSelectedText() {
// Store the original clipboard content
const originalClipboardContent = clipboard.readText();
try {
// For Linux X11, try using xclip directly instead of simulating Ctrl+C
if (this.isLinux) {
const selectedText = await this.getX11Selection();
if (!selectedText) {
this.showNotification('No Text Selected',
'Please select text before searching or copy manually with Ctrl+C first.');
return;
}
// Perform the search with the selected text
this.performSearch(selectedText);
// Restore the original clipboard content
setTimeout(() => {
clipboard.writeText(originalClipboardContent);
}, 1000);
return;
}
// For non-Linux
clipboard.writeText('');
await new Promise(resolve => setTimeout(resolve, 50));
// Simulate Ctrl+C to copy the selected text
await this.copySelectedText();
const readDelay = 400;
await new Promise(resolve => setTimeout(resolve, readDelay));
const selectedText = clipboard.readText().trim();
console.log('Copied text:', selectedText);
if (!selectedText) {
this.showNotification('No text selected', 'Please select text before searching.');
this.showNotification('Tip', 'Try selecting text and copying it manually with Ctrl+C first.');
return;
}
// Perform the search
this.performSearch(selectedText);
setTimeout(() => {
clipboard.writeText(originalClipboardContent);
}, 1000);
} catch (error) {
console.error('Error during auto-copy search:', error);
this.showNotification('Error', 'Failed to get selected text.');
if (this.isLinux) {
this.showNotification('Linux Tip',
'Try copying text manually with Ctrl+C before using the shortcut.');
} else {
this.showNotification('Tip',
'Try copying text manually with Ctrl+C and then using the search shortcut.');
}
clipboard.writeText(originalClipboardContent);
}
}
//Get selected text directly from X11 selection
getX11Selection() {
return new Promise((resolve) => {
exec('xclip -o -selection primary', { timeout: 1000 }, (primaryError, primaryText) => {
if (!primaryError && primaryText && primaryText.trim()) {
console.log('Got text from primary selection');
resolve(primaryText.trim());
} else {
exec('xclip -o -selection clipboard', { timeout: 1000 }, (clipboardError, clipboardText) => {
if (!clipboardError && clipboardText && clipboardText.trim()) {
console.log('Got text from clipboard selection');
resolve(clipboardText.trim());
} else {
this.simulateCtrlC().then(() => {
setTimeout(() => {
const clipText = clipboard.readText().trim();
console.log('After Ctrl+C simulation, got text:', clipText ? 'yes' : 'no');
resolve(clipText);
}, 800);
});
}
});
}
});
});
}
/**
* Uses multiple approaches in sequence to maximize chances of success
*/
simulateCtrlC() {
return new Promise((resolve) => {
exec('xdotool key --clearmodifiers ctrl+c', (error1) => {
if (error1) {
console.log('First xdotool attempt failed, trying alternative');
exec('xdotool keydown ctrl key c keyup ctrl', (error2) => {
if (error2) {
console.log('All xdotool attempts failed');
}
resolve();
});
} else {
resolve();
}
});
});
}
/**
* Modified: Search with a custom prefix
* Uses direct X11 selection for Linux systems
*/
async searchWithCustomPrefix() {
// Store the original clipboard content
const originalClipboardContent = clipboard.readText();
try {
let selectedText;
// For Linux X11, use direct selection method
if (this.isLinux) {
selectedText = await this.getX11Selection();
} else {
// For other platforms, use the original approach
clipboard.writeText('');
await new Promise(resolve => setTimeout(resolve, 50));
// Simulate Ctrl+C to copy the selected text
await this.copySelectedText();
// Increased delay to ensure the clipboard is updated
await new Promise(resolve => setTimeout(resolve, 400));
// Get the newly copied text
selectedText = clipboard.readText().trim();
}
// If no text was selected
if (!selectedText) {
if (this.isLinux) {
this.showNotification('No Text Selected',
'Please select text before searching or copy manually with Ctrl+C first.');
} else {
this.showNotification('No text selected', 'Please select text before searching.');
}
this.showNotification('Tip', 'Try selecting text and copying it manually with Ctrl+C first.');
// Restore the original clipboard content
clipboard.writeText(originalClipboardContent);
return;
}
// The actual prefix selection dialog is now handled by main.js through showPrefixSearchWindow()
} catch (error) {
console.error('Error during custom prefix search:', error);
this.showNotification('Error', 'Failed to get selected text.');
// Restore the original clipboard content
clipboard.writeText(originalClipboardContent);
}
}
/**
* Simulate keyboard shortcut to copy text
* Kept for non-Linux platforms and as a fallback for Linux
*/
async copySelectedText() {
return new Promise(async (resolve, reject) => {
try {
if (this.isWindows) {
// Try multiple Windows approaches for better reliability
try {
// More robust PowerShell approach
await new Promise((innerResolve, innerReject) => {
exec('powershell -WindowStyle Hidden -command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait(\'^c\')"',
{ windowsHide: true, timeout: 1500 },
(error) => {
if (error) {
console.log('Error with System.Windows.Forms approach:', error);
innerReject(error);
} else {
innerResolve();
}
}
);
});
} catch (err) {
// Fallback to original method if the improved one fails
exec('powershell -WindowStyle Hidden -command "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys(\'^c\')"',
{ windowsHide: true },
(error) => {
if (error) {
console.error('Fallback copy method error:', error);
}
}
);
}
} else if (this.isMac) {
// Improved AppleScript for macOS
exec('osascript -e \'tell application "System Events" to keystroke "c" using {command down}\'',
(error) => {
if (error) {
console.error('Error simulating Cmd+C:', error);
}
}
);
} else {
this.simulateCtrlC();
}
// Delay to ensure clipboard is updated
await new Promise(resolve => setTimeout(resolve, 400));
resolve();
} catch (err) {
console.error('Unexpected error in copySelectedText:', err);
resolve();
}
});
}
/**
* Perform search with the given text
* @param {string} searchText - Text to search for
* @param {string} [prefix=''] - Optional prefix for search query (e.g., 'explain ', 'meaning of ')
*/
performSearch(searchText, prefix = '') {
if (!searchText?.trim()) return;
// Format search URL
const formattedText = prefix + searchText.trim();
const searchUrl = `https://www.perplexity.ai/search?q=${encodeURIComponent(formattedText)}`;
this.switchView(searchUrl);
// Show the main window if it's hidden
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
if (!this.mainWindow.isVisible()) {
this.mainWindow.show();
}
this.mainWindow.focus();
}
}
/**
* Show a notification to the user
* @param {string} title - Notification title
* @param {string} body - Notification body text
*/
showNotification(title, body) {
const notification = new Notification({
title,
body
});
notification.show();
}
}
module.exports = SearchService;