-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathextension.js
643 lines (550 loc) · 20.8 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
import St from 'gi://St'
import Gio from 'gi://Gio'
import GLib from 'gi://GLib'
import * as Main from 'resource:///org/gnome/shell/ui/main.js'
import { Extension, gettext as _ } from
'resource:///org/gnome/shell/extensions/extension.js'
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js'
import { setLogging, setLogFn, journal } from './utils.js'
import { getExtensionCacheDir, noCache, fileBasedCache } from './cache.js'
const INTERFACE_SCHEMA = 'org.gnome.desktop.interface'
const PREFER_DARK = 'prefer-dark'
const ACCENT_COLOR = 'accent-color'
const BACKGROUND_SCHEMA = 'org.gnome.desktop.background'
const PICTURE_URI = 'picture-uri'
const PICTURE_URI_DARK = 'picture-uri-dark'
const SLATE_INDEX = 8
const PARSER_VERSION = 2
function getHueFromRGB(r, g, b) {
const maxColour = Math.max(r, g, b)
const minColour = Math.min(r, g, b)
const delta = maxColour - minColour
let hue = 0
if (delta === 0) {
return hue // = 0
}
switch (maxColour) {
case r:
hue = (g - b) / delta
break
case g:
hue = 2 + (b - r) / delta
break
case b:
hue = 4 + (r - g) / delta
break
}
hue *= 60
if (hue < 0) { hue += 360 }
return hue
}
function getSaturationFromRGB(r, g, b) {
const maxColourPercentage = Math.max(r, g, b) / 255
const minColourPercentage = Math.min(r, g, b) / 255
const delta = maxColourPercentage - minColourPercentage
let saturation = 0.0
if (maxColourPercentage !== 0.0) {
saturation = delta / maxColourPercentage
}
return saturation * 100
}
class HueRange {
constructor(lowerBound, upperBound) {
this.lowerBound = lowerBound
this.upperBound = upperBound
}
}
class AccentColour {
constructor(name, r, g, b, hueRange) {
this.name = name
this.r = r
this.g = g
this.b = b
this.hueRange = hueRange
}
}
// Thank you to andy.holmes on StackOverflow for this Promise wrapper
// https://stackoverflow.com/a/61150669
function execCommand(argv, input = null, cancellable = null) {
let flags = Gio.SubprocessFlags.STDOUT_PIPE;
if (input !== null)
flags |= Gio.SubprocessFlags.STDIN_PIPE;
let process = new Gio.Subprocess({
argv: argv,
flags: flags
});
process.init(cancellable);
return new Promise((resolve, reject) => {
process.communicate_utf8_async(input, cancellable, (proc, res) => {
try {
resolve(proc.communicate_utf8_finish(res)[1]);
} catch (e) {
reject(e);
}
});
});
}
function getSquaredEuclideanDistance(r1, g1, b1, r2, g2, b2) {
return (r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2
}
function isHueInRange(hue, hueRange) {
if (hue >= hueRange.lowerBound && hue <= hueRange.upperBound) {
return true
} else if (hueRange.lowerBound > hueRange.upperBound) {
// Check for wrapping
return hue >= hueRange.lowerBound || hue <= hueRange.upperBound
}
return false
}
function getClosestAccentColour(accentColours, r, g, b) {
let shortestDistance = Number.MAX_VALUE
let closestAccentIndex = -1
const hue = getHueFromRGB(r, g, b)
journal(`Parsed hue: ${hue}`)
const eligibleAccents = accentColours.filter((accent) => {
return isHueInRange(hue, accent.hueRange)
})
const saturation = getSaturationFromRGB(r, g, b)
journal(`Parsed saturation: ${saturation}`)
if (saturation < 5) {
journal('Returning slate due to low saturation')
return SLATE_INDEX
}
for (let accent of eligibleAccents) {
let squaredEuclideanDistance = getSquaredEuclideanDistance(
r, g, b,
accent.r, accent.g, accent.b
)
journal(`Distance from ${accent.name}: ${squaredEuclideanDistance}`)
if (squaredEuclideanDistance < shortestDistance) {
shortestDistance = squaredEuclideanDistance
closestAccentIndex = accentColours.indexOf(accent)
}
}
journal(`Closest accent: ${accentColours[closestAccentIndex].name}`)
return closestAccentIndex
}
/*
Crusty way of getting colorthief to run without blocking the main thread.
I have no idea how to use multithreading in GJS, so I just spawn a new
GJS subprocess to run the colorthief script asynchronously, and convert its
stdout from a string back into an array of numbers. If you have a more elegant
solution, please feel free to submit a pull request.
*/
async function runColorThief(imagePath, extensionPath) {
try {
const resultStr = await execCommand(
['gjs', '-m', `${extensionPath}/color-thief/run-color-thief.js`, imagePath]
)
const palette = resultStr.split(';')
for (let i = 0; i < palette.length; i++) {
palette[i] = palette[i].split(',').map(Number)
}
return palette
} catch (e) {
journal(e, true)
return Array(5).fill([0, 0, 0])
}
}
async function getBackgroundPalette(extensionPath, backgroundPath) {
try {
const backgroundPalette = await runColorThief(backgroundPath, extensionPath)
journal(`Wallpaper colour palette: ${backgroundPalette}`)
const dominantColourTuple = backgroundPalette[0]
const highlightColourTuple = backgroundPalette[1]
return [dominantColourTuple, highlightColourTuple]
} catch (e) {
journal(e, true)
return Array(2).fill([0, 0, 0])
}
}
async function applyClosestAccent(
thisRun,
getCurrentRun,
extensionPath,
accentColours,
backgroundUri,
cache,
highlightMode,
onWaitStart,
onIncompatibleImg,
onFinish
) {
const backgroundFile = Gio.File.new_for_uri(backgroundUri);
const backgroundPath = backgroundFile.get_path()
let bytes = null
try {
bytes = backgroundFile.load_bytes(null)[0];
} catch(e) {
journal(e, true)
onIncompatibleImg()
}
const backgroundHash = bytes.hash();
journal(`Hash of background in ${backgroundPath} is ${backgroundHash}...`);
const cachedParserVer = await cache.get('parser-version')
journal(`Cached parser version: ${cachedParserVer}`)
journal(`Current parser version: ${PARSER_VERSION}`)
if (cachedParserVer !== PARSER_VERSION) {
await cache.clear()
await cache.set('parser-version', PARSER_VERSION)
}
let backgroundPalette = await cache.get(backgroundHash)
const backgroundFileInfo = await backgroundFile.query_info_async(
'standard::*',
Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
GLib.PRIORITY_DEFAULT,
null
)
const backgroundImgFormat = backgroundFileInfo.get_content_type()
journal(`Background image format: ${backgroundImgFormat}`)
const incompatibleFormats = ['application/xml']
if (incompatibleFormats.includes(backgroundImgFormat)) {
onIncompatibleImg()
return
}
if (backgroundPalette === null) {
journal(`Cache miss: recomputing palette...`);
onWaitStart()
const rasterPath = backgroundFile.get_path();
backgroundPalette = await getBackgroundPalette(extensionPath, rasterPath)
await cache.set(backgroundHash, backgroundPalette);
}
journal(`Palette: ${backgroundPalette}...`);
const accentType = highlightMode ? 'highlight' : 'dominant';
const paletteIndex = highlightMode ? 1 : 0;
const [r, g, b] = backgroundPalette[paletteIndex];
journal(`Getting ${accentType} accent...`)
const closestAccentIndex = getClosestAccentColour(accentColours, r, g, b)
const closestAccent = accentColours[closestAccentIndex]
journal(`Accent to apply: ${closestAccent.name}`)
/* Checking the instance run against the current run prevents a race
condition where an earlier calling of this function may execute faster than,
and therefore overwrite the result of, a newer calling of this function */
const currentRun = getCurrentRun()
journal(`Instance run: ${thisRun}, current run: ${currentRun}`)
if (thisRun === currentRun) {
onFinish(closestAccent)
} else {
journal(`Aborting due to newer run`)
}
}
export default class AutoAccentColourExtension extends Extension {
enable() {
if (this.getLogger) {
// Use ExtensionBase's logger class on GNOME 48+
const logger = this.getLogger()
setLogFn(function(msg, error) {
if (error) {
logger.error(msg)
} else {
logger.log(msg)
}
})
}
/* Hue values are:
0 = Red
60 = Yellow
120 = Green
180 = Cyan
240 = Blue
300 = Magenta
*/
const gnomeAccents = [
/* The RGB values set in these accent colour entries are *not* the RGB
values of the same accent colours you would find in the GNOME appearance
settings. They are exaggerated to add further distinction between them, so
that a greater variety of accents can be returned from different backgrounds
and their derived colours. */
new AccentColour('blue', 0, 115, 255, new HueRange(195, 300)),
new AccentColour('teal', 0, 255, 255, new HueRange(120, 240)),
new AccentColour('green', 0, 191, 0, new HueRange(50, 180)),
new AccentColour('yellow', 200, 150, 0, new HueRange(29, 64)),
new AccentColour('orange', 237, 91, 0, new HueRange(7, 64)),
new AccentColour('red', 230, 0, 26, new HueRange(300, 22)),
new AccentColour('pink', 213, 0, 103, new HueRange(240, 0)),
new AccentColour('purple', 145, 65, 172, new HueRange(240, 330)),
new AccentColour('slate', 166, 166, 166, new HueRange(195, 300))
]
const ubuntuAccents = [
/* The same as above applies to these accents */
new AccentColour('blue', 0, 115, 255, new HueRange(195, 300)),
new AccentColour('teal', 0, 255, 255, new HueRange(120, 240)),
new AccentColour('green', 0, 191, 0, new HueRange(50, 180)),
new AccentColour('yellow', 200, 150, 0, new HueRange(29, 64)),
new AccentColour('orange', 237, 91, 0, new HueRange(7, 64)),
new AccentColour('red', 230, 0, 26, new HueRange(300, 22)),
new AccentColour('pink', 213, 0, 103, new HueRange(240, 0)),
new AccentColour('purple', 145, 65, 172, new HueRange(240, 330)),
new AccentColour('slate', 166, 166, 166, new HueRange(50, 180))
]
const extensionPath = this.path
this._settings = this.getSettings()
const extensionSettings = this._settings
this._backgroundSettings = new Gio.Settings({
schema: BACKGROUND_SCHEMA
})
const backgroundSettings = this._backgroundSettings
function getBackgroundUri() {
return backgroundSettings.get_string(PICTURE_URI)
}
function getDarkBackgroundUri() {
return backgroundSettings.get_string(PICTURE_URI_DARK)
}
this._interfaceSettings = new Gio.Settings({ schema: INTERFACE_SCHEMA })
const interfaceSettings = this._interfaceSettings
function getColorScheme() {
return interfaceSettings.get_string('color-scheme')
}
function setAccentColor(colorName) {
interfaceSettings.set_string(ACCENT_COLOR, colorName)
}
function getAccentColor() {
return interfaceSettings.get_string(ACCENT_COLOR)
}
function setIconTheme(theme) {
interfaceSettings.set_string('icon-theme', theme)
}
function getIconTheme() {
return interfaceSettings.get_string('icon-theme')
}
function setGtkTheme(theme) {
interfaceSettings.set_string('gtk-theme', theme)
}
function getGtkTheme() {
return interfaceSettings.get_string('gtk-theme')
}
function getDisableCache() {
return extensionSettings.get_boolean('disable-cache')
}
function getCache() {
return getDisableCache() ? noCache() : fileBasedCache(getExtensionCacheDir())
}
function applyYaruTheme() {
const iconTheme = getIconTheme()
const gtkTheme = getGtkTheme()
const yaruThemes = [
'Yaru-blue',
'Yaru-blue-dark',
'Yaru-prussiangreen',
'Yaru-prussiangreen-dark',
'Yaru-olive',
'Yaru-olive-dark',
'Yaru-yellow',
'Yaru-yellow-dark',
'Yaru',
'Yaru-dark',
'Yaru-red',
'Yaru-red-dark',
'Yaru-magenta',
'Yaru-magenta-dark',
'Yaru-purple',
'Yaru-purple-dark',
'Yaru-sage',
'Yaru-sage-dark',
'Yaru-wartybrown',
'Yaru-wartybrown-dark'
]
function getYaruColour() {
switch (getAccentColor()) {
case 'blue': return '-blue'
case 'teal': return '-prussiangreen'
case 'green': return '-olive'
case 'yellow': return '-yellow'
case 'orange': return ''
case 'red': return '-red'
case 'pink': return '-magenta'
case 'purple': return '-purple'
case 'slate': return '-sage'
default: return ''
}
}
const yaruDark = getColorScheme() === PREFER_DARK ? '-dark' : ''
const yaruTheme = `Yaru${getYaruColour()}${yaruDark}`
if (yaruThemes.includes(iconTheme)) {
setIconTheme(yaruTheme)
journal(`Applied icon theme as ${yaruTheme}`)
}
if (yaruThemes.includes(gtkTheme)) {
setGtkTheme(yaruTheme)
journal(`Applied GTK theme as ${yaruTheme}`)
}
}
setLogging(this._settings.get_boolean('debug-logging'))
const onUbuntu = Main.sessionMode.currentMode === 'ubuntu'
journal(`Running on Ubuntu: ${onUbuntu}`)
const accentColours = onUbuntu ? ubuntuAccents : gnomeAccents
function getIcon(iconName) {
return new St.Icon({
gicon: Gio.icon_new_for_string(
`${extensionPath}/icons/${iconName}.svg`
),
style_class: 'system-status-icon'
})
}
this._indicator = new PanelMenu.Button(0.0, this.metadata.name, false)
const indicator = this._indicator
const normalIcon = getIcon('color-symbolic')
const waitIcon = getIcon('color-wait-symbolic')
const alertIcon = getIcon('color-alert-symbolic')
let currentIcon = normalIcon
indicator.add_child(currentIcon)
function changeIndicatorIcon(newIcon) {
indicator.remove_child(currentIcon)
currentIcon = newIcon
indicator.add_child(currentIcon)
}
let run = 0
function getCurrentRun() {
return run
}
Main.panel.addToStatusArea(this.uuid, this._indicator)
indicator.menu.addAction(
_('Force Refresh'),
() => setAccent()
)
indicator.menu.addAction(
_('Preferences'),
() => this.openPreferences()
)
function setAccent() {
run++
const backgroundUri = getColorScheme() === PREFER_DARK
? getDarkBackgroundUri()
: getBackgroundUri()
const highlightMode = extensionSettings.get_boolean('highlight-mode')
applyClosestAccent(
run,
getCurrentRun,
extensionPath,
accentColours,
backgroundUri,
getCache(),
highlightMode,
function() { changeIndicatorIcon(waitIcon) },
function() {
Main.notifyError(
_('Background format not supported'),
_('Auto Accent Colour will not run on this background')
)
changeIndicatorIcon(alertIcon)
},
function(newAccent) {
setAccentColor(newAccent.name)
applyYaruTheme(),
journal(`New accent: ${getAccentColor()}`)
changeIndicatorIcon(normalIcon)
}
)
}
setAccent()
this._settings.bind(
'hide-indicator',
this._indicator,
'visible',
Gio.SettingsBindFlags.INVERT_BOOLEAN
)
// Watch for light background change
this._lightBackgroundHandler = this._backgroundSettings.connect(
'changed::picture-uri',
() => {
if (getColorScheme() !== PREFER_DARK) {
journal('Setting accent from picture-uri change.')
setAccent()
}
}
)
// Watch for dark background change
this._darkBackgroundHandler = this._backgroundSettings.connect(
'changed::picture-uri-dark',
() => {
if (getColorScheme() === PREFER_DARK) {
journal('Setting accent from picture-uri-dark change.')
setAccent()
}
}
)
const backgroundFilePath = GLib.get_home_dir() + '/.config/background'
const backgroundFile = Gio.File.new_for_path(backgroundFilePath)
this._backgroundFileMonitor = backgroundFile.monitor(
Gio.FileMonitorFlags.NONE,
null
)
this._backgroundFileHandler = this._backgroundFileMonitor.connect(
'changed',
(_fileMonitor, file, otherFile, eventType) => {
if (eventType === Gio.FileMonitorEvent.CREATED) {
journal('Background file changed.')
setAccent()
}
}
)
// Watch for light/dark theme change
this._colorSchemeHandler = this._interfaceSettings.connect(
'changed::color-scheme',
() => {
if (getBackgroundUri() !== getDarkBackgroundUri()) {
journal('Setting accent from color-scheme change.')
setAccent()
}
}
)
// Watch for 'hide indicator' setting change
this._hideIndicatorHandler = this._settings.connect(
'changed::hide-indicator',
(settings, key) => {
journal(`${key} = ${settings.get_value(key).print(true)}`)
}
)
this._highlightModeHandler = this._settings.connect(
'changed::highlight-mode',
(settings, key) => {
journal(`${key} = ${settings.get_value(key).print(true)}`)
setAccent()
}
)
this._debugModeHandler = this._settings.connect(
'changed::debug-logging',
(settings, key) => {
setLogging(settings.get_boolean(key))
journal(`${key} = ${settings.get_value(key).print(true)}`)
}
)
}
disable() {
if (this._lightBackgroundHandler) {
this._backgroundSettings.disconnect(this._lightBackgroundHandler)
this._lightBackgroundHandler = null
}
if (this._darkBackgroundHandler) {
this._backgroundSettings.disconnect(this._darkBackgroundHandler)
this._darkBackgroundHandler = null
}
if (this._backgroundFileHandler) {
this._backgroundFileMonitor.disconnect(this._backgroundFileHandler)
this._backgroundFileHandler = null
}
if (this._colorSchemeHandler) {
this._interfaceSettings.disconnect(this._colorSchemeHandler)
this._colorSchemeHandler = null
}
if (this._hideIndicatorHandler) {
this._settings.disconnect(this._hideIndicatorHandler)
this._hideIndicatorHandler = null
}
if (this._highlightModeHandler) {
this._settings.disconnect(this._highlightModeHandler)
this._hideIndicatorHandler = null
}
if (this._debugModeHandler) {
this._settings.disconnect(this._debugModeHandler)
this._debugModeHandler = null
}
this._indicator?.destroy()
this._indicator = null
this._settings = null
this._interfaceSettings = null
this._backgroundSettings = null
this._backgroundFileMonitor = null
setLogFn(null)
}
}