-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
3413 lines (2842 loc) · 153 KB
/
gui.py
File metadata and controls
3413 lines (2842 loc) · 153 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
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
import tkinter as tk
from tkinter import ttk, filedialog, PhotoImage, font
import paramiko
import subprocess
import os
import warnings
import psutil
import sys
import shutil
import time
import constants as const
import constants as const_2
import termination
import datetime
from screeninfo import get_monitors
import configparser
import threading
import queue
from dictionary import (
vconf_variables,
vconf_tooltips,
tooltips,
script_toggle_variables_without_gzip,
sub_variables,
dependencies_text,
sections,
script_paths
)
app_instance = None
script_dir = os.path.dirname(sys.executable if getattr(sys, 'frozen', False) else os.path.abspath(__file__)) # Get the directory of the current script
if getattr(sys, 'frozen', False):
path_to_python_scripts = os.path.join(script_dir, '_internal')
else:
path_to_python_scripts = script_dir
closing_flag = False # Global flag to track if the GUI is closing
class SplashScreen(tk.Toplevel):
def __init__(self, master, image_path, timeout=3000):
super().__init__(master)
self.timeout = timeout
self.image_path = image_path
self.init_ui()
self.after(self.timeout, self.destroy)
def init_ui(self):
self.geometry("256x400")
self.overrideredirect(True)
self.lift()
self.attributes('-topmost', True)
# Find a monitor with height 1080, if available, otherwise use the screen with the mouse
preferred_screen = next((m for m in get_monitors() if m.height == 1080), None)
active_screen = preferred_screen if preferred_screen else next((m for m in get_monitors() if m.is_primary),
get_monitors()[0])
# Center the splash screen on the selected screen
x = active_screen.x + (active_screen.width // 2) - (256 // 2)
y = active_screen.y + (active_screen.height // 2) - (400 // 2)
self.geometry(f"256x400+{x}+{y}")
# Load and display the image
img = PhotoImage(file=self.image_path)
label_img = tk.Label(self, image=img)
label_img.image = img # Keep a reference to avoid garbage collection
label_img.place(relx=0.5, rely=0.5, anchor='center', y=-50) # Center the image vertically
# Text frame and labels
text_frame = tk.Frame(self, bg="white", height=100)
text_frame.pack(fill='x', side='bottom')
label_text_1 = tk.Label(text_frame, text="Loading QueueTY...", font=("Helvetica", 12, "bold"), bg="white")
label_text_1.pack(pady=(10, 0))
label_text_2 = tk.Label(text_frame, text="by Tristan Vick", font=("Helvetica", 10), bg="white")
label_text_2.pack(pady=(5, 0))
label_text_3 = tk.Label(text_frame, text="University at Buffalo's Aga Lab 2024", font=("Helvetica", 10),
bg="white")
label_text_3.pack(pady=(5, 10))
@staticmethod
def show_splash_screen(root, image_path):
splash = SplashScreen(root, image_path)
splash.update()
return splash
class ConsoleStream:
def __init__(self, append_func, delete_last_func, keyword="\u200B"):
self.app_instance = app_instance # Store app_instance for use in after()
self.append_func = append_func
self.delete_last_func = delete_last_func
self.keyword = keyword
self.is_logging = False
self.log_file = None
self.last_message = "" # Track last message to avoid duplicates
def write(self, message):
if message != self.last_message: # Only display if different from last message
self.last_message = message
if self.keyword in message:
self.append_func(message) # Append only when keyword is present
self.app_instance.after(50, self.delete_last_func) # Use instance variable for after()
# Save to log file if logging is active
if self.is_logging and self.log_file:
try:
self.log_file.write(message + '\n')
self.log_file.flush()
except Exception as e:
sys.__stdout__.write(f"Failed to write to log file: {e}\n")
def flush(self):
if self.is_logging and self.log_file:
self.log_file.flush()
def start_logging(self, log_file_path, header_info=""):
try:
self.log_file = open(log_file_path, "w")
self.is_logging = True
if header_info:
self.log_file.write(header_info + '\n')
sys.__stdout__.write(f"Logging started for task at {log_file_path}\n")
except Exception as e:
sys.__stdout__.write(f"Failed to start logging at {log_file_path}: {e}\n")
def stop_logging(self):
if self.log_file:
self.log_file.close()
self.log_file = None
self.is_logging = False
class Constants:
def __init__(self):
self.default_vconf_settings = {}
self.experimental_vconf_settings = {}
class ToolTip:
def __init__(self, widget, wrap_length=750):
"""
Initialize the ToolTip.
Parameters:
- widget: The widget to which the tooltip is attached.
- wrap_length: The maximum line length in pixels before wrapping occurs.
"""
self.widget = widget
self.wrap_length = wrap_length # Maximum width in pixels for wrapping
self.tip_window = None
# Use the widget's font if available; otherwise, use a default font
try:
self.font = font.Font(font=self.widget['font'])
except tk.TclError:
self.font = font.nametofont("TkDefaultFont") # Use default Tkinter font
# Calculate wraplength based on the desired character width
average_char_width = self.font.measure('n') # Approximate average character width
self.wrap_length = wrap_length or (30 * average_char_width)
def showtip(self, text):
"""
Display the tooltip with the given text.
Parameters:
- text: The text to display in the tooltip.
"""
if self.tip_window or not text:
return
# Calculate the default position of the tooltip (below the widget)
try:
# Get the bounding box of the widget's "insert" cursor
bbox = self.widget.bbox("insert")
if bbox:
x, y, _cx, cy = bbox
else:
# If "insert" is not applicable (e.g., for buttons), use widget's center
x = self.widget.winfo_width() // 2
y = self.widget.winfo_height() // 2
# Calculate absolute position
x = x + self.widget.winfo_rootx() + 25
y = y + cy + self.widget.winfo_rooty() + 25
except Exception as e:
print(f"Error calculating tooltip position: {e}")
x = self.widget.winfo_rootx() + 25
y = self.widget.winfo_rooty() + 25
# Create a new top-level window for the tooltip
self.tip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True) # Remove window decorations
# Initially position the tooltip
tw.wm_geometry(f"+{x}+{y}")
# Create a Label widget within the tooltip window
label = ttk.Label(
tw,
text=text,
background="yellow",
relief="solid",
borderwidth=1,
wraplength=self.wrap_length, # Set the wrap length dynamically
justify='left', # Align text to the left
padding=(5, 3) # Add some padding for better aesthetics
)
label.pack(ipadx=1)
# Ensure the tooltip window has been drawn to get its size
tw.update_idletasks()
# Get the tooltip window's dimensions
tw_width = tw.winfo_width()
tw_height = tw.winfo_height()
# Get the screen's dimensions
screen_width = tw.winfo_screenwidth()
screen_height = tw.winfo_screenheight()
# Get the current position of the tooltip
tooltip_x = tw.winfo_x()
tooltip_y = tw.winfo_y()
# Check if the tooltip goes beyond the bottom of the screen
if (tooltip_y + tw_height) > screen_height:
# Reposition the tooltip above the widget
new_y = y - tw_height - cy - 25 # Adjust the y-coordinate upwards
if new_y < 0:
new_y = 0 # Prevent tooltip from going off the top edge
tw.wm_geometry(f"+{x}+{new_y}")
# Optionally, check for horizontal overflow and adjust x if necessary
if (tooltip_x + tw_width) > screen_width:
new_x = screen_width - tw_width - 10 # 10 pixels padding from the edge
if new_x < 0:
new_x = 0 # Prevent tooltip from going off the left edge
tw.wm_geometry(f"+{new_x}+{tw.wm_geometry().split('+')[2]}")
def hidetip(self):
"""Hide the tooltip."""
tw = self.tip_window
self.tip_window = None
if tw:
tw.destroy()
# noinspection PyAttributeOutsideInit,PyProtectedMember,PyTypeChecker
class GUI(tk.Tk):
def __init__(self):
super().__init__()
global app_instance
app_instance = self # Set the global reference to the current instance
self.init_general_settings()
self.init_paths_and_icons()
self.load_sensitive_config()
self.init_attributes()
self.init_tabs()
self.load_settings(self.constants_last_path if getattr(sys, 'frozen', False) else "constants_last.txt")
self.bind_gui_events()
self.connect_to_server()
# region ---- General Initialization Functions ----
def init_general_settings(self):
"""Initialize general settings for the GUI, including title, geometry, SSH connection, and flags."""
self.title("QueueTY")
# Set default window dimensions
default_width, default_height = 1080, 960
# Find a monitor with height 1080, if available, otherwise use the screen with the mouse
preferred_screen = next((m for m in get_monitors() if m.height == 1080), None)
active_screen = preferred_screen if preferred_screen else next((m for m in get_monitors() if m.is_primary),
get_monitors()[0])
# Calculate usable screen height excluding the taskbar
usable_height = active_screen.height - 50 # Assume a typical taskbar height of ~50px
# Set the window dimensions, adjusting to the active screen's dimensions if needed
window_width = min(default_width, active_screen.width)
window_height = min(default_height, usable_height)
# Position the window at the top of the screen, centered horizontally
x_position = active_screen.x + (active_screen.width - window_width) // 2
y_position = active_screen.y # Start at the top of the screen
self.geometry(f"{window_width}x{window_height}+{x_position}+{y_position}")
self.resizable(False, False)
self.maxsize(window_width, window_height)
# Initialize other attributes
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.is_task_running = False
self.is_task_complete = False
self.is_queue_active = False
self.current_task_start_time = None
self.script_process = None
self.console_output_stream = ConsoleStream(self.append_to_console, self.delete_last_line)
def init_paths_and_icons(self):
"""Initialize paths and icons, including settings paths, script paths, and window icons."""
# Determine base path and icon path
if getattr(sys, 'frozen', False):
self.base_path = os.path.join(sys._MEIPASS) # Access to _MEIPASS needed for PyInstaller
icon_path = os.path.join(self.base_path, 'icon.png')
else:
self.base_path = os.path.dirname(os.path.abspath(__file__))
icon_path = 'icon.png'
# Initialize paths to settings files and scripts
self.constants_last_path = os.path.join(self.base_path, 'constants_last.txt')
self.constants_path = os.path.join(self.base_path, 'constants.py')
self.default_settings_path = os.path.join(self.base_path, 'default_settings.txt')
self.main_path = os.path.join(self.base_path, 'main.py')
self.gzip_and_unzip_path = os.path.join(self.base_path, 'gzip_and_unzip.py')
self.check_remote_directory_path = os.path.join(self.base_path, 'check_remote_directory.py')
self.clean_up_molecule_list_path = os.path.join(self.base_path, 'clean_up_molecule_list.py')
self.generate_conformers_vconf_path = os.path.join(self.base_path, 'generate_conformers_vconf.py')
self.cmdline_TMoleX_process_path = os.path.join(self.base_path, 'cmdline_TMoleX_process.py')
self.submit_remote_jobs_to_cluster_path = os.path.join(self.base_path, 'submit_remote_jobs_to_cluster.py')
self.check_cluster_queue_path = os.path.join(self.base_path, 'check_cluster_queue.py')
self.grab_files_from_cluster_path = os.path.join(self.base_path, 'grab_files_from_cluster.py')
self.write_new_inp_file_path = os.path.join(self.base_path, 'write_new_inp_file.py')
self.dictionary_path = os.path.join(self.base_path, 'dictionary.py')
# Set the window icon
self.window_icon_image = PhotoImage(file=icon_path)
self.iconphoto(False, self.window_icon_image)
# Set taskbar icon (.ico files only on Windows)
try:
self.wm_iconbitmap("icon.ico")
except tk.TclError as e:
print(f"Failed to set icon: {e}")
def init_attributes(self):
"""Initialize instance attributes for UI components, script settings, and GUI configurations."""
self.script_settings_canvas = None
self.script_settings_scrollbar = None
self.scrollable_script_settings_frame = None
self.main_frame = None
self.script_parameters_frame = None
self.right_frame = None
self.editable_variables_frame = None
self.directory_editing_frame = None
self.save_button = None
self.run_button = None
self.terminate_button = None
self.save_to_queue_button = None
self.save_default_button = None
self.load_default_button = None
self.console_text = None
self.console_scrollbar = None
self.auto_scroll = tk.BooleanVar(value=True)
self.run_button_console = None
self.terminate_button_console = None
self.vconf_settings_canvas = None
self.vconf_settings_scrollbar = None
self.scrollable_vconf_settings_frame = None
# Initialize attributes for script toggles and editable variables
self.script_toggle_vars = {}
self.editable_vars = {}
self.script_texts = {}
self.script_toggle_vars_widgets = {}
self.sub_var_frames = {}
self.disabled_toggles = {}
self.sub_var_frames = {}
self.initial_toggle_states = {}
self.special_toggle_vars = script_toggle_variables_without_gzip
self.gzip_and_unzip_var = tk.BooleanVar()
self.check_remote_directory_var = tk.BooleanVar()
# Queue-related attributes
self.current_task = None
self.previous_selection = None
self.status_labels = {}
self.status_frame = ttk.Frame(self.master)
self.status_frame.pack(fill='both', expand=False)
self.settings_label_text = tk.StringVar(value="Settings")
self.log_label_text = tk.StringVar(value="Log")
self.queue_dir = os.path.join(os.path.dirname(__file__), 'saves')
self.log_dir = os.path.join(os.path.dirname(__file__), 'logs')
os.makedirs(self.queue_dir, exist_ok=True)
os.makedirs(self.log_dir, exist_ok=True)
# Terminal-related attributes
self.ssh_channel = None
self.last_focus_out_time = None
self.is_autocompleting = False
self.autocomplete_buffer = ''
self.prompt_pattern = r'^[\w\W]*[@\$] ' # Adjust based on your shell prompt
paramiko.Transport._preferred_kex = ('diffie-hellman-group14-sha1', 'diffie-hellman-group-exchange-sha256')
paramiko.Transport._preferred_keys = ('ssh-rsa',)
paramiko.Transport._preferred_ciphers = ('aes128-ctr', 'aes192-ctr', 'aes256-ctr')
paramiko.Transport._preferred_macs = ('hmac-sha2-256', 'hmac-sha2-512')
def init_tabs(self):
style = ttk.Style()
style.theme_use("alt")
# Configure tab style
style.configure(
"TNotebook.Tab",
padding=(4, 3), # Adjust padding (horizontal, vertical)
font=("Arial", 10, "bold"), # Bold the tab text
background="#3BA870", # Custom tab background color
foreground="#4D4D4D", # Custom tab text color
)
style.map(
"TNotebook.Tab",
background=[("selected", "#57F6A4")], # Highlight color for selected tab
foreground=[("selected", "black")],
)
# **Custom Style for Checkbuttons**
style.configure(
"Custom.TCheckbutton",
background="black", # Match your GUI background
foreground="black", # Text color
font=("TkDefaultFont", 12),
borderwidth=0, # Remove border
relief="flat", # Flat appearance
)
style.map(
"Custom.TCheckbutton",
background=[("active", "#D9D9D9"),
("!active", "#D9D9D9")],
foreground=[("active", "black"),
("!active", "black")],
)
style = ttk.Style()
style.configure(
"Custom.TLabelframe",
borderwidth=0, # Remove the border
background="#D9D9D9"
)
style.configure(
"Custom.TLabelframe.Label",
background="#D9D9D9" # Match the background color for the label
)
self.script_parameters_frame = ttk.LabelFrame(
self.main_frame, text="Script Parameters", width=540, style="Custom.TLabelframe"
)
self.tabs = ttk.Notebook(self)
self.script_settings_tab = ttk.Frame(self.tabs)
self.console_tab = ttk.Frame(self.tabs)
self.vconf_settings_tab = ttk.Frame(self.tabs)
self.file_editor_tab = ttk.Frame(self.tabs)
self.queue_tab = ttk.Frame(self.tabs)
self.terminal_tab = ttk.Frame(self.tabs)
self.tutorial_tab = ttk.Frame(self.tabs)
self.tabs.add(self.script_settings_tab, text="Script Settings")
self.tabs.add(self.console_tab, text="Console")
self.tabs.add(self.vconf_settings_tab, text="VConf Settings")
self.tabs.add(self.file_editor_tab, text="File Editor")
self.tabs.add(self.queue_tab, text="Queue")
self.tabs.add(self.terminal_tab, text="Remote Server Terminal")
self.tabs.add(self.tutorial_tab, text="Tutorial / Help")
self.tabs.pack(expand=1, fill="both")
# Initialize the individual sections
self.create_script_settings_tab()
self.create_console_tab()
self.create_vconf_settings_tab()
self.create_file_editor_tab()
self.create_queue_tab()
self.create_terminal_tab()
self.create_tutorial_tab()
def bind_gui_events(self):
"""Bind events like window close to save settings and execute cleanup."""
self.protocol("WM_DELETE_WINDOW", self.handle_window_closing)
# endregion
# region ---- Script Settings Tab ----
def create_script_settings_tab(self):
"""Initialize the Script Settings tab layout, adding frames for parameters, editable variables,
and directory editing with scrolling support only for Script Parameters."""
# Main container for Script Settings tab
self.main_frame = ttk.Frame(self.script_settings_tab, width=1080)
self.main_frame.pack(fill="both", expand=True, padx=10, pady=0)
# Create a custom style for smaller buttons
style = ttk.Style()
style.configure('Small.TButton', padding=(2, 2), font=('TkDefaultFont', 9))
style.configure('Browse.TButton', padding=(1, 1), font=('TkDefaultFont', 7))
style.configure('Medium.TButton', padding=(3, 3), font=('TkDefaultFont', 12))
# Define custom styles for frames and label frames
style.configure(
"Custom.TLabelframe",
background="#D9D9D9",
borderwidth=2, # Add a visible border
relief="groove" # Add a groove effect for the border
)
style.configure("Custom.TLabelframe.Label", background="#D9D9D9")
style.configure("Custom.TFrame", background="#D9D9D9")
# Top frame for buttons
self.button_frame = ttk.Frame(self.main_frame)
self.button_frame.grid(row=0, column=0, columnspan=2, sticky="")
# Configure columns in button_frame to expand equally
self.button_frame.columnconfigure(0, weight=1)
self.button_frame.columnconfigure(1, weight=1)
# Frame for the left column buttons
left_buttons_frame = ttk.Frame(self.button_frame)
left_buttons_frame.grid(row=0, column=0, padx=(0, 200), pady=1, sticky="ns")
# Frame for the right column buttons
right_buttons_frame = ttk.Frame(self.button_frame)
right_buttons_frame.grid(row=0, column=1, padx=(200, 0), pady=1, sticky="ns")
# Configure frames to expand and fill their columns
left_buttons_frame.columnconfigure(0, weight=1)
right_buttons_frame.columnconfigure(0, weight=1)
# Left side buttons (aligned to left)
self.save_button = ttk.Button(left_buttons_frame, text="Save Settings", command=self.save_settings,
style='Small.TButton')
self.save_button.grid(row=0, column=0, sticky='', pady=2)
self.run_button = ttk.Button(left_buttons_frame, text="Run Script", command=self.run_script,
style='Small.TButton')
self.run_button.grid(row=1, column=0, sticky='', pady=2)
self.terminate_button = ttk.Button(left_buttons_frame, text="Terminate Script", command=self.terminate_script,
style='Small.TButton')
self.terminate_button.grid(row=2, column=0, sticky='', pady=2)
# Right side buttons (aligned to right)
self.save_default_button = ttk.Button(right_buttons_frame, text="Save New Default Settings",
command=self.save_default_settings, style='Small.TButton')
self.save_default_button.grid(row=0, column=1, sticky='', pady=2)
self.load_default_button = ttk.Button(right_buttons_frame, text="Load Default Settings",
command=self.load_default_settings, style='Small.TButton')
self.load_default_button.grid(row=1, column=1, sticky='', pady=2)
# Save to Queue button with text box
self.button_text_frame = ttk.Frame(right_buttons_frame)
self.button_text_frame.grid(row=2, column=1, sticky='', pady=2)
self.save_to_queue_button = ttk.Button(self.button_text_frame, text="Save to Queue", command=self.save_to_queue,
style='Small.TButton')
self.save_to_queue_button.pack(side="left")
# Replace Text widget with Entry widget for single-line input
self.text_box = ttk.Entry(self.button_text_frame, width=15, font=('TkDefaultFont', 12))
self.text_box.pack(side="left", padx=5)
# Left frame for Script Parameters with content
self.script_parameters_frame = ttk.LabelFrame(
self.main_frame, text="Script Parameters", width=540, style="Custom.TLabelframe"
)
self.script_parameters_frame.grid(row=3, rowspan=2, column=0, padx=10, pady=2, sticky="nsew")
# Set the background color for the script parameters canvas and frame
self.script_parameters_canvas = tk.Canvas(
self.script_parameters_frame, bg="#D9D9D9", highlightthickness=0
)
self.scrollable_script_parameters_frame = ttk.Frame(self.script_parameters_canvas, style="Custom.TFrame")
# Create window for the scrollable frame anchored at the top
self.script_parameters_canvas.create_window((0, 0), window=self.scrollable_script_parameters_frame, anchor="nw")
# Pack canvas without scrollbar
self.script_parameters_canvas.pack(side="left", fill="both", expand=True)
# Right frame for Editable Variables and Directory Editing
self.editable_right_frame = ttk.Frame(self.main_frame, width=540)
self.editable_right_frame.grid(row=3, column=1, padx=10, pady=2, sticky="nsew")
self.editable_variables_frame = ttk.LabelFrame(
self.editable_right_frame, text="Editable Variables", style="Custom.TLabelframe"
)
self.editable_variables_frame.pack(fill="both", expand=False, padx=10, pady=0)
self.directory_editing_frame = ttk.LabelFrame(
self.editable_right_frame, text="Directory Editing", style="Custom.TLabelframe"
)
self.directory_editing_frame.pack(fill="both", expand=False, padx=10, pady=0)
# Configure main content columns in row 3 to be equal
self.main_frame.grid_columnconfigure(0, weight=1, uniform="equal")
self.main_frame.grid_columnconfigure(1, weight=1, uniform="equal")
# Set row 3 to not expand vertically
self.main_frame.grid_rowconfigure(0, weight=0)
self.main_frame.grid_rowconfigure(1, weight=0)
self.main_frame.grid_rowconfigure(2, weight=0)
self.main_frame.grid_rowconfigure(3, weight=1)
self.main_frame.grid_rowconfigure(4, weight=3)
self.main_frame.grid_rowconfigure(5, weight=3)
self.main_frame.grid_rowconfigure(6, weight=3)
# Initialize sections
self.create_script_parameters_section()
self.create_directory_editing_section()
self.create_editable_variables_section()
# 1. Tab Layout and Initialization
def create_script_parameters_section(self):
"""Setup the Script Parameters section, initializing the toggle settings for various script parameters."""
self.script_row_counter = 0
for attr in script_toggle_variables_without_gzip:
value = getattr(const, attr, None)
if value is not None:
self.create_toggle_with_sub_variables(self.scrollable_script_parameters_frame, attr, value)
self.initial_toggle_states[attr] = value
self.script_row_counter += 2
# Bind mouse wheel scroll only within Script Parameters section
#self.script_parameters_canvas.bind("<MouseWheel>", self.on_mouse_wheel_script_parameters)
# def on_mouse_wheel_script_parameters(self, event):
# """Scroll the script parameters section with the mouse wheel."""
# self.script_parameters_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def create_editable_variables_section(self):
"""Initialize the Editable Variables section, displaying fields that users can edit directly within the GUI."""
self.create_editable_subsection(self.editable_variables_frame, "Commonly Edited", [
("list_folder_name", const.list_folder_name,
"This is the name of the folder where QueueTY will read and write to. The folder can be thought of as your experiment."),
("template_name", const.template_name, "Not too important. Can be left empty. Basically just adds text to the front of the INP file.")
])
self.create_editable_subsection(self.editable_variables_frame, "Less Commonly Edited", [
("temp_dir", const.temp_dir,
"Builds a temporary directory to store transient data in at the path described by remote_directory (see below). Can be renamed."),
("server", const.server, "Your server address eg. buffalo.edu"),
("port", const.port, "default SSH port is 22"),
("username", const.username, "Whatever your username is"),
("password", const.password, "Whatever your password is")
])
self.create_editable_subsection(self.editable_variables_frame, "One and Done", [
("compound_list_directory", const.compound_list_directory,
"This is the directory that list_folder_name is in."),
("vconf_path", const.vconf_path, "This is the path to the Vconf executable."),
("remote_directory", const.remote_directory,
"This is where on the remote server you would like to put the temp_dir folder. Basically the 'compound_list_directory' of the remote server.\n\nOnce you provide your credentials and press 'Save Settings' you will be able to access the Browse button."),
])
# Add trace on list_folder_name and compound_list_directory to update VCONF settings
self.editable_vars["list_folder_name"].bind("<FocusOut>", self.update_vconf_paths)
self.editable_vars["compound_list_directory"].bind("<FocusOut>", self.update_vconf_paths)
def create_directory_editing_section(self):
"""Setup Directory Editing section with toggles for options like gzip and remote directory checks."""
self.gzip_and_unzip_var = tk.BooleanVar(value=const.gzip_and_unzip_script)
self.create_toggle_with_sub_variables(self.directory_editing_frame, "gzip_and_unzip_script",
const.gzip_and_unzip_script, is_directory_editing=True)
self.sub_var_frames["gzip_and_unzip_script"] = self.directory_editing_frame.winfo_children()[1]
self.script_toggle_vars_widgets["gzip_and_unzip_script"] = self.directory_editing_frame.winfo_children()[0]
self.check_remote_directory_var = tk.BooleanVar(value=const.check_remote_directory_script)
self.create_toggle_with_sub_variables(self.directory_editing_frame, "check_remote_directory_script",
const.check_remote_directory_script, is_directory_editing=True)
self.sub_var_frames["check_remote_directory_script"] = self.directory_editing_frame.winfo_children()[3]
self.script_toggle_vars_widgets["check_remote_directory_script"] = \
self.directory_editing_frame.winfo_children()[2]
def create_editable_subsection(self, parent, title, variables):
"""Create a labeled subsection within a parent frame, displaying editable variables with optional browse buttons."""
subsection_frame = ttk.LabelFrame(parent, text=title)
subsection_frame.pack(fill="x", expand=False, padx=10, pady=10)
# Helper function to adjust entry width with min and max constraints
def adjust_entry_width(entry, min_width=20, max_width=30):
"""Adjust the width of an entry widget based on its content length, constrained by min and max width."""
content_length = len(entry.get())
new_width = max(min(content_length + 1, max_width), min_width) # Adjust width, within min/max bounds
entry.config(width=new_width)
row_counter = 0
for var_name, var_value, tooltip in variables:
var_label = ttk.Label(subsection_frame, text=var_name, font=("TkDefaultFont", 10))
var_label.grid(row=row_counter, column=0, sticky="w", padx=5, pady=2)
self.create_tooltip(var_label, tooltip)
var_entry = ttk.Entry(subsection_frame, font=("TkDefaultFont", 10), width=11) # Start with min width
var_entry.insert(0, str(var_value))
# Apply dynamic resizing with specified min and max widths
adjust_entry_width(var_entry)
var_entry.grid(row=row_counter, column=1, sticky="w", padx=5, pady=2)
var_entry.bind("<KeyRelease>", lambda e, entry=var_entry: adjust_entry_width(entry))
self.create_tooltip(var_entry, tooltip)
self.editable_vars[var_name] = var_entry
if var_name == "remote_directory":
browse_button = ttk.Button(subsection_frame, text="Browse",
command=lambda var=var_name: self.browse_remote_directory(var),
style='Browse.TButton')
browse_button.grid(row=row_counter, column=2, sticky="w", padx=5, pady=2)
var_entry.bind("<FocusOut>", self.save_remote_directory)
elif var_name in ["compound_list_directory", "list_folder_name", "remote_file_path"]:
browse_button = ttk.Button(subsection_frame, text="Browse",
command=lambda var=var_name: self.browse_directory(var),
style='Browse.TButton')
browse_button.grid(row=row_counter, column=2, sticky="w", padx=5, pady=2)
elif var_name == "vconf_path":
browse_button = ttk.Button(subsection_frame, text="Browse",
command=lambda var=var_name: self.browse_file(var),
style='Browse.TButton')
browse_button.grid(row=row_counter, column=2, sticky="w", padx=5, pady=2)
row_counter += 1
# 2. Toggle and Parameter Functions
def create_toggle_with_sub_variables(self, parent, toggle, value, is_directory_editing=False):
"""Create a toggle checkbox with sub-variables that depend on its state, dynamically resizing text entries."""
# Determine if the value should be a BooleanVar or Entry based on its type
toggle_check = None
if isinstance(value, bool):
toggle_var = tk.BooleanVar(value=value)
else:
toggle_var = tk.IntVar(value=value) # Use IntVar for integers like 0 and 1
self.script_toggle_vars[toggle] = toggle_var
# Create the main toggle checkbox for Boolean values only
if isinstance(value, bool):
toggle_var = tk.BooleanVar(value=value)
self.script_toggle_vars[toggle] = toggle_var
# **Use ttk.Checkbutton with Custom Style**
toggle_check = ttk.Checkbutton(
parent,
text=toggle,
variable=toggle_var,
command=lambda: self.toggle_sub_variables(toggle_var, sub_vars_frame, toggle, is_directory_editing),
style="Custom.TCheckbutton" # Apply the custom style
)
toggle_check.grid(row=self.script_row_counter, column=0, sticky="w", padx=5, pady=2)
tooltip_text = tooltips.get(toggle, "")
self.create_tooltip(toggle_check, tooltip_text)
self.script_toggle_vars_widgets[toggle] = toggle_check
else:
# For integer values, create an Entry widget instead of a checkbox
entry_widget = ttk.Entry(parent, textvariable=toggle_var, font=("TkDefaultFont", 10))
entry_widget.grid(row=self.script_row_counter, column=0, sticky="w", padx=5, pady=2)
tooltip_text = tooltips.get(toggle, "")
self.create_tooltip(entry_widget, tooltip_text)
self.script_toggle_vars_widgets[toggle] = entry_widget
# Frame for sub-variables associated with this toggle
sub_vars_frame = ttk.Frame(parent)
sub_vars_frame.grid(row=self.script_row_counter + 1, column=0, padx=20, sticky="nsew")
sub_vars_frame.widgets = [] # Track sub-variable widgets for this toggle
# Helper function to adjust entry width with constraints
def adjust_entry_width(entry, min_width=20, max_width=30):
content_length = len(entry.get())
new_width = max(min(content_length + 1, max_width), min_width)
entry.config(width=new_width)
# Create each sub-variable control based on its type
sub_row = 0
sorted_sub_vars = sorted(
sub_variables.get(toggle, [])) # Retrieve sub-variables from `sub_variables` dictionary
for sub_var in sorted_sub_vars:
sub_value = getattr(const, sub_var, None)
sub_var_label = ttk.Label(sub_vars_frame, text=sub_var, font=("TkDefaultFont", 10))
sub_var_label.grid(row=sub_row, column=0, sticky="w", padx=5, pady=2)
sub_vars_frame.widgets.append(sub_var_label)
# Debug message
# print(f"Created label for sub-variable '{sub_var}'")
tooltip_text = tooltips.get(sub_var, "")
self.create_tooltip(sub_var_label, tooltip_text)
if sub_value in [True, False]: # Boolean values become checkboxes
sub_var_entry = tk.BooleanVar(value=sub_value)
sub_var_check = ttk.Checkbutton(
sub_vars_frame,
variable=sub_var_entry,
style="Custom.TCheckbutton", # Apply the custom style
)
sub_var_check.grid(row=sub_row, column=1, sticky="w", padx=5, pady=2)
self.create_tooltip(sub_var_check, tooltip_text)
sub_vars_frame.widgets.append(sub_var_check)
self.editable_vars[sub_var] = sub_var_entry
# Debug message
# print(f"Created checkbox for sub-variable '{sub_var}' with initial value '{sub_value}'")
elif isinstance(sub_value, int): # Integer values get an integer-specific entry field
sub_var_entry = ttk.Entry(sub_vars_frame, font=("TkDefaultFont", 10))
sub_var_entry.insert(0, str(sub_value))
adjust_entry_width(sub_var_entry)
sub_var_entry.grid(row=sub_row, column=1, sticky="w", padx=5, pady=2)
sub_var_entry.bind("<KeyRelease>", lambda e, entry=sub_var_entry: adjust_entry_width(entry))
self.create_tooltip(sub_var_entry, tooltip_text)
sub_vars_frame.widgets.append(sub_var_entry)
self.editable_vars[sub_var] = sub_var_entry
# Debug message
# print(f"Created integer entry for sub-variable '{sub_var}' with initial value '{sub_value}'")
elif sub_var in ["timestamp_folder", "delete_file_path", "gzip_directory_by_name",
"unzip_directory_by_name", "remote_file_path"]:
# Text entry with a browse button for file/directory paths
sub_var_entry = ttk.Entry(sub_vars_frame, font=("TkDefaultFont", 10))
if sub_value is not None:
sub_var_entry.insert(0, sub_value)
adjust_entry_width(sub_var_entry)
sub_var_entry.grid(row=sub_row, column=1, sticky="w", padx=5, pady=2)
sub_var_entry.bind("<KeyRelease>", lambda e, entry=sub_var_entry: adjust_entry_width(entry))
self.create_tooltip(sub_var_entry, tooltip_text)
sub_vars_frame.widgets.append(sub_var_entry)
self.editable_vars[sub_var] = sub_var_entry
# Add browse button
browse_button = ttk.Button(sub_vars_frame, text="Browse",
command=lambda sv=sub_var: self.browse_remote_directory(sv), style='Browse.TButton')
browse_button.grid(row=sub_row, column=2, sticky="w", padx=5, pady=2)
sub_vars_frame.widgets.append(browse_button)
# Debug message
# print(f"Created file path entry with browse button for '{sub_var}' with initial value '{sub_value}'")
else: # All other values become text entries
sub_var_entry = ttk.Entry(sub_vars_frame, font=("TkDefaultFont", 10))
if sub_value is not None:
sub_var_entry.insert(0, str(sub_value))
adjust_entry_width(sub_var_entry)
sub_var_entry.grid(row=sub_row, column=1, sticky="w", padx=5, pady=2)
sub_var_entry.bind("<KeyRelease>", lambda e, entry=sub_var_entry: adjust_entry_width(entry))
self.create_tooltip(sub_var_entry, tooltip_text)
sub_vars_frame.widgets.append(sub_var_entry)
self.editable_vars[sub_var] = sub_var_entry
# Debug message
# print(f"Created text entry for sub-variable '{sub_var}' with initial value '{sub_value}'")
sub_row += 1
# Control the enabled/disabled state of sub-variables based on the main toggle's value
self.set_widget_state(sub_vars_frame, "normal" if toggle_var.get() else "disabled")
# Add the sub-variable frame and toggle widget for reference
self.sub_var_frames[toggle] = sub_vars_frame
self.script_toggle_vars_widgets[toggle] = toggle_check
# Increment row counter for layout
self.script_row_counter += 2
def toggle_sub_variables(self, toggle_var, sub_vars_frame, toggle, is_directory_editing=False):
"""Toggle visibility and interactivity of sub-variables when a main toggle is activated or deactivated."""
if toggle == "gzip_and_unzip_script":
self.toggle_script_parameters(toggle_var.get())
self.set_widget_state(sub_vars_frame, "normal" if toggle_var.get() else "disabled")
else:
state = "normal" if toggle_var.get() else "disabled"
if self.gzip_and_unzip_var.get() and not is_directory_editing:
state = "disabled"
toggle_var.set(False)
self.set_widget_state(sub_vars_frame, state)
# Ensure sub-variables maintain their order from the dictionary
ordered_sub_vars = [widget for sub_var in sub_variables[toggle] for widget in sub_vars_frame.widgets if
widget.cget("text") == sub_var]
for widget in ordered_sub_vars:
widget.tkraise() # Raise the widget to maintain order
def toggle_script_parameters(self, enable):
"""Enable or disable script parameters, primarily for controlling the gzip and directory check toggles."""
if enable:
self.disabled_toggles = {toggle: var.get() for toggle, var in self.script_toggle_vars.items() if
toggle != "gzip_and_unzip_script"}
for toggle, var in self.script_toggle_vars.items():
if toggle != "gzip_and_unzip_script":
self.set_widget_state(self.sub_var_frames[toggle], "disabled")
self.script_toggle_vars_widgets[toggle].config(state="disabled")
var.set(False)
else:
for toggle, was_enabled in self.disabled_toggles.items():
self.script_toggle_vars[toggle].set(was_enabled)
self.set_widget_state(self.sub_var_frames[toggle], "normal" if was_enabled else "disabled")
self.script_toggle_vars_widgets[toggle].config(state="normal")
# 3. Directory Editing and Path Browsing Functions
def add_browse_button_to_var(self, var_name, parent_frame):
"""Add a browse button next to specified variables, allowing users to navigate and select directories or files."""
var_entry = self.editable_vars.get(var_name)
if var_entry:
browse_button = ttk.Button(parent_frame, text="Browse",
command=lambda: self.browse_remote_directory(var_name))
var_entry.grid(row=var_entry.grid_info()["row"], column=1, sticky="w", padx=5, pady=2)
browse_button.grid(row=var_entry.grid_info()["row"], column=2, sticky="w", padx=5, pady=2)
# noinspection PyUnresolvedReferences
def browse_remote_directory(self, var_name):
"""Open a dialog to browse remote directories, updating the associated variable entry with the selected path."""
if not self.ssh_connected:
self.connect_to_server()
if not self.ssh_connected:
self.append_to_console("SSH connection is not established. Please check your credentials.")
return
initial_dir = self.editable_vars["remote_directory"].get() if var_name != "remote_directory" else "/"
remote_path = self.remote_directory_dialog(initial_dir, browse_files=(var_name != "remote_directory"))
if remote_path:
if var_name == "remote_directory" and remote_path.endswith('/'):
remote_path = remote_path.rstrip('/')
elif var_name in ["delete_file_path", "gzip_directory_by_name", "unzip_directory_by_name",
"timestamp_folder"]:
remote_directory = self.editable_vars["remote_directory"].get()
if remote_directory and remote_path.startswith(remote_directory):
remote_path = remote_path[len(remote_directory):].lstrip('/')
if var_name == "timestamp_folder" and remote_path.endswith(".tar.gz"):
remote_path = remote_path[:-7]
self.editable_vars[var_name].delete(0, tk.END)
self.editable_vars[var_name].insert(0, remote_path.replace('\\', '/'))
if var_name in ["compound_list_directory", "list_folder_name", "remote_directory"]:
self.update_vconf_paths()
def browse_directory(self, var_name):
initial_dir = self.editable_vars["compound_list_directory"].get() if var_name == "list_folder_name" else "/"
directory = filedialog.askdirectory(initialdir=initial_dir, title="Select Directory",
parent=self) # Set parent to self
if directory:
directory = directory.replace('/', '\\')
if var_name == "list_folder_name":
folder_name = os.path.basename(directory)
self.editable_vars[var_name].delete(0, tk.END)
self.editable_vars[var_name].insert(0, folder_name)
else:
self.editable_vars[var_name].delete(0, tk.END)
self.editable_vars[var_name].insert(0, directory)
if var_name in ["compound_list_directory", "list_folder_name"]:
self.update_vconf_paths()
# Utility Functions
@staticmethod
def set_widget_state(frame, state):
"""Set the state (enabled/disabled) for all child widgets in a frame."""
for widget in frame.winfo_children():
try:
widget.config(state=state)
except tk.TclError as e:
print(f"Failed to set widget state: {e}")
# endregion
# region ---- Console Tab ----
# 1. Console Initialization Functions
def create_console_tab(self):
"""Initialize the console tab with a text display, scrollbar, and run/terminate buttons."""
# Configure the grid for the console_tab
self.console_tab.rowconfigure(0, weight=4) # Console text widget row
self.console_tab.rowconfigure(1, weight=1) # Buttons row
self.console_tab.columnconfigure(0, weight=1) # Main content column
self.console_tab.columnconfigure(1, weight=0) # Scrollbar column
# Define custom styles for console buttons with larger font size
style = ttk.Style()
# Style for main console buttons
style.configure('Console.TButton',
background='#D9D9D9',
foreground='black',
font=('TkDefaultFont', 12), # Increased font size to 12
padding=(3, 3)) # Increased padding for better appearance
style.map('Console.TButton',
background=[('active', '#C0C0C0'), ('pressed', '#A0A0A0')])
# Style for search-related buttons
style.configure('Search.TButton',
background='#D9D9D9',
foreground='black',