-
Notifications
You must be signed in to change notification settings - Fork 0
/
synchronizer.py
1957 lines (1683 loc) · 87.6 KB
/
synchronizer.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
from __future__ import annotations
import datetime
import json
import os
import shutil
import sys
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional, Union, cast, no_type_check
import gi
import jsonschema
import watchdog.events as we
import watchdog.observers as wo
gi.require_version(namespace="Gtk", version="3.0")
gi.require_version(namespace="AppIndicator3", version="0.1")
from gi.repository import AppIndicator3, GdkPixbuf, Gio, GLib, GObject, Gtk, Pango # type: ignore
class Application(Gtk.Application):
"""
Core class
"""
def __init__(self, application_id: str) -> None:
super().__init__(application_id=application_id)
# Paired Folders
self.paired_folders_app: Dict[str, PairedFolder] = {}
# AppIndicator
self._appindicator: Optional[AppIndicator] = None
# GUI
self._gui: Optional[GUI] = None
self._block_gui: bool = False
self.setup_application()
@property
def appindicator(self) -> AppIndicator:
return cast(AppIndicator, self._appindicator)
@property
def gui(self) -> GUI:
return cast(GUI, self._gui)
def setup_application(self) -> None:
GLib.set_prgname(self.get_application_id())
self.connect("startup", lambda gtk_application: self.read_config())
self.connect("activate", lambda gtk_application: self.start_app())
def read_config(self) -> None:
"""
Reads from config file and sets the configuration based on it. Callback of application's "startup" signal
"""
if not config_file.is_file():
return
# Reading from config file
config_data: Dict[str, Dict[str, Dict[str, Union[str, Dict[str, Union[bool, int]]]]]] = {}
with config_file.open(mode="r") as config_:
try:
config_data = json.load(fp=config_)
except:
pass
if not config_data:
return
# Validating json file against schema
is_schema_valid: bool = True
try:
jsonschema.validate(instance=config_data, schema=json_schema)
except:
is_schema_valid = False
dialog = self.create_dialog(
parent=None,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text="An error occured reading the configuration file",
text2="The data of the configuration does not follow the valid schema, no settings were read.",
)
self._block_gui = True
dialog.run()
dialog.destroy()
self._block_gui = False
# Validation of the data
def validate_data() -> None:
"""
Validates the data of the config file
"""
valid_paired_folders: Dict[str, PairedFolder] = {}
errors: Dict[str, List[str]] = {}
for paired_folder in config_data["paired_folders"]:
pf: PairedFolder = PairedFolder(
alias=paired_folder,
source=cast(str, config_data["paired_folders"][paired_folder]["source"]),
target=cast(str, config_data["paired_folders"][paired_folder]["target"]),
buffer_size=cast(Dict[str, int], config_data["paired_folders"][paired_folder]["options"])[
"buffer_size"
],
include_hidden_files=cast(Dict[str, bool], config_data["paired_folders"][paired_folder]["options"])[
"include_hidden_files"
],
autostart_sync=cast(Dict[str, bool], config_data["paired_folders"][paired_folder]["options"])[
"autostart_sync"
],
is_config_saved=True,
)
errors_pf: List[str] = pf.validate_from_config(valid_paired_folders=valid_paired_folders)
if len(errors_pf):
errors[pf.alias] = errors_pf
else:
valid_paired_folders[str(uuid.uuid4())] = pf
# Show the errors on a dialog if there is any
if len(errors):
text: str = "There are some errors on the data in the configuration file, the invalid settings were not applied."
for key, value in errors.items():
text += f"\n\n<b>{key}:</b>"
for err in value:
text += f"\n - {err}"
dialog = self.create_dialog(
parent=None,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text="An error occured reading the configuration file",
text2=text,
)
def cb_dialog() -> None:
self._block_gui = False
dialog.destroy()
self._block_gui = True
dialog.connect("response", lambda gtk_dialog, responde_id: cb_dialog())
dialog.show()
self.paired_folders_app = valid_paired_folders
# If the config file follows the valid jsonschema then we validate the data
if is_schema_valid:
validate_data()
def start_app(self) -> None:
"""
Initializes the AppIndicator and the User Interface. Callbak of application's "activate" signal
"""
if self._appindicator is None:
self._appindicator = AppIndicator(application=self)
if self._gui is None:
self._gui = GUI(application=self, builder=self.get_new_builder())
else: # Show main window when there's a try to open a new instance of the application
self.gui.window.present()
def create_dialog(
self,
parent: Optional[Gtk.Window],
message_type: Gtk.MessageType,
buttons: Gtk.ButtonsType,
text: str,
text2: str,
modal: bool = True,
) -> Gtk.MessageDialog:
"""
Creates a Gtk.MessageDialog and returns it
"""
dialog: Gtk.MessageDialog = Gtk.MessageDialog(
title=global_title, parent=parent, modal=modal, message_type=message_type, buttons=buttons, text=text
)
if len(text2):
dialog.format_secondary_markup(message_format=text2)
dialog.set_icon(icon=GdkPixbuf.Pixbuf.new_from_file(filename=str(icon)))
if parent is not None:
dialog.set_skip_taskbar_hint(setting=parent.is_visible())
dialog.set_position(position=Gtk.WindowPosition.CENTER_ALWAYS)
return dialog
def create_file_chooser_dialog(
self, parent: Optional[Gtk.Window], title: str, modal: bool = True, path: Optional[Path] = None
) -> Gtk.FileChooserDialog:
"""
Creates a Gtk.FileChooserDialog with specified title and current folder
"""
file_chooser_dialog: Gtk.FileChooserDialog = Gtk.FileChooserDialog(
action=Gtk.FileChooserAction.SELECT_FOLDER, parent=parent, title=title
)
file_chooser_dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
file_chooser_dialog.add_button(Gtk.STOCK_OK, Gtk.ResponseType.OK)
file_chooser_dialog.set_filename(filename=str(Path.home()) if path is None else str(path))
file_chooser_dialog.set_modal(modal=modal)
filter_dialog: Gtk.FileFilter = Gtk.FileFilter()
filter_dialog.add_mime_type(mime_type="inode/directory")
file_chooser_dialog.set_filter(filter=filter_dialog)
return file_chooser_dialog
def get_new_builder(self) -> Gtk.Builder:
"""
Returns a new instance of Gtk.Builder with the content of the ui file
"""
return cast(Gtk.Builder, Gtk.Builder.new_from_string(string=ui_content, length=len(ui_content))) # type: ignore
@staticmethod
def open_file_manager(path: Path) -> bool:
"""
Open file manager using `org.freedesktop.FileManager1` interface
"""
uri_path: str = f"file://{str(path)}"
try:
proxy_interface_file_manager: Gio.DBusProxy = Gio.DBusProxy.new_for_bus_sync(
bus_type=Gio.BusType.SESSION,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name="org.freedesktop.FileManager1",
object_path="/org/freedesktop/FileManager1",
interface_name="org.freedesktop.FileManager1",
cancellable=None,
)
parameters: GLib.Variant = GLib.Variant.new_tuple(
GLib.Variant.new_array(
child_type=GLib.VariantType.new(type_string="s"),
children=[GLib.Variant.new_string(string=uri_path)],
),
GLib.Variant.new_string(string=""), # type: ignore
)
proxy_interface_file_manager.call_sync(
method_name="ShowItems" if not str(path) == "/" else "ShowFolders",
parameters=parameters,
flags=Gio.DBusCallFlags.NONE,
timeout_msec=-1,
cancellable=None,
)
return True
except:
return False
def app_save_config(self, uuid: Optional[str] = None, exclude: bool = False) -> bool:
"""
Save configuration to configuration file
"""
config_to_save: Dict[str, Dict[str, Dict[str, Union[str, Dict[str, Union[int, bool]]]]]] = {
"paired_folders": {}
}
if uuid is not None: # Save single paired folder
for uuid_, paired_folder in self.paired_folders_app.items():
if (uuid != uuid_) and not paired_folder._is_config_saved:
continue
if exclude and (uuid == uuid_):
continue
config_to_save["paired_folders"][
paired_folder.alias if uuid == uuid_ else cast(str, paired_folder._original_state["alias"])
] = paired_folder.build_json(original_state=uuid != uuid_)
else: # Save all configured tabs to configuration file
for uuid_, paired_folder in self.paired_folders_app.items():
if not paired_folder.is_valid:
continue
config_to_save["paired_folders"][paired_folder.alias] = paired_folder.build_json()
result: bool = True
try:
with config_file.open(mode="w") as file_:
json.dump(obj=config_to_save, fp=file_, ensure_ascii=False, indent=4)
except:
result = False
return result
def exit_(self) -> None:
try:
self.gui._notebook.stop_observers()
self.quit()
except Exception as e:
print(f"EXCEPTION: {e}")
exit()
## Signals
@GObject.Signal( # type: ignore
name="app-add-paired-folder",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_STRING,
arg_types=[GObject.TYPE_STRING],
)
def app_add_paired_folder(self, alias: str) -> str:
uuid_: str = str(uuid.uuid4())
self.paired_folders_app[uuid_] = PairedFolder(alias=alias)
return uuid_
@GObject.Signal( # type: ignore
name="app-update-paired-folder",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_PYOBJECT],
)
def app_update_paired_folder(self, uuid: str, key: str, value: Optional[Union[bool, int, Path]]) -> None:
setattr(self.paired_folders_app[uuid], key, value)
@GObject.Signal( # type: ignore
name="app-delete-paired-folder",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING],
)
def app_delete_paired_folder(self, uuid: str) -> None:
if not self.paired_folders_app[uuid]._is_config_saved:
del self.paired_folders_app[uuid]
@GObject.Signal( # type: ignore
name="app-start-stop-sync",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING, GObject.TYPE_BOOLEAN],
)
def app_start_stop_sync(self, tab_uuid: str, start: bool) -> None:
if self._block_gui:
return
self.gui._notebook.start_stop_tab_sync(tab_uuid=tab_uuid, start=start)
@GObject.Signal( # type: ignore
name="gui-show-main-window", flags=GObject.SignalFlags.RUN_LAST, return_type=GObject.TYPE_NONE
)
def gui_show_main_window(self) -> None:
self.gui.window.present()
@GObject.Signal( # type: ignore
name="gui-show-tab",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING],
)
def gui_show_tab(self, tab_uuid: str) -> None:
if self._block_gui:
return
self.gui.window.present()
self.gui._notebook.show_tab(tab_uuid=tab_uuid)
@GObject.Signal( # type: ignore
name="gui-show-info-textview",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING, GObject.TYPE_PYOBJECT],
)
def gui_show_info_text_view(self, tab_uuid: str, info_to_show: Dict[str, str]) -> None:
self.gui._notebook.show_info_tab_textview(tab_uuid=tab_uuid, info=info_to_show)
@GObject.Signal( # type: ignore
name="appindicator-add-paired-folder",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_PYOBJECT, GObject.TYPE_STRING],
)
def appindicator_add_paired_folder(self, paired_folder: PairedFolder, uuid_: str) -> None:
self.appindicator.add_new_paired_folder(paired_folder=paired_folder, uuid_=uuid_)
@GObject.Signal( # type: ignore
name="appindicator-delete-paired-folder",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING],
)
def appindicator_delete_paired_folder(self, tab_uuid: str) -> None:
self.appindicator.delete_paired_folder(tab_uuid=tab_uuid)
@GObject.Signal( # type: ignore
name="appindicator-update-alias-or-create-item",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING, GObject.TYPE_PYOBJECT],
)
def appindicator_update_alias_or_create_item(self, tab_uuid: str, paired_folder: PairedFolder) -> None:
self.appindicator.update_alias_or_create_item(tab_uuid=tab_uuid, paired_folder=paired_folder)
@GObject.Signal( # type: ignore
name="appindicator-update-item-sync",
flags=GObject.SignalFlags.RUN_LAST,
return_type=GObject.TYPE_NONE,
arg_types=[GObject.TYPE_STRING],
)
def appindicator_update_item_sync(self, tab_uuid: str) -> None:
self.appindicator.update_item_based_on_sync(tab_uuid=tab_uuid)
class GUI:
"""
Main graphical interface class
"""
class Tab:
"""
Class representing every tab of the user interface
"""
def __init__(
self,
parent: GUI.Notebook,
builder: Gtk.Builder,
uuid_paired_folder: Optional[str],
include_close_button: bool = True,
) -> None:
self._notebook: GUI.Notebook = parent
self._builder: Gtk.Builder = builder
self._uuid_paired_folder: Optional[str] = uuid_paired_folder
self.container: Gtk.Box = cast(Gtk.Box, self._builder.get_object(name="containerSingleTab"))
self.title_container: Gtk.Box = cast(Gtk.Box, self._builder.get_object(name="containerTitleSingleTab"))
self.label_tab: Gtk.Label = cast(Gtk.Label, self._builder.get_object(name="labelSingleTab"))
self.button_start_stop_sync: Gtk.Button = cast(
Gtk.Button, self._builder.get_object(name="buttonControlSync")
)
self.button_save_config: Gtk.Button = cast(Gtk.Button, self._builder.get_object(name="buttonSaveConfig"))
self.button_delete_config: Gtk.Button = cast(
Gtk.Button, self._builder.get_object(name="buttonDeleteConfig")
)
# TextView
self.buffer_text_view: Gtk.TextBuffer = cast(
Gtk.TextView, self._builder.get_object(name="textView")
).get_buffer()
self.tags_buffer: Dict[str, Gtk.TextTag] = {}
# Status Bar
self.status_bar: Gtk.Statusbar = cast(Gtk.Statusbar, self._builder.get_object(name="statusBar"))
# Observer
self.folder_observer: Optional[FolderObserver] = None
self.configure_font_and_tags()
self.configure_buffer()
self.setup_tab(include_close_button=include_close_button)
@property
def paired_folder(self) -> PairedFolder:
uuid_: str = cast(str, self._uuid_paired_folder)
return self._notebook._gui._application.paired_folders_app[uuid_]
def setup_tab(self, include_close_button: bool) -> None:
self.button_start_stop_sync.connect("clicked", lambda gtk_button: self.start_stop_sync())
self.button_save_config.connect("clicked", lambda gtk_button: self.save_config())
self.button_save_config.set_tooltip_markup(markup="Save current configuration to configuration file")
self.button_save_config.set_has_tooltip(has_tooltip=False)
self.button_delete_config.connect("clicked", lambda gtk_button: self.delete_config())
self.button_delete_config.set_tooltip_markup(markup="Delete current configuration from configuration file")
self.button_delete_config.set_has_tooltip(has_tooltip=True)
new_alias: str = (
f"NewPairedFolder{len(self._notebook.tab_list)+1}"
if self._uuid_paired_folder is None
else self.paired_folder.alias
)
self.label_tab.set_markup(str=new_alias)
if self._uuid_paired_folder is None:
self._uuid_paired_folder = self._notebook._gui._application.emit("app-add-paired-folder", new_alias) # type: ignore
button_close_tab: Gtk.Button = cast(Gtk.Button, self._builder.get_object(name="buttonCloseSingleTab"))
button_close_tab.set_has_tooltip(has_tooltip=True)
button_close_tab.set_tooltip_markup(markup="Close this tab")
signal_close_tab: int = button_close_tab.connect(
"clicked", lambda gtk_button: self._notebook.delete_tab(tab=self)
)
if not include_close_button:
button_close_tab.set_image(image=Gtk.Image.new())
button_close_tab.disconnect(signal_close_tab)
button_close_tab.connect(
"clicked", lambda gtk_button: self._notebook.notebook.set_current_page(page_num=0)
)
label_source_folder: Gtk.Label = cast(Gtk.Label, self._builder.get_object(name="labelSourceFolder"))
label_source_folder.connect(
"activate-link", lambda gtk_label, uri: Application.open_file_manager(path=self.paired_folder.source)
)
label_target_folder: Gtk.Label = cast(Gtk.Label, self._builder.get_object(name="labelTargetFolder"))
label_target_folder.connect(
"activate-link", lambda gtk_label, uri: Application.open_file_manager(path=self.paired_folder.target)
)
button_select_source_folder: Gtk.Button = cast(
Gtk.Button, self._builder.get_object(name="buttonOpenDialogSelectSourceFolder")
)
button_select_source_folder.set_has_tooltip(has_tooltip=True)
button_select_source_folder.set_tooltip_markup(markup="Select source folder")
button_select_source_folder.connect(
"clicked",
lambda gtk_button: self.open_file_chooser_dialog(
path=self.paired_folder.source,
label=label_source_folder,
opposite_label=label_target_folder,
property_to_update="_source",
),
)
button_select_target_folder: Gtk.Button = cast(
Gtk.Button, self._builder.get_object(name="buttonOpenDialogSelectTargetFolder")
)
button_select_target_folder.set_has_tooltip(has_tooltip=True)
button_select_target_folder.set_tooltip_markup(markup="Select target folder")
button_select_target_folder.connect(
"clicked",
lambda gtk_button: self.open_file_chooser_dialog(
path=self.paired_folder.target,
label=label_target_folder,
opposite_label=label_source_folder,
property_to_update="_target",
),
)
checkbutton_include_hidden_files: Gtk.CheckButton = cast(
Gtk.CheckButton, self._builder.get_object(name="checkButtonIncludeHiddenFiles")
)
checkbutton_autostart_sync: Gtk.CheckButton = cast(
Gtk.CheckButton, self._builder.get_object(name="checkButtonAutostartSync")
)
markup: str = "Set the desired buffer size.\n"
markup += f"<b>Default value:</b> {default_buffer_size}\n"
markup += f"<b>Min value:</b> {min_buffer_size}\n"
markup += f"<b>Max value:</b> {max_buffer_size}"
entry_history_size: Gtk.Entry = cast(Gtk.Entry, self._builder.get_object(name="entryHistorySize"))
entry_history_size.set_has_tooltip(has_tooltip=True)
entry_history_size.set_tooltip_markup(markup=markup)
entry_history_size.connect(
"icon-press",
lambda gtk_entry, gtk_entry_icon_position, gdk_event: entry_history_size.set_text(
text=str(default_buffer_size)
),
)
# Status bar default text
self.status_bar.push(context_id=1, text="Synchronization inactive")
# This will set the configuration read from the config file
if self.paired_folder._is_config_saved:
self.show_text_textview(mode="read-config")
path_name: str = f"{self.paired_folder.source.name if len(self.paired_folder.source.name) else str(self.paired_folder.source)}"
label_source_folder.set_markup(str=f'<a href="file://{str(self.paired_folder.source)}">{path_name}</a>')
path_name = f"{self.paired_folder.target.name if len(self.paired_folder.target.name) else str(self.paired_folder.target)}"
label_target_folder.set_markup(str=f'<a href="file://{str(self.paired_folder.target)}">{path_name}</a>')
checkbutton_include_hidden_files.set_active(is_active=self.paired_folder.include_hidden_files)
checkbutton_autostart_sync.set_active(is_active=self.paired_folder.autostart_sync)
entry_history_size.set_text(text=str(self.paired_folder.buffer_size))
self.check_status_path()
self.button_delete_config.set_visible(visible=True)
if self.paired_folder.autostart_sync:
self.start_stop_sync(start=True, startup=True)
def cb_options(property_to_update: str, value: Union[int, bool]) -> None:
"""
Callback for the checkbuttons and the entry
"""
self._notebook._gui._application.emit(
"app-update-paired-folder", self._uuid_paired_folder, property_to_update, value
)
def cb_entry_history_size_focus_out() -> bool:
"""
Callback of history size entry when it loses focus
"""
history_size = entry_history_size.get_text()
if not len(history_size) or (
int(history_size) > max_buffer_size or int(history_size) < min_buffer_size
):
entry_history_size.set_text(text=str(default_buffer_size))
if int(history_size) != self.paired_folder.buffer_size:
cb_options(property_to_update="buffer_size", value=int(entry_history_size.get_text()))
return False
checkbutton_include_hidden_files.connect(
"toggled",
lambda gtk_toggle_button: cb_options(
property_to_update="include_hidden_files", value=checkbutton_include_hidden_files.get_active()
),
)
checkbutton_autostart_sync.connect(
"toggled",
lambda gtk_toggle_button: cb_options(
property_to_update="autostart_sync", value=checkbutton_autostart_sync.get_active()
),
)
entry_history_size.connect(
"focus-out-event", lambda gtk_entry, gdk_event: cb_entry_history_size_focus_out()
)
def configure_font_and_tags(self) -> None:
monospaced_font: str = "Monospace"
font_size: int = 11
try:
settings: Optional[Gio.SettingsSchema] = Gio.SettingsSchemaSource.get_default().lookup(
schema_id="org.gnome.desktop.interface", recursive=True
)
if settings is not None:
interface_settings: Gio.Settings = Gio.Settings.new(schema_id="org.gnome.desktop.interface")
current_font: str = interface_settings.get_string(key="font-name")
if len(current_font):
font_size = int(current_font.split(sep=" ")[-1])
if font_size < 11:
font_size = 12
monospaced_font = interface_settings.get_string(key="monospace-font-name")
except:
pass
# Custom monospaced font with env var MONOSPACED_FONT
custom_monospaced_font_name: Optional[str] = os.environ.get("MONOSPACED_FONT")
if custom_monospaced_font_name is not None:
pango_context: Pango.Context = self._notebook._gui.window.get_pango_context()
for family in pango_context.list_families():
family = cast(Pango.FontFamily, family)
if (
custom_monospaced_font_name == family.get_name()
or family.get_name() in custom_monospaced_font_name
):
monospaced_font = family.get_name()
break
# Tags
tag_normal: Gtk.TextTag = self.buffer_text_view.create_tag(
tag_name="normal", **{"weight": Pango.Weight.NORMAL, "size-points": float(font_size)}
)
tag_title: Gtk.TextTag = self.buffer_text_view.create_tag(
tag_name="title", **{"weight": Pango.Weight.BOLD, "size-points": 15.0}
)
tag_bold: Gtk.TextTag = self.buffer_text_view.create_tag(tag_name="bold", **{"weight": Pango.Weight.BOLD})
tag_monospaced: Gtk.TextTag = self.buffer_text_view.create_tag(
tag_name="monospaced", **{"font": monospaced_font, "size-points": 12.5}
)
tag_monospaced_bold: Gtk.TextTag = self.buffer_text_view.create_tag(
tag_name="monospaced_bold",
**{"font": monospaced_font, "weight": Pango.Weight.BOLD, "size-points": 12.5},
)
tag_centered: Gtk.TextTag = self.buffer_text_view.create_tag(
tag_name="centered", **{"justification": Gtk.Justification.CENTER}
)
self.tags_buffer.update(
{
"normal": tag_normal,
"title": tag_title,
"bold": tag_bold,
"monospaced": tag_monospaced,
"monospaced_bold": tag_monospaced_bold,
"centered": tag_centered,
}
)
def configure_buffer(self) -> None:
@no_type_check
def delete_lines_textview() -> None:
lines_to_delete: int = self.buffer_text_view.get_line_count() - self.paired_folder.buffer_size
start: Gtk.TextIter = self.buffer_text_view.get_start_iter()
end: Gtk.TextIter = self.buffer_text_view.get_iter_at_line(line_number=lines_to_delete)
self.buffer_text_view.handler_block(signal_id_textview_changed)
self.buffer_text_view.delete(start=start, end=end)
self.buffer_text_view.handler_unblock(signal_id_textview_changed)
def cb_textview_changed() -> None:
if self.buffer_text_view.get_line_count() > self.paired_folder.buffer_size:
delete_lines_textview()
signal_id_textview_changed = self.buffer_text_view.connect_after(
"changed", lambda gtk_text_buffer: GLib.idle_add(cb_textview_changed)
)
def open_file_chooser_dialog(
self, path: Path, label: Gtk.Label, opposite_label: Gtk.Label, property_to_update: str
) -> None:
"""
Open a file chooser dialog to choose source/target folder.
:param Path path: Current path of file chooser
:param Gtk.Label label: Label to update when source/target is chosen
:param Gtk.Label opposite_label: Opposite label to update when source/target is chosen
:param str property_to_update: Property to update when source/target is chosen
"""
title_: str = f"{global_title} - Select {property_to_update[1:]} folder"
dialog = self._notebook._gui._application.create_file_chooser_dialog(
parent=self._notebook._gui.window, title=title_, path=path
)
self._notebook._gui._application._block_gui = True
response: int = dialog.run()
file_: Gio.File = dialog.get_file() # Folder chosen by the dialog
dialog.destroy()
self._notebook._gui._application._block_gui = False
if not response == Gtk.ResponseType.OK:
return
opposite_property: str = "_target" if property_to_update == "_source" else "_source"
new_path: Path = Path(file_.get_path())
label.set_markup(
str=f'<a href="file://{str(new_path)}">{new_path.name if len(new_path.name) else str(new_path)}</a>'
)
def show_error(text: str) -> None:
"""
Show a Gtk.MessageDialog displaying the error message
"""
dialog: Gtk.MessageDialog = self._notebook._gui._application.create_dialog(
parent=self._notebook._gui.window,
message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.OK,
text="Invalid path",
text2=text,
)
self._notebook._gui._application._block_gui = True
dialog.run()
old_path: Optional[Path] = cast(Optional[Path], getattr(self.paired_folder, property_to_update))
old_markup: str = (
f'<a href="file://{str(old_path)}">{old_path.name if len(old_path.name) else str(old_path)}</a>'
if old_path is not None
else "(None)"
)
label.set_markup(str=old_markup)
dialog.destroy()
self._notebook._gui._application._block_gui = False
def check_permissions() -> None:
"""
Check if the new path has the appropriate read/write permissions
"""
permission_to_check: int = os.R_OK if property_to_update == "_source" else os.W_OK
verb_to_show: str = "readable" if property_to_update == "_source" else "writable"
if not os.access(path=new_path, mode=permission_to_check):
show_error(text=f"The chosen path is not {verb_to_show}, please choose another one.")
raise
def check_path_validity_against_tabs() -> None:
"""
Check if new path is in use by another tab
"""
for tab in self._notebook.tab_list:
if self._notebook.notebook.get_current_page() == self._notebook.notebook.page_num(
child=tab.container
):
continue
if tab.paired_folder._target is not None and (
new_path.resolve() == tab.paired_folder.target.resolve()
):
show_error(
text=f'The chosen path is already in use by the configuration "<b>{tab.paired_folder.alias}</b>" on tab number {self._notebook.notebook.page_num(child=tab.container) + 1}.'
)
raise
try:
check_permissions()
if property_to_update == "_target": # Target folders have to be unique
check_path_validity_against_tabs()
self._notebook._gui._application.emit(
"app-update-paired-folder", self._uuid_paired_folder, property_to_update, new_path
)
if new_path.resolve() == cast(Path, getattr(self.paired_folder, opposite_property)).resolve():
opposite_label.set_markup(str="(None)")
self._notebook._gui._application.emit(
"app-update-paired-folder", self._uuid_paired_folder, opposite_property, None
)
self.check_status_path()
except:
pass
def check_status_path(self) -> None:
"""
Checks if source and target paths are not `None` and activates the buttons to start/stop sync and to save config, also, changes the alias when both source and target are valid
"""
self.button_start_stop_sync.set_sensitive(sensitive=self.paired_folder.is_valid)
self.button_save_config.set_has_tooltip(has_tooltip=self.paired_folder.is_valid)
self.button_save_config.set_sensitive(sensitive=self.paired_folder.is_valid)
self._notebook.option_save_current_tab.set_has_tooltip(has_tooltip=self.paired_folder.is_valid)
self._notebook.option_save_current_tab.set_sensitive(sensitive=self.paired_folder.is_valid)
if self.paired_folder.is_valid:
source_name: str = (
self.paired_folder.source.name
if len(self.paired_folder.source.name)
else str(self.paired_folder.source)
)
target_name: str = (
self.paired_folder.target.name
if len(self.paired_folder.target.name)
else str(self.paired_folder.target)
)
new_alias: str = f"{source_name} --> {target_name}"
self._notebook._gui._application.emit(
"app-update-paired-folder", self._uuid_paired_folder, "alias", new_alias
)
self.label_tab.set_markup(str=new_alias)
self._notebook._gui._application.emit(
"appindicator-update-alias-or-create-item", self._uuid_paired_folder, self.paired_folder
)
def show_text_textview(self, mode: str) -> None:
"""
Show text in textview, depending on `mode`, which can be:
"read-config" to show text related with read from config file
"save-config" to show text related with save config to config file
"delete-config" to show text related with delete config from config file
"start-stop-sync" to show text related with starting/stopping synchronization
"start-sync-error" to show text related with errors when starting sync
"""
def main() -> None:
def write_common_info(title: str) -> None:
self.insert_text_with_tags(
text=f"{title}\n\n", tags=[self.tags_buffer["title"], self.tags_buffer["centered"]]
)
self.insert_text_with_tags(text="SOURCE: ", tags=[self.tags_buffer["monospaced_bold"]])
self.insert_text_with_tags(
text=f"{str(self.paired_folder.source)}\n", tags=[self.tags_buffer["monospaced"]]
)
self.insert_text_with_tags(text="TARGET: ", tags=[self.tags_buffer["monospaced_bold"]])
self.insert_text_with_tags(
text=f"{str(self.paired_folder.target)}\n", tags=[self.tags_buffer["monospaced"]]
)
def get_current_time_format() -> str:
return f'[{datetime.datetime.now().strftime("%H:%M:%S")}]'
if mode == "read-config":
write_common_info(title="CONFIGURATION READ")
self.insert_text_with_tags(text=f"{get_current_time_format()} The configuration section ")
self.insert_text_with_tags(
text=f'"{self.paired_folder._original_state["alias"]}"', tags=[self.tags_buffer["bold"]]
)
self.insert_text_with_tags(text=" has been read from the configuration file.\n\n")
elif mode == "save-config":
write_common_info(title="CONFIGURATION SAVED")
self.insert_text_with_tags(
text=f"{get_current_time_format()} The configuration has been saved in the section "
)
self.insert_text_with_tags(
text=f'"{self.paired_folder._original_state["alias"]}"', tags=[self.tags_buffer["bold"]]
)
self.insert_text_with_tags(text=" in the configuration file.\n\n")
elif mode == "delete-config":
self.insert_text_with_tags(
text="CONFIGURATION DELETED\n\n", tags=[self.tags_buffer["title"], self.tags_buffer["centered"]]
)
self.insert_text_with_tags(text=f"{get_current_time_format()} The configuration section ")
self.insert_text_with_tags(
text=f'"{self.paired_folder._original_state["alias"]}"', tags=[self.tags_buffer["bold"]]
)
self.insert_text_with_tags(text=" has been deleted from the configuration file.\n\n")
elif mode == "start-stop-sync":
if self.paired_folder._synchronization_status:
write_common_info(title="SYNCHRONIZATION STARTED")
self.insert_text_with_tags(
text=f"{get_current_time_format()} The synchronization has started, all the events reported on source are going to be replicated on target.\n\n"
)
else:
self.insert_text_with_tags(
text="SYNCHRONIZATION STOPPED\n\n",
tags=[self.tags_buffer["title"], self.tags_buffer["centered"]],
)
self.insert_text_with_tags(
text=f"{get_current_time_format()} The synchronization has been stopped.\n\n"
)
elif mode == "start-sync-error":
self.insert_text_with_tags(
text="SYNCHRONIZATION COULD NOT BE STARTED\n\n",
tags=[self.tags_buffer["title"], self.tags_buffer["centered"]],
)
self.insert_text_with_tags(
text=f"{get_current_time_format()} The synchronization could not be started, the source location is not valid.\n\n"
)
GLib.idle_add(main)
@no_type_check
def insert_text_with_tags(self, text: str, tags: Optional[List[Gtk.TextTag]] = None) -> None:
"""
Insert text in textview
"""
if tags is None:
tags = [self.tags_buffer["normal"]]
self.buffer_text_view.insert_with_tags(self.buffer_text_view.get_end_iter(), text, *tags)
def save_config(self) -> None:
"""
Save configuration of current tab in config file
"""
dialog: Gtk.MessageDialog = self._notebook._gui._application.create_dialog(
parent=self._notebook._gui.window,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text="Save configuration",
text2="Do you want to save the current configuration?",
)
if self.paired_folder._is_config_saved:
if self.paired_folder.has_changed():
dialog.format_secondary_markup(
message_format=f'Do you want to save the current configuration? This will update the section <b>"{self.paired_folder._original_state["alias"]}</b>" in the configuration file.'
)
else:
dialog = self._notebook._gui._application.create_dialog(
parent=self._notebook._gui.window,
message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.OK,
text="Save configuration",
text2=f'The configuration is already saved in the section <b>"{self.paired_folder.alias}"</b> in the configuration file.',
)
self._notebook._gui._application._block_gui = True
response_id: int = dialog.run()
dialog.destroy()
if response_id == Gtk.ResponseType.YES:
result: bool = self._notebook._gui._application.app_save_config(uuid=self._uuid_paired_folder)
text: str = (
f'The configuration has been saved in the section <b>"{self.paired_folder.alias}"</b> in the configuration file.'
if result
else "An error occurred saving the configuration to file."
)
dialog = self._notebook._gui._application.create_dialog(
parent=self._notebook._gui.window,
message_type=Gtk.MessageType.INFO if result else Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text="Save configuration",
text2=text,
)
if result:
self.paired_folder.update_config_after_save()
self.button_delete_config.set_visible(visible=True)
self.show_text_textview(mode="save-config")
self._notebook._gui.show_link_open_config_file()
dialog.run()
dialog.destroy()
self._notebook._gui._application._block_gui = False
def delete_config(self) -> None:
"""
Delete tab's associated section from config file
"""
dialog: Gtk.MessageDialog = self._notebook._gui._application.create_dialog(
parent=self._notebook._gui.window,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text="Delete configuration",
text2=f'Do you want to delete the configuration section <b>"{self.paired_folder._original_state["alias"]}"</b> from the configuration file?',
)
self._notebook._gui._application._block_gui = True
response_id: int = dialog.run()
dialog.destroy()
if response_id == Gtk.ResponseType.YES:
result: bool = self._notebook._gui._application.app_save_config(
uuid=self._uuid_paired_folder, exclude=True
)
text: str = (
f'The configuration section <b>"{self.paired_folder._original_state["alias"]}"</b> has been deleted from the configuration file.'
if result
else f'An error occurred deleting the section <b>"{self.paired_folder._original_state["alias"]}"</b> from the configuration to file.'
)
dialog = self._notebook._gui._application.create_dialog(
parent=self._notebook._gui.window,
message_type=Gtk.MessageType.INFO if result else Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text="Delete configuration",
text2=text,
)
if result:
self.paired_folder.update_config_after_save(config_saved=False)
self.show_text_textview(mode="delete-config")
def cb_dialog() -> None:
if result: