-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
__main__.py
3064 lines (2419 loc) · 114 KB
/
__main__.py
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
# Copyright (c) 2016 - 2017 Sylvia van Os <sylvia@hackerchick.me>
#
# This file is part of Pext
#
# Pext 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 3 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/>.
"""Pext.
This is the main Pext file. It will initialize, run and manage the whole of
Pext.
"""
import argparse
import atexit
import configparser
import json
import os
import platform
import signal
import sys
import threading
import time
import traceback
import webbrowser
import tempfile
from datetime import datetime
from enum import IntEnum
from importlib import reload # type: ignore
from inspect import getmembers, isfunction, ismethod, signature
from pkg_resources import parse_version
from shutil import rmtree
from subprocess import check_call, CalledProcessError, Popen
try:
from typing import Dict, List, Optional, Tuple
except ImportError:
from backports.typing import Dict, List, Optional, Tuple # type: ignore
from urllib.request import urlopen
from queue import Queue, Empty
from dulwich import porcelain
from dulwich.repo import Repo
from PyQt5.QtCore import QStringListModel, QLocale, QTranslator, Qt
from PyQt5.QtWidgets import (QApplication, QDialog, QDialogButtonBox,
QInputDialog, QLabel, QLineEdit, QMainWindow,
QMessageBox, QTextEdit, QVBoxLayout,
QStyleFactory, QSystemTrayIcon)
from PyQt5.Qt import QClipboard, QIcon, QObject, QQmlApplicationEngine, QQmlComponent, QQmlContext, QQmlProperty, QUrl
from PyQt5.QtGui import QPalette, QColor
# FIXME: Workaround for https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
warn_no_openGL_linux = False
if platform.system() == "Linux":
try:
from OpenGL import GL # NOQA
except ImportError:
warn_no_openGL_linux = True
class AppFile():
"""Get access to application-specific files."""
@staticmethod
def get_path() -> str:
"""Return the absolute current path."""
return os.path.dirname(os.path.abspath(__file__))
# Ensure pext_base and pext_helpers can always be loaded by us and the modules
sys.path.append(os.path.join(AppFile.get_path(), 'helpers'))
sys.path.append(os.path.join(AppFile.get_path()))
from pext_base import ModuleBase # noqa: E402
from pext_helpers import Action, SelectionType # noqa: E402
class MinimizeMode(IntEnum):
"""A list of possible ways Pext can react on minimization."""
Normal = 0
Tray = 1
NormalManualOnly = 2
TrayManualOnly = 3
class SortMode(IntEnum):
"""A list of possible ways Pext can sort module entries."""
Module = 0
Ascending = 1
Descending = 2
class ConfigRetriever():
"""Retrieve global configuration entries."""
def __init__(self) -> None:
"""Initialize the configuration location."""
# Initialze defaults
try:
config_home = os.environ['XDG_CONFIG_HOME']
except Exception:
config_home = os.path.join(os.path.expanduser('~'), '.config')
self.config = {'config_path': os.path.join(config_home, 'pext')}
def get_setting(self, variable: str) -> str:
"""Get a specific configuration setting."""
return self.config[variable]
def get_updatecheck_permission_asked(self) -> bool:
"""Return info on if allowing updates was asked."""
try:
with open(os.path.join(self.get_setting('config_path'), 'update_check_enabled'), 'r'):
return True
except (FileNotFoundError):
return False
def get_updatecheck_permission(self) -> bool:
"""Return info on if update checking is allowed."""
try:
with open(os.path.join(self.get_setting('config_path'), 'update_check_enabled'), 'r') as update_check_file:
result = update_check_file.readline()
return True if result == str(1) else False
except (FileNotFoundError):
return False
def save_updatecheck_permission(self, granted: bool) -> None:
"""Save the current updatecheck permission status."""
with open(os.path.join(self.get_setting('config_path'), 'update_check_enabled'), 'w') as update_check_file:
update_check_file.write(str(int(granted)))
class RunConseq():
"""A simple helper to run several functions consecutively."""
def __init__(self, functions: List) -> None:
"""Run the given function consecutively."""
for function in functions:
if len(function['args']) > 0:
function['name'](function['args'], **function['kwargs'])
else:
function['name'](**function['kwargs'])
class InputDialog(QDialog):
"""A simple dialog requesting user input."""
def __init__(self, question: str, text: str, parent=None) -> None:
"""Initialize the dialog."""
super().__init__(parent)
self.setWindowTitle("Pext")
layout = QVBoxLayout(self)
layout.addWidget(QLabel(question))
self.text_edit = QTextEdit(self)
self.text_edit.setPlainText(text)
layout.addWidget(self.text_edit)
button = QDialogButtonBox(QDialogButtonBox.Ok)
button.accepted.connect(self.accept)
layout.addWidget(button)
def show(self) -> Tuple[str, bool]:
"""Show the dialog."""
result = self.exec_()
return (self.text_edit.toPlainText(), result == QDialog.Accepted)
class Logger():
"""Log events to the appropriate location.
Shows events in the main window and, if the main window is not visible,
as a desktop notification.
"""
def __init__(self, window: 'Window') -> None:
"""Initialize the logger and add a status bar to the main window."""
self.window = window
self.queued_messages = [] # type: List[Dict[str, str]]
self.last_update = None # type: Optional[float]
self.status_text = self.window.window.findChild(QObject, "statusText")
self.status_queue = self.window.window.findChild(QObject, "statusQueue")
def _queue_message(self, module_name: str, message: str, type_name: str) -> None:
"""Queue a message for display."""
for formatted_message in self._format_message(module_name, message):
self.queued_messages.append(
{'message': formatted_message, 'type': type_name})
def _format_message(self, module_name: str, message: str) -> List[str]:
"""Format message for display, including splitting multiline messages."""
message_lines = []
for line in message.splitlines():
if not (not line or line.isspace()):
if module_name:
message = '{}: {}'.format(module_name, line)
else:
message = line
message_lines.append(message)
return message_lines
@staticmethod
def _log(message: str, logger=None) -> None:
"""If a logger is provided, log to the logger. Otherwise, print."""
if logger:
logger.add_message("", message)
else:
print(message)
@staticmethod
def _log_error(message: str, logger=None) -> None:
"""If a logger is provided, log to the logger. Otherwise, print."""
if logger:
logger.add_error("", message)
else:
print(message)
def show_next_message(self) -> None:
"""Show next statusbar message.
If the status bar has not been updated for 1 second, display the next
message. If no messages are available, clear the status bar after it
has been displayed for 5 seconds.
"""
current_time = time.time()
time_diff = 5 if len(self.queued_messages) < 1 else 1
if self.last_update and current_time - time_diff < self.last_update:
return
if len(self.queued_messages) == 0:
QQmlProperty.write(self.status_text, "text", "")
self.last_update = None
else:
message = self.queued_messages.pop(0)
if message['type'] == 'error':
statusbar_message = "<font color='red'>⚠ {}</color>".format(
message['message'])
notification_message = '⚠ {}'.format(message['message'])
else:
statusbar_message = message['message']
notification_message = message['message']
QQmlProperty.write(self.status_text, "text", statusbar_message)
if self.window.window.windowState() == Qt.WindowMinimized or not self.window.window.isVisible():
try:
Popen(['notify-send', 'Pext', notification_message])
except Exception as e:
print("Could not open notify-send: {}. Notification follows after exception:".format(e))
traceback.print_exc()
print(notification_message)
self.last_update = current_time
def add_error(self, module_name: str, message: str) -> None:
"""Add an error message to the queue."""
self._queue_message(module_name, message, 'error')
def add_message(self, module_name: str, message: str) -> None:
"""Add a regular message to the queue."""
self._queue_message(module_name, message, 'message')
def set_queue_count(self, count: List[int]) -> None:
"""Show the queue size on screen."""
QQmlProperty.write(self.status_queue, "entriesLeftForeground", count[0])
QQmlProperty.write(self.status_queue, "entriesLeftBackground", count[1])
class MainLoop():
"""Main application loop.
The main application loop connects the application, queue and UI events and
ensures these events get managed without locking up the UI.
"""
def __init__(self, app: QApplication, window: 'Window', logger: Logger) -> None:
"""Initialize the main loop."""
self.app = app
self.window = window
self.logger = logger
def _process_tab_action(self, tab: Dict, active_tab: int) -> None:
action = tab['queue'].get_nowait()
if action[0] == Action.critical_error:
self.logger.add_error(tab['module_name'], str(action[1]))
tab_id = self.window.tab_bindings.index(tab)
self.window.module_manager.unload_module(self.window, tab_id)
elif action[0] == Action.add_message:
self.logger.add_message(tab['module_name'], str(action[1]))
elif action[0] == Action.add_error:
self.logger.add_error(tab['module_name'], str(action[1]))
elif action[0] == Action.add_entry:
tab['vm'].entry_list = tab['vm'].entry_list + [action[1]]
elif action[0] == Action.prepend_entry:
tab['vm'].entry_list = [action[1]] + tab['vm'].entry_list
elif action[0] == Action.remove_entry:
tab['vm'].entry_list.remove(action[1])
elif action[0] == Action.replace_entry_list:
if len(action) > 1:
tab['vm'].entry_list = action[1]
else:
tab['vm'].entry_list = []
elif action[0] == Action.add_command:
tab['vm'].command_list = tab['vm'].command_list + [action[1]]
elif action[0] == Action.prepend_command:
tab['vm'].command_list = [action[1]] + tab['vm'].command_list
elif action[0] == Action.remove_command:
tab['vm'].command_list.remove(action[1])
elif action[0] == Action.replace_command_list:
if len(action) > 1:
tab['vm'].command_list = action[1]
else:
tab['vm'].command_list = []
elif action[0] == Action.set_header:
if len(action) > 1:
tab['vm'].set_header(str(action[1]))
else:
tab['vm'].set_header("")
elif action[0] == Action.set_filter:
if len(action) > 1:
QQmlProperty.write(tab['vm'].search_input_model, "text", str(action[1]))
else:
QQmlProperty.write(tab['vm'].search_input_model, "text", "")
elif action[0] == Action.ask_question_default_yes:
answer = QMessageBox.question(
self.window,
"Pext",
action[1],
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes)
if len(signature(tab['vm'].module.process_response).parameters) == 2:
tab['vm'].module.process_response(
True if (answer == QMessageBox.Yes) else False,
action[2] if len(action) > 2 else None)
else:
tab['vm'].module.process_response(
True if (answer == QMessageBox.Yes) else False)
elif action[0] == Action.ask_question_default_no:
answer = QMessageBox.question(
self.window,
"Pext",
action[1],
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if len(signature(tab['vm'].module.process_response).parameters) == 2:
tab['vm'].module.process_response(
True if (answer == QMessageBox.Yes) else False,
action[2] if len(action) > 2 else None)
else:
tab['vm'].module.process_response(
True if (answer == QMessageBox.Yes) else False)
elif action[0] == Action.ask_input:
answer, ok = QInputDialog.getText(
self.window,
"Pext",
action[1],
QLineEdit.Normal,
action[2] if len(action) > 2 else "")
if len(signature(tab['vm'].module.process_response).parameters) == 2:
tab['vm'].module.process_response(
answer if ok else None,
action[3] if len(action) > 3 else None)
else:
tab['vm'].module.process_response(
answer if ok else None)
elif action[0] == Action.ask_input_password:
answer, ok = QInputDialog.getText(
self.window,
"Pext",
action[1],
QLineEdit.Password,
action[2] if len(action) > 2 else "")
if len(signature(tab['vm'].module.process_response).parameters) == 2:
tab['vm'].module.process_response(
answer if ok else None,
action[3] if len(action) > 3 else None)
else:
tab['vm'].module.process_response(
answer if ok else None)
elif action[0] == Action.ask_input_multi_line:
dialog = InputDialog(
action[1],
action[2] if len(action) > 2 else "",
self.window)
answer, ok = dialog.show()
if len(signature(tab['vm'].module.process_response).parameters) == 2:
tab['vm'].module.process_response(
answer if ok else None,
action[3] if len(action) > 3 else None)
else:
tab['vm'].module.process_response(
answer if ok else None)
elif action[0] == Action.copy_to_clipboard:
# Copy the given data to the user-chosen clipboard
if Settings.get('clipboard') == 'selection':
mode = QClipboard.Selection
else:
mode = QClipboard.Clipboard
self.app.clipboard().setText(str(action[1]), mode)
elif action[0] == Action.set_selection:
if len(action) > 1:
tab['vm'].selection = action[1]
else:
tab['vm'].selection = []
tab['vm'].context.setContextProperty(
"resultListModelDepth", len(tab['vm'].selection))
tab['vm'].make_selection()
elif action[0] == Action.close:
self.window.close()
tab['vm'].selection = []
tab['vm'].context.setContextProperty(
"resultListModelDepth", len(tab['vm'].selection))
tab['vm'].module.selection_made(tab['vm'].selection)
elif action[0] == Action.set_entry_info:
if len(action) > 2:
tab['vm'].extra_info_entries[str(action[1])] = str(action[2])
else:
try:
del tab['vm'].extra_info_entries[str(action[1])]
except KeyError:
pass
tab['vm'].update_context_info_panel(request_update=False)
elif action[0] == Action.replace_entry_info_dict:
if len(action) > 1:
tab['vm'].extra_info_entries = action[1]
else:
tab['vm'].extra_info_entries = {}
tab['vm'].update_context_info_panel(request_update=False)
elif action[0] == Action.set_command_info:
if len(action) > 2:
tab['vm'].extra_info_commands[str(action[1])] = str(action[2])
else:
try:
del tab['vm'].extra_info_commands[str(action[1])]
except KeyError:
pass
tab['vm'].update_context_info_panel(request_update=False)
elif action[0] == Action.replace_command_info_dict:
if len(action) > 1:
tab['vm'].extra_info_commands = action[1]
else:
tab['vm'].extra_info_commands = {}
tab['vm'].update_context_info_panel(request_update=False)
elif action[0] == Action.set_base_info:
if len(action) > 1:
tab['vm'].update_base_info_panel(action[1])
else:
tab['vm'].update_base_info_panel("")
elif action[0] == Action.set_entry_context:
if len(action) > 2:
tab['vm'].context_menu_entries[str(action[1])] = action[2]
else:
try:
del tab['vm'].context_menu_entries[str(action[1])]
except KeyError:
pass
elif action[0] == Action.replace_entry_context_dict:
if len(action) > 1:
tab['vm'].context_menu_entries = action[1]
else:
tab['vm'].context_menu_entries = {}
elif action[0] == Action.set_command_context:
if len(action) > 2:
tab['vm'].context_menu_commands[str(action[1])] = action[2]
else:
try:
del tab['vm'].context_menu_commands[str(action[1])]
except KeyError:
pass
elif action[0] == Action.replace_command_context_dict:
if len(action) > 1:
tab['vm'].context_menu_commands = action[1]
else:
tab['vm'].context_menu_commands = {}
elif action[0] == Action.set_base_context:
if len(action) > 0:
tab['vm'].context_menu_base = action[1]
else:
tab['vm'].context_menu_base = []
else:
print('WARN: Module requested unknown action {}'.format(action[0]))
if active_tab and tab['entries_processed'] >= 100:
tab['vm'].search(new_entries=True)
tab['entries_processed'] = 0
self.window.update()
tab['queue'].task_done()
def run(self) -> None:
"""Process actions modules put in the queue and keep the window working."""
while True:
self.app.sendPostedEvents()
self.app.processEvents()
self.logger.show_next_message()
current_tab = QQmlProperty.read(self.window.tabs, "currentIndex")
queue_size = [0, 0]
all_empty = True
for tab_id, tab in enumerate(self.window.tab_bindings):
if not tab['init']:
continue
if tab_id == current_tab:
queue_size[0] = tab['queue'].qsize()
active_tab = True
tab['vm'].context.setContextProperty(
"resultListModelHasEntries", True if tab['vm'].entry_list or tab['vm'].command_list else False)
else:
queue_size[1] += tab['queue'].qsize()
active_tab = False
try:
self._process_tab_action(tab, active_tab)
tab['entries_processed'] += 1
all_empty = False
except Empty:
if active_tab and tab['entries_processed']:
tab['vm'].search(new_entries=True)
tab['entries_processed'] = 0
except Exception as e:
print('WARN: Module {} caused exception {}'.format(tab['module_name'], e))
traceback.print_exc()
self.logger.set_queue_count(queue_size)
if all_empty:
if self.window.window.isVisible():
time.sleep(0.01)
else:
time.sleep(0.1)
class ProfileManager():
"""Create, remove, list, load and save to a profile."""
def __init__(self, config_retriever: ConfigRetriever) -> None:
"""Initialize the profile manager."""
self.profile_dir = os.path.join(config_retriever.get_setting('config_path'), 'profiles')
self.config_retriever = config_retriever
self.saved_settings = ['clipboard', 'locale', 'minimize_mode', 'sort_mode', 'theme', 'tray']
self.enum_settings = ['minimize_mode', 'sort_mode']
@staticmethod
def _get_pid_path(profile: str) -> str:
return os.path.join(tempfile.gettempdir(), 'pext_{}.pid'.format(profile))
@staticmethod
def lock_profile(profile: str) -> None:
"""Claim the profile as in-use."""
pidfile = ProfileManager._get_pid_path(profile)
pid = str(os.getpid())
open(pidfile, 'w').write(pid)
@staticmethod
def get_lock_instance(profile: str) -> Optional[int]:
"""Get the pid of the current process having a lock, if any."""
pidfile = ProfileManager._get_pid_path(profile)
if os.path.isfile(pidfile):
pid = int(open(pidfile, 'r').read())
if platform.system() == 'Windows':
return True
try:
os.kill(pid, 0)
except ProcessLookupError:
return None
return pid
@staticmethod
def unlock_profile(profile: str) -> None:
"""Remove the status of the profile currently being in use."""
pidfile = ProfileManager._get_pid_path(profile)
os.unlink(pidfile)
@staticmethod
def default_profile_name() -> str:
"""Return the default profile name."""
return "default"
def create_profile(self, profile: str) -> bool:
"""Create a new empty profile if name not in use already."""
try:
os.mkdir(os.path.join(self.profile_dir, profile))
except OSError:
return False
return True
def rename_profile(self, old_name: str, new_name: str) -> bool:
"""Rename a profile that's currently not in use, if the new name doesn't already exist."""
if ProfileManager.get_lock_instance(old_name):
return False
try:
os.rename(os.path.join(self.profile_dir, old_name), os.path.join(self.profile_dir, new_name))
except OSError:
return False
return True
def remove_profile(self, profile: str) -> bool:
"""Remove a profile and all associated data if not in use."""
if ProfileManager.get_lock_instance(profile):
return False
rmtree(os.path.join(self.profile_dir, profile))
return True
def list_profiles(self) -> List:
"""List the existing profiles."""
return os.listdir(self.profile_dir)
def save_modules(self, profile: str, modules: List[Dict]) -> None:
"""Save the list of open modules and their settings to the profile."""
config = configparser.ConfigParser()
for number, module in enumerate(modules):
name = ModuleManager.add_prefix(module['module_name'])
settings = {}
for setting in module['settings']:
# Only save non-internal variables
if setting[0] != "_":
settings[setting] = module['settings'][setting]
config['{}_{}'.format(number, name)] = settings
with open(os.path.join(self.profile_dir, profile, 'modules'), 'w') as configfile:
config.write(configfile)
def retrieve_modules(self, profile: str) -> List[Dict]:
"""Retrieve the list of modules and their settings from the profile."""
config = configparser.ConfigParser()
modules = []
config.read(os.path.join(self.profile_dir, profile, 'modules'))
for module in config.sections():
settings = {}
for key in config[module]:
settings[key] = config[module][key]
modules.append(
{'name': module.split('_', 1)[1], 'settings': settings})
return modules
def save_settings(self, profile: str) -> None:
"""Save the current settings to the profile."""
config = configparser.ConfigParser()
settings_to_store = {}
for setting in Settings.get_all():
if setting in self.saved_settings:
setting_data = Settings.get(setting).value if setting in self.enum_settings else Settings.get(setting)
if setting_data is not None:
settings_to_store[setting] = setting_data
config['settings'] = settings_to_store
with open(os.path.join(self.profile_dir, profile, 'settings'), 'w') as configfile:
config.write(configfile)
def retrieve_settings(self, profile: str) -> Dict:
"""Retrieve the settings from the profile."""
config = configparser.ConfigParser()
settings = {} # type: Dict[str, Any]
config.read(os.path.join(self.profile_dir, profile, 'settings'))
try:
for setting in config['settings']:
if setting in self.saved_settings:
Settings.set(setting, config['settings'][setting])
except KeyError:
pass
return settings
class ObjectManager():
"""Shared management for modules and themes."""
@staticmethod
def list_objects(core_directory: str) -> Dict[str, Dict[str, Dict[str, str]]]:
"""Return a list of objects together with their source."""
objects = {}
for directory in os.listdir(core_directory):
if not os.path.isdir(os.path.join(core_directory, directory)):
continue
name = directory
name = ModuleManager.remove_prefix(name)
name = ThemeManager.remove_prefix(name)
try:
source = UpdateManager.get_remote_url(os.path.join(core_directory, directory))
except Exception:
source = None
try:
with open(os.path.join(core_directory, directory, "metadata.json"), 'r') as metadata_json:
metadata = json.load(metadata_json)
except (FileNotFoundError, json.decoder.JSONDecodeError):
print("Object {} lacks a metadata.json file".format(name))
metadata = {}
# Add revision last updated time
if source:
try:
version = UpdateManager.get_version(os.path.join(core_directory, directory))
metadata['version'] = version
except Exception:
pass
try:
last_updated = UpdateManager.get_last_updated(os.path.join(core_directory, directory))
metadata['last_updated'] = str(last_updated)
except Exception:
pass
objects[name] = {"source": source, "metadata": metadata}
return objects
class ModuleManager():
"""Install, remove, update and list modules."""
def __init__(self, config_retriever: ConfigRetriever) -> None:
"""Initialize the module manager."""
self.config_retriever = config_retriever
self.module_dir = os.path.join(self.config_retriever.get_setting('config_path'),
'modules')
self.module_dependencies_dir = os.path.join(self.config_retriever.get_setting('config_path'),
'module_dependencies')
self.logger = None # type: Optional[Logger]
@staticmethod
def add_prefix(module_name: str) -> str:
"""Ensure the string starts with pext_module_."""
if not module_name.startswith('pext_module_'):
return 'pext_module_{}'.format(module_name)
return module_name
@staticmethod
def remove_prefix(module_name: str) -> str:
"""Remove pext_module_ from the start of the string."""
if module_name.startswith('pext_module_'):
return module_name[len('pext_module_'):]
return module_name
def _pip_install(self, module_dir_name: str) -> int:
"""Install module dependencies using pip."""
module_requirements_path = os.path.join(self.module_dir, module_dir_name, 'requirements.txt')
module_dependencies_path = os.path.join(self.module_dependencies_dir, module_dir_name)
if not os.path.isfile(module_requirements_path):
return 0
try:
os.mkdir(module_dependencies_path)
except OSError:
# Probably already exists, that's okay
pass
# Create the pip command
pip_command = [sys.executable,
'-m',
'pip',
'install']
# FIXME: Cheap hack to work around Debian's faultily-patched pip
if os.path.isfile('/etc/debian_version'):
pip_command += ['--system']
pip_command += ['--upgrade',
'--target',
module_dependencies_path,
'-r',
module_requirements_path]
returncode = 0
# FIXME: Cheap macOS workaround, part 1
# See https://github.com/pypa/pip/pull/4111#issuecomment-280616124
if platform.system() == "Darwin":
with open(os.path.expanduser('~/.pydistutils.cfg'), 'w') as macos_workaround:
macos_workaround.write('[install]\nprefix=')
# Actually run the pip command
try:
check_call(pip_command)
except CalledProcessError as e:
returncode = e.returncode
# FIXME: Cheap macOS workaround, part 2
if platform.system() == "Darwin":
os.remove(os.path.expanduser('~/.pydistutils.cfg'))
return returncode
def bind_logger(self, logger: Logger) -> None:
"""Connect a logger to the module manager.
If a logger is connected, the module manager will log all
messages directly to the logger.
"""
self.logger = logger
def load_module(self, window: 'Window', module: Dict, locale: str) -> bool:
"""Load a module and attach it to the main window."""
# Append modulePath if not yet appendend
module_path = os.path.join(self.config_retriever.get_setting('config_path'), 'modules')
if module_path not in sys.path:
sys.path.append(module_path)
# Remove pext_module_ from the module name
module_dir = ModuleManager.add_prefix(module['name']).replace('.', '_')
module_name = ModuleManager.remove_prefix(module['name'])
# Append module dependencies path if not yet appended
module_dependencies_path = os.path.join(self.config_retriever.get_setting('config_path'),
'module_dependencies',
module_dir)
if module_dependencies_path not in sys.path:
sys.path.append(module_dependencies_path)
# Prepare viewModel and context
vm = ViewModel()
module_context = QQmlContext(window.context)
module_context.setContextProperty(
"resultListModel", vm.result_list_model_list)
module_context.setContextProperty(
"resultListModelNormalEntries", len(vm.filtered_entry_list))
module_context.setContextProperty(
"resultListModelCommandEntries", len(vm.filtered_command_list))
module_context.setContextProperty(
"resultListModelHasEntries", False)
module_context.setContextProperty(
"resultListModelCommandMode", False)
module_context.setContextProperty(
"resultListModelDepth", 0)
module_context.setContextProperty(
"contextMenuModel", vm.context_menu_model_list)
module_context.setContextProperty(
"contextMenuEnabled", False)
# Prepare module
try:
module_import = __import__(module_dir, fromlist=['Module'])
except ImportError as e1:
Logger._log_error(
"Failed to load module {} from {}: {}".format(module_name, module_dir, e1),
self.logger)
# Remove module dependencies path
sys.path.remove(module_dependencies_path)
return False
Module = getattr(module_import, 'Module')
# Ensure the module implements the base
assert issubclass(Module, ModuleBase)
# Set up a queue so that the module can communicate with the main
# thread
q = Queue() # type: Queue
# Load module
try:
module_code = Module()
except TypeError as e2:
Logger._log_error(
"Failed to load module {} from {}: {}".format(module_name, module_dir, e2),
self.logger)
return False
# Check if the required functions have enough parameters
required_param_lengths = {}
for name, value in getmembers(ModuleBase, isfunction):
required_param_lengths[name] = len(signature(value).parameters) - 1 # Python is inconsistent with self
for name, value in getmembers(module_code, ismethod):
try:
required_param_length = required_param_lengths[name]
except KeyError:
continue
param_length = len(signature(value).parameters)
if param_length != required_param_length:
if name == 'process_response' and param_length == 1:
print("WARN: Module {} uses old process_response signature and will not be able to receive an "
"identifier if requested".format(module_name))
else:
Logger._log_error(
"Failed to load module {} from {}: {} function has {} parameters (excluding self), expected {}"
.format(module_name, module_dir, name, param_length, required_param_length),
self.logger)
return False
# Prefill API version and locale
module['settings']['_api_version'] = [0, 7, 0]
module['settings']['_locale'] = locale
# Start the module in the background
module_thread = ModuleThreadInitializer(
module_name,
q,
target=module_code.init,
args=(module['settings'], q))
module_thread.start()
# Add tab
tab_data = QQmlComponent(window.engine)
tab_data.loadUrl(
QUrl.fromLocalFile(os.path.join(AppFile.get_path(), 'qml', 'ModuleData.qml')))
window.engine.setContextForObject(tab_data, module_context)
window.tabs.addTab(module_name, tab_data)
# Store tab/viewModel combination
# tabData is not used but stored to prevent segfaults caused by
# Python garbage collecting it
window.tab_bindings.append({'init': False,
'queue': q,
'vm': vm,
'module': module_code,