forked from polychromatic/polychromatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
polychromatic-controller
executable file
·2717 lines (2290 loc) · 120 KB
/
polychromatic-controller
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Polychromatic is free software: you can redistribute it and/or modify
# it under the temms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Polychromatic 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 Polychromatic. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2015-2017 Luke Horwell <luke@ubuntu-mate.org>
# 2015-2016 Terry Cain <terry@terrys-home.co.uk>
version = "0.3.9"
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, Gdk, WebKit2
import os
import sys
import glob
import signal
import json
import gettext
import setproctitle
setproctitle.setproctitle('polychromatic-controller')
import time
import threading
from subprocess import Popen as background_process
from subprocess import check_output
from platform import linux_distribution
try:
import razer.client as rclient
from razer_daemon.keyboard import get_keyboard_layout
from razer_daemon.keyboard import RGB
daemon_missing = False
except ImportError as e:
# We'll show a graphical error when loading up.
print("Failed to import modules for daemon.")
print("Exception: " + str(e))
daemon_missing = True
try:
# Relative copy
import pylib.preferences as pref
import pylib.profiles as prof
import pylib.common as common
import pylib.demo as demo
except ImportError:
# Installed to system
import polychromatic.preferences as pref
import polychromatic.profiles as prof
import polychromatic.common as common
import polychromatic.demo as demo
except Exception as e:
print("One or more of Polychromatic's modules could not be imported!")
print("Try re-installing the application.")
print("\nException:" + str(e))
exit(1)
path = pref.Paths()
path.data_source = path.get_data_source(__file__)
daemon_config_path = os.path.join(os.path.expanduser('~'), ".razer-service", "razer.conf")
# Imported on-demand:
# * requests
# * configparser
# * shutil
# * grp
class Translations(object):
def __init__(self):
# Use relative translations if available.
if os.path.exists(os.path.join(path.data_source, '../locale/')):
stdout.vprint("Using relative path for translations.")
self.locale_path = os.path.join(path.data_source, '../locale/')
else:
stdout.vprint("Using '/usr/share/locale/' or falling back to 'en_US' for translations.")
self.locale_path = '/usr/share/locale/'
# Initialise i18n translations
global _
t = gettext.translation('polychromatic-controller', localedir=self.locale_path, fallback=True)
_ = t.gettext
def push(self, element, string, append=False):
"""
Pushes a translatible string to the page.
"""
# "append=True" is useful for elements that share contents.
if append:
app.update_page(element, 'append', "{0}".format(string))
else:
app.update_page(element, 'html', "{0}".format(string))
def push_var(self, variable, string):
"""
Pushes a translatable string to a JavaScript variable on the page.
"""
app.webkit.run_javascript('var {0} = "{1}"'.format(variable, string))
class AppView(WebKit2.WebView):
def __init__(self, startpage):
"""
Initialise WebKit2
"""
# Create WebKit Container
webkit = WebKit2
webkit.WebView.__init__(self)
self.set_background_color(Gdk.RGBA(0,0,0,1))
# Post-actions after pages fully load.
self.connect('load-changed', self.load_changed_cb)
self.connect('notify::title', self.title_changed_cb)
self.connect('context-menu', self.context_menu_cb)
stdout.vvprint('Initialised WebKit2.')
try:
# Allows Keyboard SVGs to load.
self.get_settings().set_allow_file_access_from_file_urls(True)
self.get_settings().set_allow_universal_access_from_file_urls(True)
# Print console log errors to stdout
self.get_settings().set_enable_write_console_messages_to_stdout(True)
# Basic accessibility - keyboard navigation
self.get_settings().set_enable_spatial_navigation(True)
self.get_settings().set_enable_caret_browsing(True)
except AttributeError:
print("WebKit2GTK failed to initialise. Please try upgrading this dependency.\n")
print("Your distribution may be using an older version of this package.")
print("In Debian/Ubuntu, this package is provided in 'gir1.2-webkit-4.0'\n")
print("At least v2.12 is required for this software to function.")
sys.exit(1)
# Enable web inspector for debugging
if stdout.inspector:
self.get_settings().set_property("enable-developer-extras", True)
inspector = self.get_inspector()
inspector.show()
# Load the starting page
default_page = 'loading'
self.load_uri('file://' + os.path.join(path.data_source, 'pages/' + startpage + '.html'))
def title_changed_cb(self, view, frame):
"""
Callback: Title changed ('commands' used for communicating to Python)
"""
title = self.get_title()
if title not in ["null", None, "", " "]:
stdout.vvprint('** Command: ' + title)
app.process_command(title)
def load_changed_cb(self, view, frame):
"""
Callback: Page changed
"""
uri = str(self.get_uri())
try:
page = uri.rsplit('/', 1)[1].split('.html')[0]
except IndexError:
return
if not self.is_loading():
app.current_page = page
stdout.vvprint(' ** Page Changed: ' + page)
app.page_loaded()
def context_menu_cb(self, view, menu, event, htr, user_data=None):
"""
Callback: Disables the context menu.
"""
return True
class JavaScriptExecutor(object):
"""
Collects JavaScript and send altogether, used for profile editing.
"""
def __init__(self, webkit, script=None, wrapper=None):
if wrapper is not None:
self.wrapper = wrapper
else:
self.wrapper = "$(document).ready(function(){{{0}}});"
self.lines = []
self.webkit = webkit
stdout.vvprint(' => JSExec: Ready.')
if script is not None:
self.add(script)
def add(self, line):
"""
Adds a line to the collection.
:param line: Line to execute
:type line: str
:return: Returns a copy of the object
:rtype: JavaScriptExecutor
"""
line = str(line)
stdout.vvprint(' => JSExec: Line added: ' + line)
if line.endswith(';'):
self.lines.append(line)
else:
self.lines.append(line + ';')
return self
def exec(self):
"""
Runs the collection of commands.
"""
payload = str(self)
stdout.vvprint(' => JSExec: Pushed to page.')
self.webkit.run_javascript(payload)
def __lshift__(self, other):
self.add(other)
return self
def __str__(self):
lines = '\n' + '\n'.join(self.lines) + '\n'
result = self.wrapper.format(lines)
return result
class Controller(object):
def __init__(self):
"""
Initialises the application.
"""
# Set up "memory" variables
self.current_page = 'loading'
self.load_lock = False
# Set up variables provided by daemon
try:
self.kb_layout = get_keyboard_layout()
except:
self.kb_layout = 'gb'
# Is this application installed in /usr/share or ran from repository?
if os.path.exists(os.path.join(path.data_source + "/../install/update.sh")):
self.app_installed = False
else:
self.app_installed = True
def start(self):
"""
Assembles and runs the application.
"""
# Initalise WebKit
self.webkit = AppView(self.current_page)
# Create window
w = Gtk.Window(title="Polychromatic Controller")
w.set_wmclass('polychromatic-controller', 'polychromatic-controller')
w.set_position(Gtk.WindowPosition.CENTER)
w.modify_bg(Gtk.StateType(0), Gdk.Color(0,0,0))
w.set_resizable(False)
self.window = w
try:
w.set_icon_from_file(os.path.join(path.data_source, '../install/hicolor/16x16/apps/polychromatic-controller.svg'))
stdout.vvprint('Window icon set from relative path.')
except:
w.set_icon_from_file('/usr/share/icons/hicolor/16x16/apps/polychromatic-controller.svg')
stdout.vvprint('Window icon set from /usr/share/ path.')
# Add elements to window
sw = Gtk.ScrolledWindow()
sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
sw.add(self.webkit)
# Scale the application so it looks good on large displays.
scale = float(pref.get('editor', 'scaling', 1))
if scale == 1.5:
self.webkit.set_zoom_level(1.5)
w.set_size_request(1500, 900)
elif scale == 2:
self.webkit.set_zoom_level(2)
w.set_size_request(2000, 1200)
elif scale == 2.5:
self.webkit.set_zoom_level(2.5)
w.set_size_request(2500, 1500)
else:
self.webkit.set_zoom_level(1)
w.set_size_request(1000, 600)
stdout.vprint('Program Scale Set: ' + str(scale))
# Build an auto expanding box and add our scrolled window
b = Gtk.VBox(homogeneous=False, spacing=0)
b.pack_start(sw, expand=True, fill=True, padding=0)
w.add(b)
w.connect("delete-event", Gtk.main_quit)
w.show_all()
stdout.vvprint('Initialised Window.')
# Kills process when CTRL+C'd.
signal.signal(signal.SIGINT, signal.SIG_DFL)
thread = threading.Thread(target=self.run_app, args=())
thread.daemon = True
thread.start()
Gtk.main()
def run_app(self):
"""
Starts the main application's operations.
"""
# Prepare devices
stdout.vprint("Loading Daemon...")
if daemon_missing:
self.show_error_page(
"serious", "generic", _("Daemon Not Installed"),
_("Polychromatic requires the daemon, but it could not be imported. Please check the Razer drivers, daemon and Python library are installed.") +
'<br><br><a onclick="cmd(\'open?https://github.com/lah7/polychromatic\')">' + _("See the README for further information.") + '</a>')
return
try:
self.devman = rclient.DeviceManager()
except rclient.DaemonNotFound:
print("ERROR: Daemon Not Found.")
self.devman = None
self.devman_error = "not-running"
except Exception as e:
print("ERROR: Exception: " + str(e))
self.devman = None
self.devman_error = "presume-crashed"
self.devman_reason = str(e)
# When the running daemon and installed library differ, request the user to restart the daemon.
# Running = Current running daemon's version.
# Installed = Version installed globally on system.
try:
running_version = self.devman._daemon_version
import razer_daemon.daemon
installed_version = razer_daemon.daemon.__version__
except Exception:
# Daemon may have crashed, skip this check.
running_version = 0
installed_version = 0
if installed_version < running_version:
print("ERROR: Currently running daemon is older than the installed version.")
self.show_error_page(
"warning", "restart-required", _("Daemon requires a restart"),
_("The daemon that is currently running is older than the installed version.") + "<br>" +
_("This can cause glitches. Please restart the daemon to continue.") + "<br><br>" +
_("This happens if the driver/daemon packages were updated, but you haven't restarted your session or computer.")
)
return
# Display an upgrade message if using the old daemon.
if os.path.exists("/usr/lib/python3/dist-packages/razer/inteface/keyboard.py") or os.path.exists(os.path.join(sys.path[-1], "/razer/inteface/keyboard.py")):
print("ERROR: Daemon is incompatible with this version of the program.")
self.show_error_page(
"normal", "upgrade", _("Daemon Upgrade Required"),
_("The Razer 'Chroma' driver and daemon currently installed on your system is no longer supported by Polychromatic.") + "<br><br>" +
_("Please remove the current Razer driver/daemon from your system, then install the new one from: ") +
'<a onclick="cmd(\'open?http://terrycain.github.io/razer-drivers/\')">http://terrycain.github.io/razer-drivers/</a>' +
'<br><br><a onclick="cmd(\'open?https://github.com/lah7/polychromatic/releases/tag/v0.3.0\')">' +
_("For more information, see the Release Notes for v0.3.0.") + '</a>')
return
# Display an error message if the daemon is having problems on the system.
if not self.devman:
print("ERROR: Could not connect to the Daemon Device Manager!")
if self.devman_error == "not-running":
self.show_error_page(
"serious", "generic", _("Daemon Not Running"),
_("Polychromatic uses the daemon to interact with your Razer devices, but it doesn't appear to be running."))
return
if self.devman_error == "presume-crashed":
exception = ""
for line in self.devman_reason.split('\n'):
exception += '<code>' + line + '</code><br>'
self.show_error_page(
"serious", "generic", _("Daemon Not Responding"),
_("Polychromatic could not initialise the daemon. This could be caused by a bug with the daemon process.") + "<br><br>" +
_("Exception:") + ' <code>' + exception + '</code>')
return
# Display "No Devices Found" screen if none can be found
if self.devman:
self.devices = self.get_devices()
if len(self.devices) == 0:
# get_devices() function shows "No Devices Found".
return
# Initialise Profiles
stdout.vprint("Loading Application Profiles...")
self.profiles = prof.AppProfiles()
self.profiles.selected_uuid = None
self.profiles.previous_uuid = None
# Set active device.
if len(self.devices) == 0:
self.active_device = None
self.active_device_serial = None
return
else:
self.active_device = self.devices[0]
self.active_device_serial = self.devices[0].serial
# Start watching devicestate index for changes.
common.devicestate_monitor_start(self.device_state_changed, path.devicestate)
stdout.vprint('Application Ready.\n')
self.show_menu('menu')
def update_page(self, element, function, parm1=None, parm2=None):
"""
Sends a jQuery function to the page, ensuring correctly parsed quotes.
"""
if parm1 and parm2:
buffer = '$("' + element + '").' + function + "('" + parm1.replace("'", '\\\'') + "', '" + parm2.replace("'", '\\\'') + "')"
stdout.vvprint(' => Push JS: ' + buffer)
self.webkit.run_javascript(buffer)
if parm1:
buffer = '$("' + element + '").' + function + "('" + parm1.replace("'", '\\\'') + "')"
stdout.vvprint(' => Push JS: ' + buffer)
self.webkit.run_javascript(buffer)
else:
buffer = '$("' + element + '").' + function + '()'
stdout.vvprint(' => Push JS: ' + buffer)
self.webkit.run_javascript(buffer)
def show_menu(self, page):
"""
Changes the current page in use.
"""
self.current_page = page
page_path = os.path.join(path.data_source, 'pages', page + '.html')
if os.path.exists(page_path):
self.webkit.load_uri('file://' + page_path)
else:
print("Unknown menu: " + page)
def page_loaded(self):
"""
Initialise the page when it has finished loading.
"""
stdout.vvprint(' ** Running post-actions for page: "' + self.current_page + '"...')
trans.push('#close-window', _("Close"))
if self.current_page == 'menu':
# Push strings
trans.push('#page-header', _("Overview"))
trans.push_var('str_overview', _("Overview"))
trans.push('#str-brightness', _("Brightness"))
trans.push('#str-lighting', _("Lighting Effects"))
trans.push('#str-spectrum', _("Spectrum"))
trans.push('#str-wave', _("Wave"))
trans.push('#str-reactive', _("Reactive"))
trans.push('#str-breath', _("Breath"))
trans.push('#str-pulsate', _("Pulsate"))
trans.push('#str-ripple', _("Ripple"))
trans.push('#str-static', _("Static"))
trans.push('#str-color', _("Color:"), True)
trans.push('.str-custom', _("Custom..."))
trans.push('.str-none', _("None"), True)
trans.push('#str-direction', _("Direction:"), True)
trans.push('#str-wave-left', _("Left"))
trans.push('#str-wave-right', _("Right"))
trans.push('#str-speed', _("Speed:"), True)
trans.push('.str-random', _("Random"), True)
trans.push('.str-single-col', _("Single Color"), True)
trans.push('#str-dual-col', _("Dual Colors"), True)
trans.push('#str-cycles', _("Cycle:"), True)
trans.push('#str-colours', _("Colors:"), True)
trans.push('#str-slow', _("Slow"), True)
trans.push('#str-med', _("Medium"), True)
trans.push('#str-fast', _("Fast"), True)
trans.push('#str-modes', _("Key Modes"))
trans.push('#str-game-mode', _("Gaming Mode"))
trans.push('#game-mode-disable', _("Disable"))
trans.push('#game-mode-enable', _("Enable"))
trans.push('#game-mode-tip', _("Disables ALT+F4 and Super key."))
trans.push('#str-macro-keys', _("Macro Keys"))
trans.push('#macro-keys-enable', _("Activate"))
trans.push('#profiles-activate', _("Activate"), True)
trans.push('.str-help', _("Help"))
trans.push('#str-profiles', _("Application Profiles"), True)
trans.push('#profiles-new', _("New"), True)
trans.push('#profiles-edit', _("Edit"), True)
trans.push('#profiles-delete', _("Delete"), True)
trans.push('#dialog-new-title', _("Create New Application Profile"))
trans.push('#dialog-new-hint', _("Please enter a name for the new profile, and optionally an icon."))
trans.push('#str-new-name', _("Application:"))
trans.push('#str-new-icon', _("Icon Path:"))
trans.push('#str-fetch-launcher', _("Select Installed Application"))
trans.push('#dialog-new-cancel', _("Cancel"))
trans.push('#dialog-new-ok', _("Create"))
trans.push('#dialog-del-title', _("Delete"))
trans.push('#dialog-del-hint', _("Are you sure you want to delete this?"))
trans.push('#dialog-del-no', _("Keep"))
trans.push('#dialog-del-yes', _("Delete"))
trans.push('#dialog-applauncher-title', _("Choose an Application"))
trans.push('#dialog-applauncher-hint', _("The information from the chosen program will be used as the profile's base."))
trans.push('#dialog-applauncher-revert', _("Cancel"))
trans.push('#dialog-applauncher-ok', _("Select"))
trans.push('#dialog-help-title', _("Quick Help"))
# Just the macro keys are present here.
trans.push('#dialog-help-subtitle', _("Macro Keys Usage"))
trans.push('#dialog-help-body', _("You can also use on-the-fly macro recording (provided by the daemon) by following these steps:") +
'<ol><li>FN + <div class="macro-key"></div> ' + _("to enter macro mode.") + '</li>' +
'<li>' + _("Press the macro key to assign to. E.g. M1") +'</li>' +
'<li>' + _("Typing in your key combination.") +'</li>' +
'<li>' + _("Exiting macro mode with ") + ' FN + <div class="macro-key"></div></li></ol>')
trans.push('#dialog-help-close', _("Close"))
trans.push('#str-browse-icon', _("Browse Icon"))
trans.push('#str-dpi', _("DPI"))
trans.push('#str-poll-rate', _("Polling Rate"))
# Page actions
self.webkit.run_javascript('instantProfileSwitch = false;')
self.update_page('#profiles-activate', 'show')
self.refresh_device_list()
self.refresh_profiles_list()
# Tell JavaScript whether live profile switching is enabled.
if pref.get('editor', 'live_switch', 'true') == 'true':
self.webkit.run_javascript('live_switch = true;')
self.update_page('#profiles-activate', 'hide')
else:
self.webkit.run_javascript('live_switch = false;')
# If there are multiple devices connected, show the overview screen first.
if len(self.devices) > 1:
self.update_page(".device", "removeClass", "active")
self.update_page("#device-overview-tab", "addClass", "active")
self.update_page("#device-individual", "hide")
self.update_page("#device-overview", "fadeIn")
else:
self.update_device_supported_features()
self.update_device_active_options()
# Display warning and disable sync effects if enabled in daemon.
if os.path.exists(daemon_config_path):
with open(daemon_config_path, "r") as f:
daemon_config = f.read()
if daemon_config.find("sync_effects_enabled = True") != -1:
daemon_config = daemon_config.replace("sync_effects_enabled = True", "sync_effects_enabled = False")
with open(daemon_config_path, 'w') as f:
f.write(daemon_config)
error_text = _("Sync effects have been disabled in the daemon's configuration as they are not supported in Polychromatic.")
self.update_page("#error", "fadeIn")
self.update_page("#error", "addClass", "warning")
self.update_page("#error-text", "html", error_text)
stdout.error(error_text)
elif self.current_page == 'profile_editor':
# Push strings
trans.push('#cancel', _("Cancel"))
trans.push('#edit-preview', _("Preview"))
trans.push('#edit-save', _("Save"), True)
trans.push_var('str_set', _("Set"))
trans.push_var('str_set_help', _("Click on a key to assign a color here."))
trans.push_var('str_picker', _("Picker"))
trans.push_var('str_picker_help', _("Click on a key to grab its color."))
trans.push_var('str_clear', _("Clear"))
trans.push_var('str_clear_help', _("Click on a key to clear."))
self.webkit.run_javascript("set_mode('set')")
trans.push('#str-edit-profile', _("Edit"), True)
trans.push('#dialog-rename-title', _("Edit Profile Details"))
trans.push('#dialog-rename-hint', _("Change the name and icon for this profile."))
trans.push('#str-rename-name', _("Name:"))
trans.push('#str-rename-icon', _("Icon Path:"))
trans.push('#dialog-rename-cancel', _("Discard"))
trans.push('#dialog-rename-ok', _("Save Changes"))
trans.push('#str-browse-icon', _("Browse Icon"))
# Initialise keyboard layout
js_exec = self.webkit.JavaScriptExecutor(self.webkit)
kb_callback = self.webkit.JavaScriptExecutor(None, wrapper="keyboard_obj.load(function(){{{0}}});")
# Initalise colour picker
self.print_colour_options("editor-colour", "#colour-selection", [0, 255, 0], "profile")
# Collect profile details.
uuid = self.profiles.selected_uuid
self.webkit.run_javascript("var selected_profile = '{0}'".format(uuid))
profile_path = os.path.join(path.profile_folder, str(uuid) + ".json")
self.profiles.memory = pref.load_file(profile_path)
profile_data = self.profiles.memory
profile_name = profile_data["name"]
profile_icon = profile_data["icon"]
# Set profile title on page
self.update_page("#profile-name", "html", profile_name)
self.update_page("#profile-name", "fadeIn")
# Set profile icon on page
self.update_page("#profile-icon", "attr", "src", profile_icon)
self.update_page("#profile-icon", "fadeIn")
# Set keyboard layout
kb_callback << "keyboard_obj.set_layout(\"kb-" + self.kb_layout + "\")"
# Load profile into keyboard.
self.profiles.selected_uuid = uuid
if pref.get('editor', 'live_preview', 'true') == 'true':
self.profiles.send_profile_to_keyboard(self.active_device, profile_data)
for row in range(0, 6):
for col in range(0, 22):
red = profile_data["rows"][str(row)][col][0]
green = profile_data["rows"][str(row)][col][1]
blue = profile_data["rows"][str(row)][col][2]
js_string = "keyboard_obj.set_key_colour({0},{1},\"#{2:02X}{3:02X}{4:02X}\")".format(row, col, red, green, blue)
kb_callback << js_string
# Disable space key and FN for keyboards that don't support them.
device_name = str(self.active_device.name)
if device_name in "Razer BlackWidow Chroma" "Razer BlackWidow Ultimate":
# Except that BW Ultimate 2016 does support the keys.
if not device_name == "Razer BlackWidow Ultimate 2016":
kb_callback << "keyboard_obj.disable_key(5,7)"
kb_callback << "keyboard_obj.disable_key(5,12)"
# Hide preview button if live previewing is enabled.
if pref.get('editor', 'live_preview', 'true') == 'true':
kb_callback << '$("#edit-preview").hide();'
kb_callback << "$(\"#cancel\").attr({onclick: \"cmd('cancel-changes?"+ self.cancel_changes + "?" + uuid + "')\"})"
js_exec << kb_callback
js_exec.exec()
elif self.current_page == 'preferences':
trans.push('#page-header', _("Preferences"))
########################
# About
########################
trans.push('#str-about', _("About"))
trans.push('#str-tray', _("Tray Applet"))
trans.push('#str-app-settings', _("General"))
trans.push('.str-colours', _("Colors"))
trans.push('#str-daemon', _("Daemon"))
trans.push('#str-version-app', _("Version:"))
trans.push('#str-version-config', _("Configuration:"))
trans.push('#str-version-daemon', _("Daemon Version:"))
trans.push('#str-version-lib', _("Razer Python Library:"))
trans.push('#project-button', _("View on GitHub"), True)
trans.push('#update-button', _("Check for Updates"))
trans.push('#changelog-button', _("View Change Log"))
trans.push('#dialog-changelog-title', _("Update History"), True)
trans.push('#dialog-changelog-subtitle', _("A human-readable list of changes made to Polychromatic."))
trans.push('#dialog-close', _("Close"), True)
# Append version information
def make_dev_version():
version_master = version[:-1] + str(int(version[-1:]) + 1)
self.update_page('#str-version-app-string', "html", version_master + "-dev")
if self.app_installed:
# Hide the option to update if the app is running globally.
self.update_page('#str-version-app-string', "html", version)
self.update_page("#update-button", "hide")
else:
# When running from 'master' directly.
make_dev_version()
self.update_page('#str-version-config-string', "html", str(pref.version))
self.update_page('#str-version-lib-string', "html", str(self.devman.version))
self.update_page('#str-version-daemon-string', "html", str(self.devman.daemon_version))
# For Apt, check for the source file to determine builds.
distro = linux_distribution()[0]
if distro == "Ubuntu" or distro == "Debian":
codename = linux_distribution()[2]
source_file = "/etc/apt/sources.list.d/lah7-ubuntu-polychromatic-" + codename + ".list"
if os.path.exists(source_file) and os.path.getsize(source_file) > 0:
self.update_page("#auto-update-info", "html", "<tr><td style='color:lime'><br><span class='fa fa-check-circle'></span> {0}</td></tr>".format(
_("You are set for automatic updates (via PPA)")))
self.update_page("#auto-update-info", "show")
source_file = "/etc/apt/sources.list.d/lah7-ubuntu-polychromatic-daily-" + codename + ".list"
if os.path.exists(source_file) and os.path.getsize(source_file) > 0:
self.update_page("#auto-update-info", "html", "<tr><td style='color:yellow'><br><span class='fa fa-check-circle'></span> {0}</td></tr>".format(
_("You have opted for development packages.")))
self.update_page("#auto-update-info", "show")
make_dev_version()
# Synchronised demo for BlackWidow Chroma users.
for device in self.devices:
if device.name.startswith("Razer BlackWidow Chroma"):
self.update_page("#demo-chroma", "show")
trans.push('#demo-chroma', _("Play Demo - Razer BlackWidow Chroma Advert"))
########################
# General
########################
trans.push('#str-app-profiles', _("Application Profiles"))
trans.push('#str-live-switch', _("Enable live switching"), True)
trans.push('#str-live-switch-help', _("Activate profiles instantly as soon as you click on them."))
trans.push('#str-live-preview', _("Enable live preview"), True)
trans.push('#str-live-preview-help', _("While editing, show your changes on the actual keyboard."))
trans.push('#str-activate-on-save', _("Always activate profiles after saving."), True)
trans.push('#str-interface', _("Interface"))
trans.push('#str-scaling', _("Scale:"))
trans.push('#str-scaling-help', _("Scale the application so it looks good on large displays. Requires restart."))
trans.push('#str-advanced', _("Advanced"))
trans.push('#str-open-config', _("Open Configuration Folder"), True)
trans.push('#str-reset-pref', _("Reset Preferences"), True)
trans.push('#str-reset-all', _("Reset Everything"))
trans.push('#pref-save', _("OK"), True)
trans.push_var('del_all_text', _("Are you sure you wish to erase all configuration and profiles?"))
trans.push_var('no_change', _("No Change"))
for setting in ["live_switch", "live_preview", "activate_on_save"]:
if pref.get("editor", setting, "true") == 'true':
self.update_page("#" + setting, "prop", "checked", "true")
# Set value for slider
scaling = pref.get("editor", "scaling", 1)
self.update_page("#scaling", "val", str(scaling))
########################
# Tray Applet
########################
trans.push('#str-tray-icon', _("Tray Icon"))
trans.push('#str-tray-custom', _("Use Custom Image"), True)
trans.push('#tray-custom', _("Custom Icon:"), True)
trans.push('#str-tray-icon-builtin', _("Use a built-in icon"), True)
trans.push('#str-tray-icon-gtk', _("Use a theme icon (GTK)"), True)
trans.push('#str-tray-icon-custom', _("Use a custom image"), True)
trans.push('#str-gtk-example', _("Examples: ibus-keyboard, gnome-desktop-config"), True)
trans.push('#str-preview', _("Preview:"), True)
# If it's the first time loading, set default icon to desktop environment.
if not pref.exists("tray_icon", "type"):
common.set_default_tray_icon(pref)
# Populate built-in icons
def add_icon(uuid):
icon_name = icon_index[uuid]["name"]
icon_path = os.path.join(path.data_source, "tray", icon_index[uuid]["path"])
icon_info = icon_index[uuid]["info"]
onclick_cmd = "cmd('select-tray-icon-uuid?{0}'); $('.tray-uuid').removeClass('selected'); $('#tray-uuid-{0}').addClass('selected');".format(uuid)
self.update_page("#tray-icon-previews", "append", "<button id='tray-uuid-{0}' class='tray-uuid btn' onclick=\"{1}\"><img src='{2}'/></button>".format(uuid, onclick_cmd, icon_path))
icon_type = pref.get("tray_icon", "type", "builtin")
self.update_page("#tray-" + icon_type, "prop", "checked", "true")
self.webkit.run_javascript("show_only_relevant('.tray-options', '#tray-{0}-options')".format(icon_type))
icon_index = pref.load_file(os.path.join(path.data_source, "tray/icons.json"))
icons = sorted(list(icon_index.keys()))
for uuid in icons:
add_icon(uuid)
icon_value = pref.get("tray_icon", "value", "0")
if icon_type == "builtin":
self.update_page("#tray-uuid-" + icon_value, "addClass", "selected")
elif icon_type == "gtk":
self.update_page("#tray-icon-gtk", "val", icon_value)
elif icon_type == "custom":
self.update_page("#tray-icon-path", "val", icon_value)
########################
# Colours
########################
trans.push('#dialog-del-title', _("Reset Colors"))
trans.push('#dialog-del-hint', _("Are you sure you want to reset all colors to their defaults?"))
trans.push('#dialog-del-no', _("Cancel"))
trans.push('#dialog-del-yes', _("Reset Defaults"))
trans.push('#colour-choose', _("Choose..."))
trans.push('#colour-new', _("New"), True)
trans.push('#colour-reset', _("Restore Defaults"), True)
trans.push('#colour-save', _("Save"), True)
trans.push('#colour-revert', _("Revert"))
trans.push('#colour-delete', _("Delete"), True)
self.populate_colours_table()
# Reads and sets configuration set in razer.conf
self.config_path = os.path.join(os.path.expanduser('~'), ".razer-service", "razer.conf")
import configparser
self.daemon_config = configparser.ConfigParser()
########################
# Daemon
########################
trans.push('#str-daemon-title', _("About the Daemon"))
trans.push('#str-daemon-info', _("The daemon is the software that communicates between the front-end applications and the driver."))
trans.push('#str-website', _("Website"), True)
trans.push('#str-project', _("Project"), True)
trans.push('#str-issues', _("Issues"))
trans.push('#str-troubleshooting', _("Troubleshooting"))
trans.push('#str-device-support', _("Device/Daemon Support"))
trans.push('#str-logs', _("Logs"))
trans.push('#str-logs-help', _("Useful for diagnosing issues and debugging daemon-related operations."))
trans.push('#str-watch', _("Watch"), True)
trans.push('#str-daemon-options', _("Daemon Service"))
trans.push('#str-daemon-stop', _("Stop"))
trans.push('#str-daemon-restart', _("Restart"))
trans.push('#str-daemon-service', _("If you have re-plugged devices, or are experiencing glitches, try restarting the daemon service."))
trans.push('#str-options-missing', _("Could not read the daemon's configuration file."))
trans.push('#str-options-restart', _("The daemon (and Polychromatic) needs to be restarted for the new settings to take effect."))
if os.path.exists(self.config_path):
self.daemon_config.read(self.config_path)
else:
self.update_page("#daemon-options-missing", "show")
for element in ["verbose-logging", "sync-effects", "screensaver", "key-statistics"]:
self.update_page("#daemon-"+element, "addClass", "disabled")
self.update_page("#str-"+element, "addClass", "disabled")
def read_daemon_config(group, item, element, label, description):
"""
Sets the initial checkbox state for razer.conf daemon settings
"""
element_checkbox = "#daemon-" + element
element_label = "#str-" + element
element_help = "#str-" + element + "-help"
self.update_page(element_label, "append", label)
self.update_page(element_help, "html", description)
if not self.daemon_config.has_option(group, item):
self.update_page(element_checkbox, "addClass", "disabled")
self.update_page(element_label, "addClass", "disabled")
return
if self.daemon_config.get(group, item) == 'True':
self.update_page(element_checkbox, "prop", "checked", "true")
read_daemon_config("General", "verbose_logging", "verbose-logging", _("Verbose Logging"), _("Show lots of debug messages."))
read_daemon_config("Startup", "sync_effects_enabled", "sync-effects", _("Sync Effects to All Devices"), _("When setting an effect, apply this to all other connected devices (where supported)."))
read_daemon_config("Startup", "devices_off_on_screensaver", "screensaver", _("Turn off devices when screensaver is running"), _("Not all desktop environments support this feature."))
read_daemon_config("Statistics", "key_statistics", "key-statistics", _("Generate Key Statistics"), _("Collects number of key presses per hour for generating heatmaps."))
elif self.current_page == 'error':
self.update_page("#close-window", "html", _("Quit"))
self.update_page("#restart-app", "html", _("Retry"))
self.update_page("#restart-daemon", "html", _("Restart Daemon"))
self.update_page("#error-icon", "attr", "src", "../img/error/" + self.error_icon + ".png")
self.update_page("#error-title", "html", self.error_title)
self.update_page("#error-title", "addClass", self.error_class)
self.update_page("#error-details", "html", self.error_message)
else:
stdout.vvprint('No post-actions for this page.')
def refresh_profiles_list(self):
"""
Reloads the key light profiles created by the user.
"""
stdout.vvprint('Refreshing profile list...')
self.update_page('#app-profiles', 'html' , ' ')
uuid_in_use = pref.get_device_state(self.active_device.serial, "main", "profile")
# Function to append to page.
def append_item(uuid, data):
css_id = "app-" + uuid
title = data["name"]
title = title.replace("'", ''').replace('"', ''')
try:
icon_path = data["icon"]
except:
icon_path = path.data_source + "/img/profile-default.svg"
if self.current_page == "menu":
# Show highlight in UI if in use
extra_class = ""
if uuid_in_use:
if uuid == uuid_in_use:
extra_class = "active"
self.update_page('#app-profiles', 'append', "<button class='app-profile-item {4}' id='{0}' onclick='profile_list_change(\"{0}\", \"{3}\", \"{2}\")'><img src='{1}'>{2}</button>".format(css_id, icon_path, title, uuid, extra_class))
elif self.current_page == "preferences":
self.update_page('#profiles-list', 'append', "<option value='{1}'>{0}</option>".format(title, uuid))
# Sort the profiles A-Z.
sorted_names = {}
for uuid in self.profiles.list_profiles():
data = self.profiles.load_profile(str(uuid))
try:
human_name = data["name"]
except:
print("Profile UUID corrupt: " + str(uuid))
continue
sorted_names[human_name] = int(uuid)
item_no = 0
for program in sorted(sorted_names):
uuid = sorted_names[program]
data = self.profiles.load_profile(str(uuid))
item_no += 1
append_item(str(uuid), data)
def process_command(self, command):
"""
Processes a command passed from the page to Python.
"""
if command == 'quit':
quit()
## Effects & Keyboard Controls
elif command.startswith('brightness'):
"""
Expects: brightness?<source>?<value>
"""
source = command.split("?")[1]
value = command.split("?")[2]
try:
common.set_brightness(pref, self.active_device, source, value)
self.update_device_active_options()
except Exception as exception:
self.print_error(exception, str(_("Failed to set/change brightness for {0}.")).replace("{0}",self.active_device.name))
elif command.startswith('effect'):
"""
Expects: effect?<source>?<effect>?[params]
"""
source = command.split("?")[1]
effect = command.split("?")[2]
colours = pref.get_device_state(self.active_device.serial, source, "colour_primary")
try:
params = command.split("?")[3]
except Exception:
params = None
if colours == None:
colours = [0, 255, 0]
try:
common.set_lighting_effect(pref, self.active_device, source, effect, params)
self.update_lighting_options(source, effect)
except Exception as exception:
self.print_error(exception, str(_("Failed to set effect '{0}' for {1}.")).replace("{0}",effect).replace("{1}",self.active_device.name))
self.update_device_active_options()
self.update_background_header(colours)
elif command.startswith('dpi'):
try:
value = int(command.split("?")[1])
self.active_device.dpi = (value, value)
self.update_page("#dpi-value", "html", str(value))
pref.set_device_state(self.active_device.serial, "main", "dpi", value)
except Exception as exception:
self.print_error(exception, str(_("Failed to set effect '{0}' for {1}.")).replace("{0}",effect).replace("{1}",self.active_device.name))
elif command.startswith('poll-rate'):
try:
value = int(command.split("?")[1])
if value == 1:
actual_value = 125
if value == 2:
actual_value = 500
if value == 3:
actual_value = 1000
self.active_device.poll_rate = actual_value
self.update_page("#poll-rate-value", "html", str(actual_value) + "Hz")
except Exception as exception:
self.print_error(exception, str(_("Failed to set poll rate for '{device_name}' to {poll_rate}.")).replace("{device_name}", self.active_device).replace("{poll_rate}",str(value)))