-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobocopygui.py
More file actions
executable file
·665 lines (615 loc) · 25.8 KB
/
robocopygui.py
File metadata and controls
executable file
·665 lines (615 loc) · 25.8 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__application__ = 'RoboCopyGui'
__author__ = 'Markus Thilo'
__version__ = '0.4.0_2026-01-09'
__license__ = 'GPL-3'
__email__ = 'markus.thilomarkus@gmail.com'
__status__ = 'Testing'
__description__ = 'Graphical user interface for RoboCopy with hash and verify options'
from sys import executable as __executable__
from pathlib import Path
from threading import Thread, Event
from ctypes import windll
from subprocess import run
from tkinter import Tk, PhotoImage, StringVar, BooleanVar, Checkbutton, Toplevel, Radiobutton
from tkinter.font import nametofont
from tkinter.ttk import Frame, Label, Entry, Button, Combobox, LabelFrame, Progressbar
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import askopenfilenames, askdirectory
from tkinter.messagebox import showerror, askokcancel, askyesno, showwarning
from idlelib.tooltip import Hovertip
from worker import Copy
from rc_classes import Config, Settings, Labels, GuiDefs, FileHash, RoboCopy
from tk_pathdialog import askpaths
__parent_path__ = Path(__file__).parent if Path(__executable__).stem.startswith('python') else Path(__executable__).parent
class WorkThread(Thread):
'''The worker has tu run as thread not to freeze GUI/Tk'''
def __init__(self, src_paths, dst_path, simulate, gui):
'''Pass arguments to worker'''
super().__init__()
self._finish = gui.finished
self._kill_event = Event()
self._worker = Copy(src_paths, dst_path, gui.settings, gui.config, gui.labels,
simulate = simulate,
echo = gui.echo,
kill = self._kill_event
)
def kill(self):
'''Kill thread'''
self._kill_event.set()
def kill_is_set(self):
'''Return True if kill event is set'''
return self._kill_event.is_set()
def run(self):
'''Run worker thread'''
self._finish(self._worker.run())
class Gui(Tk):
'''GUI look and feel'''
def __init__(self):
'''Open application window'''
self.config = Config()
self.settings = Settings(self.config)
self.labels = Labels(self.settings.lang)
self._defs = GuiDefs()
self._admin_rights = windll.shell32.IsUserAnAdmin() != 0
self._work_thread = None
super().__init__() ### use tk, define the gui ###
self.title(f'{__application__} v{__version__}')
for row, weight in enumerate(self._defs.row_weights):
self.rowconfigure(row, weight=weight)
for column, weight in enumerate(self._defs.column_weights):
self.columnconfigure(column, weight=weight)
self.iconphoto(True, PhotoImage(file=Path(__file__).parent/self._defs.icon_name))
self.protocol('WM_DELETE_WINDOW', self._quit_app)
self._font = nametofont('TkTextFont').actual()
min_size_x = self._font['size'] * self._defs.x_factor
min_size_y = self._font['size'] * self._defs.y_factor
self.minsize(min_size_x , min_size_y)
self.geometry(f'{min_size_x}x{min_size_y}')
self.resizable(True, True)
self._pad = int(self._font['size'] * self._defs.pad_factor)
frame = Frame(self) ### source selector
frame.grid(row=0, column=0, sticky='nswe')
self._source_dir_button = Button(frame, text=self.labels.directory, command=self._select_source_dir) # source dir button #
self._source_dir_button.pack(anchor='nw', padx=self._pad, pady=self._pad, expand=True)
Hovertip(self._source_dir_button, self.labels.source_dir_tip)
self._source_files_button = Button(frame, text=self.labels.files, command=self._select_source_files) # souce file button
self._source_files_button.pack(anchor='nw', padx=self._pad, pady=self._pad, expand=True)
Hovertip(self._source_files_button, self.labels.source_files_tip)
self._source_multiple_button = Button(frame, text=self.labels.multiple, command=self._select_multiple) # multiple button #
self._source_multiple_button.pack(anchor='nw', padx=self._pad, pady=self._pad, expand=True)
Hovertip(self._source_multiple_button, self.labels.source_multiple_tip)
self._clear_source_button = Button(frame, text=self.labels.clear, command=self._clear_source) # clear source button
self._clear_source_button.pack(side='bottom', anchor='sw', padx=self._pad, pady=self._pad, expand=True)
Hovertip(self._clear_source_button, self.labels.clear_source_tip)
self._source_text = ScrolledText(self, # source field
font = (self._font['family'], self._font['size']),
wrap = "none",
padx = self._pad,
pady = self._pad
)
self._source_text.grid(row=0, column=1, columnspan=3, sticky='nswe', ipadx=self._pad, ipady=self._pad, padx=self._pad, pady=self._pad)
Hovertip(self._source_text, self.labels.source_text_tip)
self._destination_button = Button(self, text=self.labels.destination, command=self._select_destination) ### destination selector
self._destination_button.grid(row=1, column=0, sticky='nswe', padx=self._pad, pady=(0, self._pad))
self._destination = StringVar()
self._destination_entry = Entry(self, textvariable=self._destination)
self._destination_entry.grid(row=1, column=1, columnspan=3, sticky='nsew', padx=self._pad, pady=(0, self._pad))
Hovertip(self._destination_button, self.labels.destination_tip)
self._options_var = StringVar(value=self._gen_options_label()) ### options ###
frame = LabelFrame(self, text=self.labels.options)
frame.grid(row=2, column=1, sticky='nswe', padx=self._pad)
self._options_selector = Combobox(frame, values=self._gen_options_list(), state='readonly', textvariable=self._options_var)
self._options_selector.pack(fill='both', expand=True, padx=self._pad, pady=(0, self._pad))
self._options_selector.bind('<<ComboboxSelected>>', self._options_event)
Hovertip(self._options_selector, self.labels.options_tip)
self.possible_hashes = FileHash.get_algorithms() ### hash ###
self._hash_var = StringVar(value=self._gen_hash_label())
frame = LabelFrame(self, text=self.labels.hash)
frame.grid(row=2, column=2, sticky='nswe', padx=self._pad)
self._hash_selector = Combobox(frame, values=self._gen_hash_list(), state='readonly', textvariable=self._hash_var)
self._hash_selector.pack(fill='both', expand=True, padx=self._pad, pady=(0, self._pad))
self._hash_selector.bind('<<ComboboxSelected>>', self._hash_event)
Hovertip(self._hash_selector, self.labels.hash_tip)
self._verify_var = StringVar(value=self._gen_verify_label()) ### verify ###
frame = LabelFrame(self, text=self.labels.verify)
frame.grid(row=2, column=3, sticky='nswe', padx=self._pad)
self._verify_selector = Combobox(frame, values=self._gen_verify_list(), state='readonly', textvariable=self._verify_var)
self._verify_selector.pack(fill='both', expand=True, padx=self._pad, pady=(0, self._pad))
self._verify_selector.bind('<<ComboboxSelected>>', self._verify_event)
Hovertip(self._verify_selector, self.labels.verify_tip)
self._log_button = Button(self, text=self.labels.log, command=self._select_log) ### log ###
self._log_button.grid(row=3, column=0, sticky='nswe', padx=self._pad, pady=self._pad)
self._log = StringVar(value=self.settings.log_dir_path)
self._log_entry = Entry(self, textvariable=self._log)
self._log_entry.grid(row=3, column=1, columnspan=3, sticky='nswe', padx=self._pad, pady=self._pad)
Hovertip(self._log_button, self.labels.log_tip)
if self._admin_rights: ### admin label ###
text = self.labels.admin
tip = self.labels.admin_tip
else:
text = self.labels.no_admin
tip = self.labels.no_admin_tip
self._admin_label = Label(self, text=text)
self._admin_label.grid(row=4, column=1, sticky='nswe', padx=self._pad, pady=(0, self._pad))
Hovertip(self._admin_label, tip)
self._simulate_button_text = StringVar(value=self.labels.simulate) ### simulate ###
self._simulate_button = Button(self, textvariable=self._simulate_button_text, command=self._simulate)
self._simulate_button.grid(row=4, column=2, sticky='nswe', padx=self._pad, pady=(0, self._pad))
Hovertip(self._simulate_button, self.labels.simulate_tip)
self._exec_button = Button(self, text=self.labels.exec_button, command=self._execute) ### execute ###
self._exec_button.grid(row=4, column=3, sticky='nswe', padx=self._pad, pady=(0, self._pad))
Hovertip(self._exec_button, self.labels.exec_tip)
self._help_button = Button(self, text=self.labels.help, command=self._echo_help) ### help ###
self._help_button.grid(row=5, column=0, sticky='nwe', padx=self._pad, pady=(0, self._pad))
Hovertip(self._help_button, self.labels.help_tip)
self._info_text = ScrolledText(self, font=(self._font['family'], self._font['size']), padx=self._pad, pady=self._pad) ### info ###
self._info_text.grid(row=5, column=1, columnspan=3, sticky='nswe',
ipadx=self._pad, ipady=self._pad, padx=self._pad, pady=(0, self._pad))
self._info_text.bind('<Key>', lambda dummy: 'break')
self._info_text.configure(state='disabled')
self._info_fg = self._info_text.cget('foreground')
self._info_bg = self._info_text.cget('background')
self._info_newline = True
self._info_label = Label(self)
self._info_label.grid(row=6, column=1, sticky='nsw', padx=self._pad, pady=(0, self._pad))
self._label_fg = self._info_label.cget('foreground')
self._label_bg = self._info_label.cget('background')
self._lang_button = Button(self, text=self.labels.language, command=self._change_lang) ### language ###
self._lang_button.grid(row=6, column=0, sticky='nwe', padx=self._pad, pady=(0, self._pad))
Hovertip(self._lang_button, self.labels.language_tip)
if self._admin_rights: ### shutdown after finish
self._shutdown = BooleanVar(value=False)
self._shutdown_button = Checkbutton(self,
text = self.labels.shutdown,
variable = self._shutdown,
command = self._toggle_shutdown
)
self._shutdown_button.grid(row=6, column=2, sticky='nswe', padx=self._pad, pady=(0, self._pad))
Hovertip(self._shutdown_button, self.labels.shutdown_tip)
self._quit_button_text = StringVar(value=self.labels.quit) ### quit/abort ###
self._quit_button = Button(self, textvariable=self._quit_button_text, command=self._quit_app)
self._quit_button.grid(row=6, column=3, sticky='nse', padx=self._pad, pady=(0, self._pad))
Hovertip(self._quit_button, self.labels.quit_tip)
self._init_warning()
def _set_lang(self, code):
'''Set albel language'''
self.settings.lang = code
self._lang_window.destroy()
def _change_lang(self):
'''Change language'''
self._lang_window = Toplevel(self)
self._lang_window.title(self.labels.language)
old_lang = StringVar(value=self.settings.lang)
for lang, code in self.config.languages.items():
Radiobutton(self._lang_window,
text = lang,
command = lambda: self._set_lang(code),
variable = old_lang,
value = code).pack(padx=self._pad, pady=self._pad)
Button(self._lang_window,
text = self.labels.cancel,
command = self._lang_window.destroy
).pack(padx=self._pad, pady=self._pad)
pos_x = self.winfo_x() + (2*self._pad)
pos_y = self.winfo_y() + self.winfo_height() - self._lang_window.winfo_reqheight() - (2*self._pad)
self._lang_window.geometry(f'+{pos_x}+{pos_y}')
Hovertip(self._lang_window, self.labels.language_tip)
self._lang_window.wait_window()
def _read_source_paths(self):
'''Read paths from text field'''
if text := self._source_text.get('1.0', 'end').strip():
return [Path(line.strip()).absolute() for line in text.split('\n')]
return ()
def _chck_source_path(self, source):
'''Check if source path is valid'''
if not source:
return
path = Path(source)
if path.exists():
return path
showerror(title=self.labels.error, message=self.labels.src_path_not_found.replace('#', f'{path}'))
def _select_source_dir(self):
'''Select directory to add into field'''
if directory := askdirectory(title=self.labels.select_dir, mustexist=True, initialdir=self.settings.src_dir_path):
path = Path(directory).absolute()
if path in self._read_source_paths():
showerror(title=self.labels.error, message=self.labels.already_added.replace('#', f'{path}'))
return
self._source_text.insert('end', f'{path}\n')
self.settings.src_dir_path = f'{path}'
def _select_source_files(self):
'''Select file(s) to add into field'''
if filenames := askopenfilenames(title=self.labels.select_files, initialdir=self.settings.src_dir_path):
if len(filenames) == 1:
path = Path(filenames[0]).absolute()
if path in self._read_source_paths():
showerror(title=self.labels.error, message=self.labels.already_added.replace('#', f'{path}'))
return
for filename in filenames:
path = Path(filename).absolute()
if not path in self._read_source_paths():
self._source_text.insert('end', f'{path}\n')
self.settings.src_dir_path = path.parent
def _select_multiple(self):
'''Select multiple files and directories to add into field'''
if paths := askpaths(
title = self.labels.select_multiple,
confirm = self.labels.confirm,
cancel = self.labels.cancel,
initialdir = self.settings.src_dir_path
):
for path in paths:
if not path in self._read_source_paths():
self._source_text.insert('end', f'{path}\n')
self.settings.src_dir_path = path.parent
def _get_source_paths(self):
'''Get source paths from text field'''
unverified_paths = self._read_source_paths()
if not unverified_paths:
showerror(title=self.labels.error, message=self.labels.no_source)
return
src_paths = list()
for path in unverified_paths:
src_path = self._chck_source_path(path)
if not src_path:
return
src_paths.append(src_path)
return src_paths
def _select_destination(self):
'''Select destination directory'''
if directory := askdirectory(
title = self.labels.select_destination,
mustexist = False,
initialdir = self.settings.dst_dir_path
):
path = Path(directory).absolute()
self._destination.set(path)
self.settings.dst_dir_path = path
def _get_destination_path(self, src_paths):
'''Get destination directory'''
dst_dir = self._destination.get()
if not dst_dir:
self._select_destination()
dst_dir = self._destination.get()
if not dst_dir:
showerror(title=self.labels.error, message=self.labels.no_destination)
return
try:
dst_path = Path(dst_dir).absolute()
except:
showerror(title=self.labels.error, message=self.labels.invalid_destination.replace('#', f'{dst_dir}'))
return
for src_path in src_paths: # collisions with source paths?
is_dir = src_path.is_dir()
if (
( is_dir and src_path.parent in [dst_path] + list(dst_path.parents) ) or
( not is_dir and src_path.parent == dst_path )
):
showerror(title=self.labels.error, message=self.labels.source_collides_destination.replace('#', f'{src_path}').replace('&', f'{dst_path}'))
return
showerror(
title = self.labels.error,
message = self.labels.source_collides_destination.replace('#', f'{src_path}').replace('&', f'{dst_path}')
)
return
if dst_path.exists() and not dst_path.is_dir():
showerror(self.labels.error, self.labels.destination_no_directory.replace('#', f'{dst_path}'))
return
return dst_path
def _mk_destination_path(self, dst_path):
'''Make destination directory'''
if dst_path.exists():
top = dst_path.samefile(dst_path.parent)
for path in dst_path.iterdir():
if top and path.is_dir() and path.name.upper() in ('$RECYCLE.BIN', 'SYSTEM VOLUME INFORMATION'):
continue
if askyesno(self.labels.warning, self.labels.destination_not_empty.replace('#', f'{dst_path}')):
return
else:
return True
return
try:
dst_path.mkdir(parents=True)
except Exception as ex:
showerror(
title = self.labels.error,
message = f'{self.labels.invalid_dst_path.replace("#", dst_dir)}\n{type(ex): {ex}}'
)
return True
def _select_log(self):
'''Select directory '''
if directory := askdirectory(title=self.labels.select_log, mustexist=False, initialdir=self.settings.log_dir_path):
path = Path(directory).absolute()
self._log.set(path)
self.settings.log_dir_path = path
def _get_log_dir(self):
'''Get log directory'''
if log_dir := self._log.get():
try:
self.settings.log_dir_path = Path(log_dir).absolute()
except:
return
else:
self.settings.log_dir_path = None
def _mk_log_dir(self):
'''Create log directory if not exists'''
if log_dir := self._log_entry.get():
try:
self.settings.log_dir_path = Path(log_dir).absolute()
except Exception as ex:
showerror(
title = self.labels.error,
message = f'{self.labels.invalid_log_path.replace("#", f"{log_dir}")}\n{type(ex)}: {ex}'
)
self.settings.log_dir_path = None
else:
self.settings.log_dir_path = None
if not self.settings.log_dir_path and self.settings.hashes:
self._select_log()
if not self.settings.log_dir_path:
showerror(title=self.labels.error, message=self.labels.log_required)
return True
if self.settings.log_dir_path:
try:
self.settings.log_dir_path.mkdir(parents=True, exist_ok=True)
except Exception as ex:
showerror(
title = self.labels.error,
message = f'{self.labels.invalid_log_path.replace("#", f'{self.settings.log_dir_path}')}\n{type(ex)}: {ex}'
)
return True
def _gen_options_list(self):
'''Generate list of options'''
return [
f'\u2611 {option}' if option in self.settings.options else f'\u2610 {option}'
for option in self.config.robocopy_parameters
]
def _gen_hash_list(self):
'''Generate list of hashes to check'''
return [
f'\u2611 {hash}' if hash in self.settings.hashes else f'\u2610 {hash}'
for hash in self.possible_hashes
]
def _gen_verify_list(self):
'''Generate list of verification methodes'''
return [
f'\u2611 {self.labels.size}' if self.settings.verify == 'size' else f'\u2610 {self.labels.size}'
] + [
f'\u2611 {hash}' if self.settings.verify == hash else f'\u2610 {hash}'
for hash in self.settings.hashes
]
def _gen_options_label(self):
'''Generate label for options menu'''
return ' '.join(self.settings.options)
def _gen_hash_label(self):
'''Generate label for hash menu'''
return ', '.join(self.settings.hashes)
def _gen_verify_label(self):
'''Generate label for verification menu'''
return self.labels.size if self.settings.verify == 'size' else self.settings.verify
def _options_event(self, dummy_event):
'''Robocopy options selection'''
choosen = self._options_var.get()[2:]
if choosen in self.config.options:
self.config.options.remove(choosen)
else:
self.config.options.append(choosen)
self.config.options.sort()
for deselect in self.config.robocopy_parameters[choosen]:
try:
self.config.options.remove(deselect)
except ValueError:
pass
self._options_selector['values'] = self._gen_options_list()
self._options_var.set(self._gen_options_label())
def _hash_event(self, dummy_event):
'''Hash algorithm selection'''
choosen = self._hash_var.get()[2:]
if choosen in self.settings.hashes:
self.settings.hashes.remove(choosen)
if choosen == self.settings.verify:
self.settings.verify = 'size'
else:
self.settings.hashes.append(choosen)
self.settings.hashes.sort()
self._hash_selector['values'] = self._gen_hash_list()
self._verify_selector['values'] = self._gen_verify_list()
self._hash_var.set(self._gen_hash_label())
self._verify_var.set(self._gen_verify_label())
def _verify_event(self, dummy_event):
'''Hash algorithm selection'''
choosen = self._verify_var.get()[2:]
choosen = 'size' if choosen == self.labels.size else choosen
if choosen == self.settings.verify:
self.settings.verify = ''
else:
self.settings.verify = choosen
self._verify_selector['values'] = self._gen_verify_list()
self._verify_var.set(self._gen_verify_label())
def _clear_source(self):
'''Clear source text'''
if askyesno(title=self.labels.warning, message=self.labels.ask_clear_source):
self._source_text.delete('1.0', 'end')
def _clear_info(self):
'''Clear info text'''
self._info_text.configure(state='normal')
self._info_text.delete('1.0', 'end')
self._info_text.configure(state='disabled')
self._info_text.configure(foreground=self._info_fg, background=self._info_bg)
self._warning_state = 'stop'
def _start_worker(self, src_paths, dst_path, simulate):
'''Disable source selection and start worker'''
if self._mk_log_dir():
return
try:
self.settings.save()
except:
showerror(title=self.labels.warning, message=self.labels.config_error)
return
self._exec_button.configure(state='disabled')
self._warning_state = 'disabled'
self._clear_info()
self._quit_button_text.set(self.labels.abort)
if simulate:
self._simulate_button_text.set(self.labels.abort)
else:
self._simulate_button.configure(state='disabled')
self._work_thread = WorkThread(
src_paths,
dst_path,
simulate,
self
)
self._work_thread.start()
def _simulate(self):
'''Run simulation'''
if self._work_thread:
self._work_thread.kill()
return
src_paths = self._get_source_paths()
if not src_paths:
return
dst_path = self._get_destination_path(src_paths)
if not dst_path:
return
self._start_worker(src_paths, dst_path, True)
def _execute(self):
'''Start copy process / worker'''
if self._work_thread:
return
src_paths = self._get_source_paths()
if not src_paths:
return
dst_path = self._get_destination_path(src_paths)
if not dst_path:
return
if self._mk_destination_path(dst_path):
return
self._start_worker(src_paths, dst_path, False)
def _echo_help(self):
'''Show RoboCopy help'''
self._clear_info()
for line in RoboCopy(parameters='/?').popen().stdout:
self.echo(line.strip())
self.echo(self.labels.help_text)
def _init_warning(self):
'''Init warning functionality'''
self._warning_state = 'disabled'
self._warning()
def _enable_warning(self):
'''Enable red text field and blinking Label'''
self._info_text.configure(foreground=self._defs.red_fg, background=self._defs.red_bg)
self._warning_state = 'enable'
def _warning(self):
'''Show flashing warning'''
if self._warning_state == 'enable':
self._info_label.configure(text=self.labels.warning)
self._warning_state = '1'
if self._warning_state == '1':
self._info_label.configure(foreground=self._defs.red_fg, background=self._defs.red_bg)
self._warning_state = '2'
elif self._warning_state == '2':
self._info_label.configure(foreground=self._label_fg, background=self._label_bg)
self._warning_state = '1'
elif self._warning_state != 'disabled':
self._info_label.configure(text= '', foreground=self._label_fg, background=self._label_bg)
self._warning_state = 'disabled'
self.after(500, self._warning)
def _toggle_shutdown(self):
'''Toggle select switch to shutdown after finish'''
if self._shutdown.get():
self._shutdown.set(False)
if askyesno(title=self.labels.warning, message=self.labels.shutdown_warning):
self._shutdown.set(True)
def _reset(self):
'''Run this when worker has finished copy process'''
self._simulate_button_text.set(self.labels.simulate)
self._simulate_button.configure(state='normal')
self._exec_button.configure(state='normal')
self._quit_button_text.set(self.labels.quit)
self._work_thread = None
def _quit_app(self):
'''Quit app or ask to abort process'''
if self._work_thread:
if self._work_thread.kill_is_set():
self._reset()
else:
if askokcancel(title=self.labels.warning, message=self.labels.abort_warning):
self._work_thread.kill() # kill running work thread
return
self._get_log_dir()
try:
self.settings.save()
except:
pass
self.destroy()
def _delay_shutdown(self):
'''Delay shutdown and update progress bar'''
if self._shutdown_cnt < self._defs.shutdown_delay:
self._shutdown_cnt += 1
self._delay_progressbar.step(1)
self._shutdown_window.after(1000, self._delay_shutdown)
else:
run(['shutdown', '/s'])
def _shutdown_dialog(self):
'''Show shutdown dialog'''
self._shutdown_window = Toplevel(self)
self._shutdown_window.title(self.labels.warning)
self._shutdown_window.transient(self)
self._shutdown_window.focus_set()
self._shutdown_window.resizable(False, False)
self._shutdown_window.grab_set()
frame = Frame(self._shutdown_window, padding=self._pad)
frame.pack(fill='both', expand=True)
Label(frame,
text = '\u26A0',
font = (self._font['family'], self._font['size'] * self._defs.symbol_factor),
foreground = self._defs.symbol_fg,
background = self._defs.symbol_bg
).pack(side='left', padx=self._pad, pady=self._pad)
Label(frame, text=self.labels.shutdown_question, anchor='s').pack(
side='right', fill='both', padx=self._pad, pady=self._pad
)
frame = Frame(self._shutdown_window, padding=self._pad)
frame.pack(fill='both', expand=True)
self._delay_progressbar = Progressbar(frame, mode='determinate', maximum=self._defs.shutdown_delay)
self._delay_progressbar.pack(side='top', fill='x', padx=self._pad, pady=self._pad)
cancel_button = Button(frame, text=self.labels.cancel_shutdown, command=self._shutdown_window.destroy)
cancel_button.pack(side='bottom', fill='both', padx=self._pad, pady=self._pad)
self.update_idletasks()
self._shutdown_cnt = 0
self._delay_shutdown()
self._shutdown_window.wait_window(self._shutdown_window)
def echo(self, *args, end=None):
'''Write message to info field (ScrolledText)'''
msg = ' '.join(f'{arg}' for arg in args)
self._info_text.configure(state='normal')
if not self._info_newline:
self._info_text.delete('end-2l', 'end-1l')
self._info_text.insert('end', f'{msg}\n')
self._info_text.configure(state='disabled')
if self._info_newline:
self._info_text.yview('end')
self._info_newline = end != '\r'
def finished(self, returncode):
'''Run this when worker has finished copy process'''
if returncode:
if self._admin_rights and self._shutdown.get(): ### Shutdown dialog ###
self._shutdown_dialog()
if isinstance(returncode, Exception):
self._enable_warning()
showerror(
title = self.labels.error,
message = f'{self.labels.aborted_on_error}\n\n{type(returncode)}:\n{returncode}'
)
elif isinstance(returncode, str):
self._enable_warning()
showwarning(title=self.labels.warning, message=self.labels.process_returned.replace('#', returncode))
else:
self._info_text.configure(foreground=self._defs.green_fg, background=self._defs.green_bg)
self._source_text.delete('1.0', 'end')
self._reset()
if __name__ == '__main__': # start here when run as application
Gui().mainloop()