SXXXXXXX_GitUtility/gui.py
2025-04-07 14:35:48 +02:00

762 lines
33 KiB
Python

# gui.py
import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox, simpledialog
import logging
import os
import re # Ensure re is imported
# Import constant from the central location
from config_manager import DEFAULT_BACKUP_DIR
# --- Tooltip Class Definition ---
class Tooltip:
"""Simple tooltip implementation for Tkinter widgets."""
def __init__(self, widget, text):
"""Initialize tooltip."""
self.widget = widget
self.text = text
self.tooltip_window = None
self.id = None
self.x = self.y = 0
def showtip(self):
"""Display text in a tooltip window."""
self.hidetip()
if not self.widget.winfo_exists():
return
try:
x_rel, y_rel, _, _ = self.widget.bbox("insert")
x_root = self.widget.winfo_rootx()
y_root = self.widget.winfo_rooty()
x_pos = x_root + x_rel + 25
y_pos = y_root + y_rel + 25
except tk.TclError:
x_root = self.widget.winfo_rootx()
y_root = self.widget.winfo_rooty()
widget_width = self.widget.winfo_width()
widget_height = self.widget.winfo_height()
x_pos = x_root + widget_width // 2
y_pos = y_root + widget_height + 5
self.tooltip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{int(x_pos)}+{int(y_pos)}")
label = tk.Label(
tw, text=self.text, justify=tk.LEFT, background="#ffffe0",
relief=tk.SOLID, borderwidth=1, font=("tahoma", "8", "normal")
)
label.pack(ipadx=1)
def hidetip(self):
"""Hide the tooltip window."""
tw = self.tooltip_window
self.tooltip_window = None
if tw:
try:
if tw.winfo_exists():
tw.destroy()
except tk.TclError:
pass
# --- End Tooltip Class ---
# --- Gitignore Editor Window Class ---
class GitignoreEditorWindow(tk.Toplevel):
""" Toplevel window for editing the .gitignore file. """
def __init__(self, master, gitignore_path, logger):
""" Initialize the editor window. """
super().__init__(master)
self.gitignore_path = gitignore_path
self.logger = logger
self.original_content = ""
self.title(f"Edit {os.path.basename(gitignore_path)}")
self.geometry("600x450")
self.minsize(400, 300)
self.grab_set()
self.transient(master)
self.protocol("WM_DELETE_WINDOW", self._on_close)
main_frame = ttk.Frame(self, padding="10")
main_frame.pack(fill=tk.BOTH, expand=True)
main_frame.rowconfigure(0, weight=1)
main_frame.columnconfigure(0, weight=1)
self.text_editor = scrolledtext.ScrolledText(
main_frame, wrap=tk.WORD, font=("Consolas", 10), undo=True
)
self.text_editor.grid(row=0, column=0, sticky="nsew", pady=(0, 10))
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=1, column=0, sticky="ew")
button_frame.columnconfigure(0, weight=1) # Spacer left
button_frame.columnconfigure(3, weight=1) # Spacer right
self.save_button = ttk.Button(
button_frame, text="Save and Close", command=self._save_and_close
)
self.save_button.grid(row=0, column=2, padx=5)
self.cancel_button = ttk.Button(
button_frame, text="Cancel", command=self._on_close
)
self.cancel_button.grid(row=0, column=1, padx=5)
self._load_file()
self._center_window(master)
self.text_editor.focus_set()
def _center_window(self, parent):
"""Centers the editor window relative to its parent."""
self.update_idletasks()
parent_x = parent.winfo_rootx()
parent_y = parent.winfo_rooty()
parent_width = parent.winfo_width()
parent_height = parent.winfo_height()
win_width = self.winfo_width()
win_height = self.winfo_height()
x_pos = parent_x + (parent_width // 2) - (win_width // 2)
y_pos = parent_y + (parent_height // 2) - (win_height // 2)
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x_pos = max(0, min(x_pos, screen_width - win_width))
y_pos = max(0, min(y_pos, screen_height - win_height))
self.geometry(f"+{int(x_pos)}+{int(y_pos)}")
def _load_file(self):
"""Loads the content of the .gitignore file into the editor."""
self.logger.info(f"Loading content for: {self.gitignore_path}")
try:
content = ""
if os.path.exists(self.gitignore_path):
with open(self.gitignore_path, 'r', encoding='utf-8',
errors='replace') as f:
content = f.read()
self.logger.debug(".gitignore content loaded.")
else:
self.logger.info(f"'{self.gitignore_path}' does not exist.")
self.original_content = content
self.text_editor.delete("1.0", tk.END)
self.text_editor.insert(tk.END, self.original_content)
self.text_editor.edit_reset()
except IOError as e:
self.logger.error(f"Read error: {e}", exc_info=True)
messagebox.showerror("Error Reading", f"Could not read file:\n{e}",
parent=self)
except Exception as e:
self.logger.exception(f"Unexpected load error: {e}")
messagebox.showerror("Error", f"Unexpected load error:\n{e}",
parent=self)
def _save_file(self):
"""Saves the current editor content to the .gitignore file."""
current_content = self.text_editor.get("1.0", tk.END).rstrip()
if current_content:
current_content += "\n"
normalized_original = self.original_content.rstrip()
if normalized_original:
normalized_original += "\n"
if current_content == normalized_original:
self.logger.info("No changes detected. Skipping save.")
return True
self.logger.info(f"Saving changes to: {self.gitignore_path}")
try:
with open(self.gitignore_path, 'w', encoding='utf-8', newline='\n') as f:
f.write(current_content)
self.logger.info(".gitignore saved successfully.")
self.original_content = current_content
self.text_editor.edit_reset()
return True
except IOError as e:
self.logger.error(f"Write error: {e}", exc_info=True)
messagebox.showerror("Error Saving", f"Could not save file:\n{e}",
parent=self)
return False
except Exception as e:
self.logger.exception(f"Unexpected save error: {e}")
messagebox.showerror("Error", f"Unexpected save error:\n{e}",
parent=self)
return False
def _save_and_close(self):
"""Saves the file and closes the window if save succeeds."""
if self._save_file():
self.destroy()
def _on_close(self):
"""Handles closing the window (checks for unsaved changes)."""
current_content = self.text_editor.get("1.0", tk.END).rstrip()
if current_content: current_content += "\n"
normalized_original = self.original_content.rstrip()
if normalized_original: normalized_original += "\n"
if current_content != normalized_original:
response = messagebox.askyesnocancel(
"Unsaved Changes", "Save changes?", parent=self
)
if response is True:
self._save_and_close()
elif response is False:
self.logger.warning("Discarding editor changes.")
self.destroy()
# else (Cancel): Do nothing
else:
self.destroy()
# --- End Gitignore Editor Window ---
# --- Create Tag Dialog ---
class CreateTagDialog(simpledialog.Dialog):
""" Dialog to get new tag name and message. """
def __init__(self, parent, title="Create New Tag"):
"""Initialize the dialog."""
self.tag_name_var = tk.StringVar()
self.tag_message_var = tk.StringVar()
self.result = None
super().__init__(parent, title=title)
def body(self, master):
"""Create dialog body with input fields."""
name_label = ttk.Label(master, text="Tag Name:")
name_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.name_entry = ttk.Entry(
master, textvariable=self.tag_name_var, width=40
)
self.name_entry.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
message_label = ttk.Label(master, text="Tag Message:")
message_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.message_entry = ttk.Entry(
master, textvariable=self.tag_message_var, width=40
)
self.message_entry.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
master.columnconfigure(1, weight=1) # Allow entries to expand
return self.name_entry # Initial focus
def validate(self):
"""Validate the input fields."""
name = self.tag_name_var.get().strip()
message = self.tag_message_var.get().strip()
if not name:
messagebox.showwarning("Input Error", "Tag name empty.", parent=self)
return 0 # Fail
if not message:
messagebox.showwarning("Input Error", "Tag message empty.", parent=self)
return 0 # Fail
# Validate tag name format using regex
pattern = r"^(?![./]|.*([./]{2,}|[.]$|\.lock$))[^ \t\n\r\f\v~^:?*[\\]+(?<!\.)$"
if not re.match(pattern, name):
messagebox.showwarning("Input Error", "Invalid tag name format.",
parent=self)
return 0 # Fail
return 1 # Success
def apply(self):
"""Process the data if validation succeeds."""
name = self.tag_name_var.get().strip()
message = self.tag_message_var.get().strip()
self.result = (name, message)
# --- End Create Tag Dialog ---
class MainFrame(ttk.Frame):
""" The main frame containing all GUI elements. """
GREEN = "#90EE90" # Light Green
RED = "#F08080" # Light Coral
# --- MODIFIED: __init__ ---
# Added manual_commit_cb
def __init__(self, master, load_profile_settings_cb, browse_folder_cb,
update_svn_status_cb, prepare_svn_for_git_cb, create_git_bundle_cb,
fetch_from_git_bundle_cb, config_manager_instance, profile_sections_list,
add_profile_cb, remove_profile_cb, manual_backup_cb,
open_gitignore_editor_cb, save_profile_cb,
refresh_tags_cb, create_tag_cb, checkout_tag_cb,
manual_commit_cb): # Added manual commit callback
""" Initializes the MainFrame. """
super().__init__(master)
self.master = master
# Store callbacks
self.load_profile_settings_callback = load_profile_settings_cb
self.browse_folder_callback = browse_folder_cb
self.update_svn_status_callback = update_svn_status_cb
self.prepare_svn_for_git_callback = prepare_svn_for_git_cb
self.create_git_bundle_callback = create_git_bundle_cb
self.fetch_from_git_bundle_callback = fetch_from_git_bundle_cb
self.add_profile_callback = add_profile_cb
self.remove_profile_callback = remove_profile_cb
self.manual_backup_callback = manual_backup_cb
self.open_gitignore_editor_callback = open_gitignore_editor_cb
self.save_profile_callback = save_profile_cb
self.refresh_tags_callback = refresh_tags_cb
self.create_tag_callback = create_tag_cb
self.checkout_tag_callback = checkout_tag_cb
self.manual_commit_callback = manual_commit_cb # Store manual commit callback
self.config_manager = config_manager_instance
self.initial_profile_sections = profile_sections_list
self.style = ttk.Style()
self.style.theme_use('clam')
self.pack(side=tk.TOP, fill=tk.BOTH, expand=True, padx=10, pady=10)
# Tkinter Variables
self.profile_var = tk.StringVar()
self.autobackup_var = tk.BooleanVar()
self.backup_dir_var = tk.StringVar()
self.autocommit_var = tk.BooleanVar() # For autocommit before bundle
self.commit_message_var = tk.StringVar() # For manual/auto commit message
self.backup_exclude_extensions_var = tk.StringVar()
# Widget Creation
self._create_profile_frame()
self._create_repo_frame() # Paths/Bundles only
self._create_backup_frame() # Backup settings
self._create_commit_tag_frame() # Commit/Tag UI (modified layout)
self._create_function_frame() # Core Actions
self._create_log_area()
# Initial State
self._initialize_profile_selection()
self.toggle_backup_dir()
def _create_profile_frame(self):
"""Creates the frame for profile selection and management."""
self.profile_frame = ttk.LabelFrame(
self, text="Profile Configuration", padding=(10, 5)
)
self.profile_frame.pack(pady=5, fill="x")
self.profile_frame.columnconfigure(1, weight=1) # Dropdown expands
profile_label = ttk.Label(self.profile_frame, text="Profile:")
profile_label.grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
self.profile_dropdown = ttk.Combobox(
self.profile_frame, textvariable=self.profile_var,
state="readonly", width=35, values=self.initial_profile_sections
)
self.profile_dropdown.grid(row=0, column=1, sticky=tk.EW, padx=5, pady=5)
self.profile_dropdown.bind(
"<<ComboboxSelected>>",
lambda e: self.load_profile_settings_callback(self.profile_var.get())
)
self.profile_var.trace_add(
"write",
lambda *a: self.load_profile_settings_callback(self.profile_var.get())
)
self.save_settings_button = ttk.Button(
self.profile_frame, text="Save Settings",
command=self.save_profile_callback
)
self.save_settings_button.grid(row=0, column=2, sticky=tk.W,
padx=(5, 2), pady=5)
self.create_tooltip(self.save_settings_button,
"Save settings for the selected profile.")
self.add_profile_button = ttk.Button(
self.profile_frame, text="Add", width=5,
command=self.add_profile_callback
)
self.add_profile_button.grid(row=0, column=3, sticky=tk.W,
padx=(2, 0), pady=5)
self.remove_profile_button = ttk.Button(
self.profile_frame, text="Remove", width=8,
command=self.remove_profile_callback
)
self.remove_profile_button.grid(row=0, column=4, sticky=tk.W,
padx=(2, 5), pady=5)
def _create_repo_frame(self):
"""Creates the frame ONLY for repository paths and bundle names."""
self.repo_frame = ttk.LabelFrame(
self, text="Repository & Bundle Paths", padding=(10, 5)
)
self.repo_frame.pack(pady=5, fill="x")
col_label = 0; col_entry = 1; col_button = 2; col_indicator = 3
self.repo_frame.columnconfigure(col_entry, weight=1) # Entry expands
# Row 0: SVN Path
svn_label = ttk.Label(self.repo_frame, text="SVN Working Copy:")
svn_label.grid(row=0, column=col_label, sticky=tk.W, padx=5, pady=3)
self.svn_path_entry = ttk.Entry(self.repo_frame, width=60)
self.svn_path_entry.grid(row=0, column=col_entry, sticky=tk.EW, padx=5, pady=3)
self.svn_path_entry.bind(
"<FocusOut>",
lambda e: self.update_svn_status_callback(self.svn_path_entry.get())
)
self.svn_path_entry.bind(
"<Return>",
lambda e: self.update_svn_status_callback(self.svn_path_entry.get())
)
self.svn_path_browse_button = ttk.Button(
self.repo_frame, text="Browse...", width=9,
command=lambda: self.browse_folder_callback(self.svn_path_entry)
)
self.svn_path_browse_button.grid(row=0, column=col_button, sticky=tk.W,
padx=(0, 5), pady=3)
self.svn_status_indicator = tk.Label(
self.repo_frame, text="", width=2, height=1, relief=tk.SUNKEN,
background=self.RED, anchor=tk.CENTER
)
self.svn_status_indicator.grid(row=0, column=col_indicator, sticky=tk.E,
padx=(0, 5), pady=3)
self.create_tooltip(self.svn_status_indicator,
"Git repo status (Green=Ready, Red=Not Ready)")
# Row 1: USB/Bundle Target Path
usb_label = ttk.Label(self.repo_frame, text="Bundle Target Dir:")
usb_label.grid(row=1, column=col_label, sticky=tk.W, padx=5, pady=3)
self.usb_path_entry = ttk.Entry(self.repo_frame, width=60)
self.usb_path_entry.grid(row=1, column=col_entry, sticky=tk.EW, padx=5, pady=3)
self.usb_path_browse_button = ttk.Button(
self.repo_frame, text="Browse...", width=9,
command=lambda: self.browse_folder_callback(self.usb_path_entry)
)
self.usb_path_browse_button.grid(row=1, column=col_button, sticky=tk.W,
padx=(0, 5), pady=3)
# Row 2: Create Bundle Name
create_label = ttk.Label(self.repo_frame, text="Create Bundle Name:")
create_label.grid(row=2, column=col_label, sticky=tk.W, padx=5, pady=3)
self.bundle_name_entry = ttk.Entry(self.repo_frame, width=60)
self.bundle_name_entry.grid(row=2, column=col_entry, columnspan=2, # Span 2 cols
sticky=tk.EW, padx=5, pady=3)
# Row 3: Fetch Bundle Name
fetch_label = ttk.Label(self.repo_frame, text="Fetch Bundle Name:")
fetch_label.grid(row=3, column=col_label, sticky=tk.W, padx=5, pady=3)
self.bundle_updated_name_entry = ttk.Entry(self.repo_frame, width=60)
self.bundle_updated_name_entry.grid(row=3, column=col_entry, columnspan=2,
sticky=tk.EW, padx=5, pady=3)
def _create_backup_frame(self):
"""Creates the frame for backup configuration including exclusions."""
self.backup_frame = ttk.LabelFrame(
self, text="Backup Configuration (ZIP)", padding=(10, 5)
)
self.backup_frame.pack(pady=5, fill="x")
col_label = 0; col_entry = 1; col_button = 2
self.backup_frame.columnconfigure(col_entry, weight=1) # Entry expands
# Row 0: Autobackup Checkbox
self.autobackup_checkbox = ttk.Checkbutton(
self.backup_frame, text="Automatic Backup before Create/Fetch",
variable=self.autobackup_var, command=self.toggle_backup_dir
)
self.autobackup_checkbox.grid(row=0, column=col_label, columnspan=3,
sticky=tk.W, padx=5, pady=(5, 0))
# Row 1: Backup Directory
backup_dir_label = ttk.Label(self.backup_frame, text="Backup Directory:")
backup_dir_label.grid(row=1, column=col_label, sticky=tk.W, padx=5, pady=5)
self.backup_dir_entry = ttk.Entry(
self.backup_frame, textvariable=self.backup_dir_var,
width=60, state=tk.DISABLED
)
self.backup_dir_entry.grid(row=1, column=col_entry, sticky=tk.EW,
padx=5, pady=5)
self.backup_dir_button = ttk.Button(
self.backup_frame, text="Browse...", width=9,
command=self.browse_backup_dir, state=tk.DISABLED
)
self.backup_dir_button.grid(row=1, column=col_button, sticky=tk.W,
padx=(0, 5), pady=5)
# Row 2: Exclude Extensions
exclude_label = ttk.Label(self.backup_frame, text="Exclude Extensions:")
exclude_label.grid(row=2, column=col_label, sticky=tk.W, padx=5, pady=5)
self.backup_exclude_entry = ttk.Entry(
self.backup_frame, textvariable=self.backup_exclude_extensions_var,
width=60
)
self.backup_exclude_entry.grid(row=2, column=col_entry, columnspan=2,
sticky=tk.EW, padx=5, pady=5)
self.create_tooltip(self.backup_exclude_entry,
"Comma-separated extensions (e.g., .log,.tmp,.bak)")
# --- MODIFIED: Commit / Tag Management Frame Layout ---
def _create_commit_tag_frame(self):
"""Creates the frame for commit settings and tag management."""
self.commit_tag_frame = ttk.LabelFrame(
self, text="Commit / Tag Management", padding=(10, 5)
)
self.commit_tag_frame.pack(pady=5, fill="x")
# --- Configure grid columns ---
# Col 0: Labels/Checkboxes
# Col 1: Entries / Listbox (Expands)
# Col 2: Commit Button
# Col 3: Vertical Button Column (Tags/Gitignore) (Fixed Width)
self.commit_tag_frame.columnconfigure(1, weight=1)
self.commit_tag_frame.rowconfigure(2, weight=1) # Listbox expands vertically
# --- Commit Area ---
# Row 0: Autocommit Checkbox (Moved to top)
self.autocommit_checkbox = ttk.Checkbutton(
self.commit_tag_frame, text="Autocommit before 'Create Bundle'",
variable=self.autocommit_var, state=tk.DISABLED
)
self.autocommit_checkbox.grid(row=0, column=0, columnspan=3, # Span 3 cols
sticky="w", padx=5, pady=(5, 3))
self.create_tooltip(self.autocommit_checkbox,
"If checked, commit changes before creating bundle.")
# Row 1: Commit Message + Commit Button
commit_msg_label = ttk.Label(self.commit_tag_frame, text="Commit Message:")
commit_msg_label.grid(row=1, column=0, sticky="w", padx=5, pady=3)
self.commit_message_entry = ttk.Entry(
self.commit_tag_frame, textvariable=self.commit_message_var,
width=50, state=tk.DISABLED
)
self.commit_message_entry.grid(row=1, column=1, sticky="ew", padx=5, pady=3)
self.create_tooltip(self.commit_message_entry,
"Message for manual commit or commit before tagging.")
# New Manual Commit Button
self.commit_button = ttk.Button(
self.commit_tag_frame, text="Commit", width=10,
command=self.manual_commit_callback, state=tk.DISABLED
)
self.commit_button.grid(row=1, column=2, sticky="w", padx=(5, 0), pady=3)
self.create_tooltip(self.commit_button,
"Commit staged changes with the provided message.")
# --- Tag Listing Area ---
# Row 2: Listbox + Scrollbar (in own frame for layout)
tag_list_frame = ttk.Frame(self.commit_tag_frame)
# Span label and entry columns
tag_list_frame.grid(row=2, column=0, columnspan=3, sticky="nsew",
padx=5, pady=(10,5)) # Add top padding
tag_list_frame.rowconfigure(0, weight=1)
tag_list_frame.columnconfigure(0, weight=1)
self.tag_listbox = tk.Listbox(
tag_list_frame, height=7, exportselection=False, # Slightly taller
selectmode=tk.SINGLE, font=("Consolas", 9)
)
self.tag_listbox.grid(row=0, column=0, sticky="nsew")
tag_scrollbar = ttk.Scrollbar(
tag_list_frame, orient=tk.VERTICAL, command=self.tag_listbox.yview
)
tag_scrollbar.grid(row=0, column=1, sticky="ns")
self.tag_listbox.config(yscrollcommand=tag_scrollbar.set)
self.create_tooltip(self.tag_listbox,
"Tags (newest first) with messages. Select to checkout.")
# --- Tag/Gitignore Action Buttons Area --- (Vertical column)
# Row 2, Column 3: Vertical Button Frame
action_button_frame = ttk.Frame(self.commit_tag_frame)
action_button_frame.grid(row=2, column=3, sticky="ns", # North-South align
padx=(5,0), pady=(10,5)) # Match listbox padding
button_width = 18 # Consistent width for vertical buttons
self.refresh_tags_button = ttk.Button(
action_button_frame, text="Refresh Tags", width=button_width,
command=self.refresh_tags_callback, state=tk.DISABLED
)
self.refresh_tags_button.pack(side=tk.TOP, fill=tk.X, pady=(0, 3))
self.create_tooltip(self.refresh_tags_button, "Reload tag list.")
self.create_tag_button = ttk.Button(
action_button_frame, text="Create Tag...", width=button_width,
command=self.create_tag_callback, state=tk.DISABLED
)
self.create_tag_button.pack(side=tk.TOP, fill=tk.X, pady=3)
self.create_tooltip(self.create_tag_button,
"Commit changes (requires message) and create tag.")
self.checkout_tag_button = ttk.Button(
action_button_frame, text="Checkout Selected Tag", width=button_width,
command=self.checkout_tag_callback, state=tk.DISABLED
)
self.checkout_tag_button.pack(side=tk.TOP, fill=tk.X, pady=3)
self.create_tooltip(self.checkout_tag_button,
"Switch to selected tag (Detached HEAD).")
# Moved Edit .gitignore button here
self.edit_gitignore_button = ttk.Button(
action_button_frame, text="Edit .gitignore", width=button_width,
command=self.open_gitignore_editor_callback, state=tk.DISABLED
)
self.edit_gitignore_button.pack(side=tk.TOP, fill=tk.X, pady=(3, 0))
self.create_tooltip(self.edit_gitignore_button,
"Open editor for the .gitignore file.")
def _create_function_frame(self):
"""Creates the frame holding the main Core Action buttons."""
self.function_frame = ttk.LabelFrame(
self, text="Core Actions", padding=(10, 10)
)
self.function_frame.pack(pady=5, fill="x", anchor=tk.N)
# Sub-frame for button layout
button_subframe = ttk.Frame(self.function_frame)
button_subframe.pack(fill=tk.X)
# Prepare SVN button
self.prepare_svn_button = ttk.Button(
button_subframe, text="Prepare SVN Repo",
command=self.prepare_svn_for_git_callback
)
self.prepare_svn_button.pack(side=tk.LEFT, padx=(0,5), pady=5)
# Create Bundle button
self.create_bundle_button = ttk.Button(
button_subframe, text="Create Bundle",
command=self.create_git_bundle_callback
)
self.create_bundle_button.pack(side=tk.LEFT, padx=5, pady=5)
# Fetch Bundle button
self.fetch_bundle_button = ttk.Button(
button_subframe, text="Fetch from Bundle",
command=self.fetch_from_git_bundle_callback
)
self.fetch_bundle_button.pack(side=tk.LEFT, padx=5, pady=5)
# Manual Backup Button
self.manual_backup_button = ttk.Button(
button_subframe, text="Backup Now (ZIP)",
command=self.manual_backup_callback
)
self.manual_backup_button.pack(side=tk.LEFT, padx=5, pady=5)
def _create_log_area(self):
"""Creates the scrolled text area for logging output."""
log_frame = ttk.Frame(self.master)
log_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True,
padx=10, pady=(5, 10))
self.log_text = scrolledtext.ScrolledText(
log_frame, height=10, width=100, # Reduced height slightly
font=("Consolas", 9), wrap=tk.WORD, state=tk.DISABLED
)
self.log_text.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
def _initialize_profile_selection(self):
"""Sets the initial value of the profile dropdown."""
try: from config_manager import DEFAULT_PROFILE
except ImportError: DEFAULT_PROFILE = "default"
if DEFAULT_PROFILE in self.initial_profile_sections:
self.profile_var.set(DEFAULT_PROFILE)
elif self.initial_profile_sections:
self.profile_var.set(self.initial_profile_sections[0])
# --- GUI Update Methods ---
def toggle_backup_dir(self):
"""Enables/disables backup directory widgets based on checkbox."""
new_state = tk.NORMAL if self.autobackup_var.get() else tk.DISABLED
if hasattr(self, 'backup_dir_entry'):
self.backup_dir_entry.config(state=new_state)
if hasattr(self, 'backup_dir_button'):
self.backup_dir_button.config(state=new_state)
def browse_backup_dir(self):
"""Opens a directory selection dialog for backup directory."""
initial_dir = self.backup_dir_var.get() or DEFAULT_BACKUP_DIR
dirname = filedialog.askdirectory(
initialdir=initial_dir, title="Select Backup Directory",
parent=self.master
)
if dirname:
self.backup_dir_var.set(dirname)
def update_svn_indicator(self, is_prepared):
"""Updates only the indicator color and Prepare button state."""
if is_prepared:
color = self.GREEN; state = tk.DISABLED; tip = "Prepared"
else:
color = self.RED; state = tk.NORMAL; tip = "Not prepared"
# Update indicator
if hasattr(self, 'svn_status_indicator'):
self.svn_status_indicator.config(background=color)
self.update_tooltip(self.svn_status_indicator, tip)
# Update Prepare button
if hasattr(self, 'prepare_svn_button'):
self.prepare_svn_button.config(state=state)
def update_profile_dropdown(self, sections):
"""Updates the profile combobox list."""
if hasattr(self, 'profile_dropdown'):
current = self.profile_var.get()
self.profile_dropdown['values'] = sections
# Maintain selection logic
if sections:
if current in sections: self.profile_var.set(current)
elif "default" in sections: self.profile_var.set("default")
else: self.profile_var.set(sections[0])
else: self.profile_var.set("")
def update_tag_list(self, tags_with_subjects):
"""Clears and repopulates tag listbox with name and subject."""
if not hasattr(self, 'tag_listbox'):
logging.error("Tag listbox missing for update.")
return
try:
self.tag_listbox.delete(0, tk.END)
if tags_with_subjects:
# Reset color if needed
try:
if self.tag_listbox.cget("fg") == "grey":
self.tag_listbox.config(fg='SystemWindowText')
except tk.TclError: pass # Ignore errors
# Insert items
for name, subject in tags_with_subjects:
display = f"{name}\t({subject})"
self.tag_listbox.insert(tk.END, display)
else:
# Show placeholder
self.tag_listbox.insert(tk.END, "(No tags found)")
try: self.tag_listbox.config(fg="grey")
except tk.TclError: pass # Ignore errors
except tk.TclError as e: logging.error(f"TclError updating tags: {e}")
except Exception as e: logging.error(f"Error updating tags: {e}", exc_info=True)
def get_selected_tag(self):
"""Returns the name only of the selected tag."""
if hasattr(self, 'tag_listbox'):
indices = self.tag_listbox.curselection()
if indices:
item = self.tag_listbox.get(indices[0])
if item != "(No tags found)":
name = item.split('\t', 1)[0] # Get text before tab
return name.strip()
return None
# --- Dialog Wrappers ---
def ask_new_profile_name(self):
return simpledialog.askstring("Add Profile", "Enter new profile name:",
parent=self.master)
def show_error(self, title, message):
messagebox.showerror(title, message, parent=self.master)
def show_info(self, title, message):
messagebox.showinfo(title, message, parent=self.master)
def show_warning(self, title, message):
messagebox.showwarning(title, message, parent=self.master)
def ask_yes_no(self, title, message):
return messagebox.askyesno(title, message, parent=self.master)
# --- Tooltip Helpers ---
def create_tooltip(self, widget, text):
tooltip = Tooltip(widget, text)
widget.bind("<Enter>", lambda e, tt=tooltip: tt.showtip(), add='+')
widget.bind("<Leave>", lambda e, tt=tooltip: tt.hidetip(), add='+')
widget.bind("<ButtonPress>", lambda e, tt=tooltip: tt.hidetip(), add='+')
def update_tooltip(self, widget, text):
widget.unbind("<Enter>")
widget.unbind("<Leave>")
widget.unbind("<ButtonPress>")
self.create_tooltip(widget, text)