-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
338 lines (300 loc) · 9.86 KB
/
extension.js
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
/* extension.js
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
// Based on the example provided by GNOME Shell documentation:
// https://gjs.guide/extensions/topics/search-provider.html
import St from "gi://St";
import Gda from "gi://Gda";
import GLib from "gi://GLib";
import Gio from "gi://Gio";
import { Extension } from "resource:///org/gnome/shell/extensions/extension.js";
import * as Main from "resource:///org/gnome/shell/ui/main.js";
/**
* History entry
* @typedef {Object} HistoryEntry
* @property {string} uri - The URI of the history entry
* @property {string} title - The title of the history entry
* @property {string} remote - The remote of the history entry
* @property {string} remoteType - The remote of the history entry
*/
class SearchProvider {
constructor(extension) {
console.debug("✅ SearchProvider starts");
this._extension = extension;
/** @type {HistoryEntry[]} */
this._historyEntries = [];
}
/**
* The application of the provider.
*
* Applications will return a `Gio.AppInfo` representing themselves.
* Extensions will usually return `null`.
*
* @type {Gio.AppInfo}
*/
get appInfo() {
return null;
}
/**
* Whether the provider offers detailed results.
*
* Applications will return `true` if they have a way to display more
* detailed or complete results. Extensions will usually return `false`.
*
* @type {boolean}
*/
get canLaunchSearch() {
return false;
}
/**
* The unique ID of the provider.
*
* Applications will return their application ID. Extensions will usually
* return their UUID.
*
* @type {string}
*/
get id() {
return this._extension.uuid;
}
/**
* Launch the search result.
*
* This method is called when a search provider result is activated.
*
* @param {string} result - The result identifier
* @param {string[]} terms - The search terms
*/
activateResult(result, terms) {
console.debug(`activateResult(${result}, [${terms}])`);
GLib.spawn_command_line_async(`code --folder-uri ${result}`);
}
/**
* Launch the search provider.
*
* This method is called when a search provider is activated. A provider can
* only be activated if the `appInfo` property holds a valid `Gio.AppInfo`
* and the `canLaunchSearch` property is `true`.
*
* Applications will typically open a window to display more detailed or
* complete results.
*
* @param {string[]} terms - The search terms
*/
launchSearch(terms) {
console.debug(`launchSearch([${terms}])`);
}
/**
* Create a result object.
*
* This method is called to create an actor to represent a search result.
*
* Implementations may return any `Clutter.Actor` to serve as the display
* result, or `null` for the default implementation.
*
* @param {ResultMeta} meta - A result metadata object
* @returns {Clutter.Actor|null} An actor for the result
*/
createResultObject(meta) {
console.debug(`createResultObject(${meta.id})`);
return null;
}
/**
* Get result metadata.
*
* This method is called to get a `ResultMeta` for each identifier.
*
* If @cancellable is triggered, this method should throw an error.
*
* @async
* @param {string[]} results - The result identifiers
* @param {Gio.Cancellable} cancellable - A cancellable for the operation
* @returns {Promise<ResultMeta[]>} A list of result metadata objects
*/
async getResultMetas(results, cancellable) {
console.debug(`getResultMetas([${results}])`);
const { scaleFactor } = St.ThemeContext.get_for_stage(global.stage);
return new Promise((resolve, reject) => {
const cancelledId = cancellable.connect(() =>
reject(Error("Operation Cancelled"))
);
const resultMetas = [];
for (const identifier of results) {
const historyEntry = this._historyEntries.find(
(entry) => entry.uri === identifier
);
if (!historyEntry) {
continue;
}
const meta = {
id: identifier,
name: historyEntry.title,
description: historyEntry.uri,
clipboardText: historyEntry.uri,
createIcon: (size) => {
return new St.Icon({
icon_name: "dialog-information",
width: size * scaleFactor,
height: size * scaleFactor,
});
},
};
resultMetas.push(meta);
}
cancellable.disconnect(cancelledId);
if (!cancellable.is_cancelled()) resolve(resultMetas);
});
}
/**
* Get the history entries.
*
* @returns {Promise<HistoryEntry[]>} The history entries
*/
async _getHistoryEntries(searchTerms) {
console.debug(`_getHistoryEntries([${searchTerms}])`);
const globalStorageDir =
GLib.get_home_dir() + "/.config/Code/User/globalStorage";
// run a sqlite query to get the history entries
let conn;
try {
conn = conn = new Gda.Connection({
provider: Gda.Config.get_provider("SQLite"),
cnc_string: `DB_DIR=${globalStorageDir};DB_NAME=state.vscdb`,
});
conn.open();
} catch (error) {
console.error(error);
return [];
}
// empty cached history entries
this._historyEntries.length = 0;
const dataModel = conn.execute_select_command(
"SELECT value FROM ItemTable WHERE key = 'history.recentlyOpenedPathsList'"
);
const iter = dataModel.create_iter();
if (!iter.move_next()) return [];
const result = JSON.parse(iter.get_value_at(0).to_string(0));
conn.close();
while (result.entries.length > 0) {
const entry = result.entries.shift();
if ("folderUri" in entry) {
let include = false;
for (const term of searchTerms) {
if ('label' in entry && entry.label.includes(term)) {
include = true;
break;
}
if (entry.folderUri.includes(term)) {
include = true;
break;
}
}
if (include) {
this._historyEntries.push({
uri: entry.folderUri,
title: entry?.label || entry.folderUri,
remote: entry?.remoteAuthority || "local",
remoteType: entry.remoteAuthority ? "remote" : "local",
});
}
}
}
return this._historyEntries;
}
/**
* Initiate a new search.
*
* This method is called to start a new search and should return a list of
* unique identifiers for the results.
*
* If @cancellable is triggered, this method should throw an error.
*
* @async
* @param {string[]} terms - The search terms
* @param {Gio.Cancellable} cancellable - A cancellable for the operation
* @returns {Promise<string[]>} A list of result identifiers
*/
getInitialResultSet(terms, cancellable) {
console.debug(`getInitialResultSet([${terms}])`);
return new Promise((resolve, reject) => {
const cancelledId = cancellable.connect(() =>
reject(Error("Search Cancelled"))
);
this._getHistoryEntries(terms)
.then((entries) => {
const identifiers = entries.map((entry) => entry.uri);
cancellable.disconnect(cancelledId);
if (!cancellable.is_cancelled()) resolve(identifiers);
})
.catch((_error) => {
console.error(_error);
cancellable.disconnect(cancelledId);
if (!cancellable.is_cancelled()) resolve([]);
});
});
}
/**
* Refine the current search.
*
* This method is called to refine the current search results with
* expanded terms and should return a subset of the original result set.
*
* Implementations may use this method to refine the search results more
* efficiently than running a new search, or simply pass the terms to the
* implementation of `getInitialResultSet()`.
*
* If @cancellable is triggered, this method should throw an error.
*
* @async
* @param {string[]} results - The original result set
* @param {string[]} terms - The search terms
* @param {Gio.Cancellable} cancellable - A cancellable for the operation
* @returns {Promise<string[]>}
*/
getSubsearchResultSet(results, terms, cancellable) {
console.debug(`getSubsearchResultSet([${results}], [${terms}])`);
if (cancellable.is_cancelled()) throw Error("Search Cancelled");
return this.getInitialResultSet(terms, cancellable);
}
/**
* Filter the current search.
*
* This method is called to truncate the number of search results.
*
* Implementations may use their own criteria for discarding results, or
* simply return the first n-items.
*
* @param {string[]} results - The original result set
* @param {number} maxResults - The maximum amount of results
* @returns {string[]} The filtered results
*/
filterResults(results, maxResults) {
console.debug(`filterResults([${results}], ${maxResults})`);
if (results.length <= maxResults) return results;
return results.slice(0, maxResults);
}
}
export default class ExampleExtension extends Extension {
enable() {
this._provider = new SearchProvider(this);
Main.overview.searchController.addProvider(this._provider);
}
disable() {
Main.overview.searchController.removeProvider(this._provider);
this._provider = null;
}
}