fix canvas calculate and save state for new open app

This commit is contained in:
2025-08-26 00:48:02 +02:00
parent 1802f7ff06
commit 3867a2bf4f
15 changed files with 376 additions and 1507 deletions

View File

@@ -1,414 +0,0 @@
"""
A Tkinter widget for displaying animated icons.
This module provides the AnimatedIcon class, a custom Tkinter Canvas widget
that can display various types of animations. It supports both native Tkinter
drawing and Pillow (PIL) for anti-aliased graphics if available.
"""
import tkinter as tk
from math import sin, cos, pi
from typing import Tuple, Optional
try:
from PIL import Image, ImageDraw, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
def _hex_to_rgb(hex_color: str) -> Tuple[int, int, int]:
"""Converts a hex color string to an RGB tuple."""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
class AnimatedIcon(tk.Canvas):
"""A custom Tkinter Canvas widget for displaying animations."""
def __init__(self, master: tk.Misc, width: int = 20, height: int = 20, animation_type: str = "counter_arc", color: str = "#2a6fde", highlight_color: str = "#5195ff", use_pillow: bool = False, bg: Optional[str] = None) -> None:
if bg is None:
try:
bg = master.cget("background")
except tk.TclError:
bg = "#f0f0f0" # Fallback color
super().__init__(master, width=width, height=height, bg=bg, highlightthickness=0)
self.width = width
self.height = height
self.animation_type = animation_type
self.color = color
self.highlight_color = highlight_color
self.use_pillow = use_pillow and PIL_AVAILABLE
self.running = False
self.is_disabled = False
self.pause_count = 0
self.angle = 0
self.pulse_animation = False
self.after_id = None # ID for the after() job
self.color_rgb = _hex_to_rgb(self.color)
self.highlight_color_rgb = _hex_to_rgb(self.highlight_color)
if self.use_pillow:
self.image = Image.new(
"RGBA", (width * 4, height * 4), (0, 0, 0, 0))
self.draw = ImageDraw.Draw(self.image)
self.photo_image = None
def _draw_frame(self) -> None:
if self.use_pillow:
self._draw_pillow_frame()
else:
self._draw_canvas_frame()
def _draw_canvas_frame(self) -> None:
self.delete("all")
if self.pulse_animation:
self._draw_canvas_pulse()
elif self.animation_type == "line":
self._draw_canvas_line()
elif self.animation_type == "double_arc":
self._draw_canvas_double_arc()
elif self.animation_type == "counter_arc":
self._draw_canvas_counter_arc()
elif self.animation_type == "blink":
self._draw_canvas_blink()
def _draw_canvas_pulse(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
alpha = (sin(self.angle * 5) + 1) / 2
r = int(alpha * (self.highlight_color_rgb[0] - self.color_rgb[0]) + self.color_rgb[0])
g = int(alpha * (self.highlight_color_rgb[1] - self.color_rgb[1]) + self.color_rgb[1])
b = int(alpha * (self.highlight_color_rgb[2] - self.color_rgb[2]) + self.color_rgb[2])
pulse_color = f"#{r:02x}{g:02x}{b:02x}"
if self.animation_type == "line":
for i in range(8):
angle = i * (pi / 4)
start_x = center_x + cos(angle) * (self.width * 0.2)
start_y = center_y + sin(angle) * (self.height * 0.2)
end_x = center_x + cos(angle) * (self.width * 0.4)
end_y = center_y + sin(angle) * (self.height * 0.4)
self.create_line(start_x, start_y, end_x, end_y, fill=pulse_color, width=2)
elif self.animation_type == "double_arc":
radius = min(center_x, center_y) * 0.8
bbox = (center_x - radius, center_y - radius, center_x + radius, center_y + radius)
self.create_arc(bbox, start=0, extent=359.9, style=tk.ARC, outline=pulse_color, width=2)
elif self.animation_type == "counter_arc":
radius_outer = min(center_x, center_y) * 0.8
bbox_outer = (center_x - radius_outer, center_y - radius_outer, center_x + radius_outer, center_y + radius_outer)
self.create_arc(bbox_outer, start=0, extent=359.9, style=tk.ARC, outline=pulse_color, width=2)
radius_inner = min(center_x, center_y) * 0.6
bbox_inner = (center_x - radius_inner, center_y - radius_inner, center_x + radius_inner, center_y + radius_inner)
self.create_arc(bbox_inner, start=0, extent=359.9, style=tk.ARC, outline=self.color, width=2)
def _draw_canvas_line(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
for i in range(8):
angle = self.angle + i * (pi / 4)
start_x = center_x + cos(angle) * (self.width * 0.2)
start_y = center_y + sin(angle) * (self.height * 0.2)
end_x = center_x + cos(angle) * (self.width * 0.4)
end_y = center_y + sin(angle) * (self.height * 0.4)
alpha = (cos(self.angle * 2 + i * (pi / 4)) + 1) / 2
r = int(alpha * (self.highlight_color_rgb[0] - self.color_rgb[0]) + self.color_rgb[0])
g = int(alpha * (self.highlight_color_rgb[1] - self.color_rgb[1]) + self.color_rgb[1])
b = int(alpha * (self.highlight_color_rgb[2] - self.color_rgb[2]) + self.color_rgb[2])
color = f"#{r:02x}{g:02x}{b:02x}"
self.create_line(start_x, start_y, end_x, end_y, fill=color, width=2)
def _draw_canvas_double_arc(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
radius = min(center_x, center_y) * 0.8
bbox = (center_x - radius, center_y - radius, center_x + radius, center_y + radius)
start_angle1 = -self.angle * 180 / pi
extent1 = 120 + 60 * sin(-self.angle)
self.create_arc(bbox, start=start_angle1, extent=extent1, style=tk.ARC, outline=self.highlight_color, width=2)
start_angle2 = (-self.angle + pi) * 180 / pi
extent2 = 120 + 60 * sin(-self.angle + pi / 2)
self.create_arc(bbox, start=start_angle2, extent=extent2, style=tk.ARC, outline=self.color, width=2)
def _draw_canvas_counter_arc(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
radius_outer = min(center_x, center_y) * 0.8
bbox_outer = (center_x - radius_outer, center_y - radius_outer, center_x + radius_outer, center_y + radius_outer)
start_angle1 = -self.angle * 180 / pi
self.create_arc(bbox_outer, start=start_angle1, extent=150, style=tk.ARC, outline=self.highlight_color, width=2)
radius_inner = min(center_x, center_y) * 0.6
bbox_inner = (center_x - radius_inner, center_y - radius_inner, center_x + radius_inner, center_y + radius_inner)
start_angle2 = self.angle * 180 / pi + 60
self.create_arc(bbox_inner, start=start_angle2, extent=150, style=tk.ARC, outline=self.color, width=2)
def _draw_canvas_blink(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
radius = min(center_x, center_y) * 0.8
alpha = (sin(self.angle * 2) + 1) / 2
r = int(alpha * (self.highlight_color_rgb[0] - self.color_rgb[0]) + self.color_rgb[0])
g = int(alpha * (self.highlight_color_rgb[1] - self.color_rgb[1]) + self.color_rgb[1])
b = int(alpha * (self.highlight_color_rgb[2] - self.color_rgb[2]) + self.color_rgb[2])
blink_color = f"#{r:02x}{g:02x}{b:02x}"
self.create_arc(center_x - radius, center_y - radius, center_x + radius, center_y + radius, start=0, extent=359.9, style=tk.ARC, outline=blink_color, width=4)
def _draw_pillow_frame(self) -> None:
self.draw.rectangle([0, 0, self.width * 4, self.height * 4], fill=(0, 0, 0, 0))
if self.pulse_animation:
self._draw_pillow_pulse()
elif self.animation_type == "line":
self._draw_pillow_line()
elif self.animation_type == "double_arc":
self._draw_pillow_double_arc()
elif self.animation_type == "counter_arc":
self._draw_pillow_counter_arc()
elif self.animation_type == "blink":
self._draw_pillow_blink()
resized_image = self.image.resize((self.width, self.height), Image.Resampling.LANCZOS)
self.photo_image = ImageTk.PhotoImage(resized_image)
self.delete("all")
self.create_image(0, 0, anchor="nw", image=self.photo_image)
def _draw_pillow_pulse(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
alpha = (sin(self.angle * 5) + 1) / 2
r = int(alpha * (self.highlight_color_rgb[0] - self.color_rgb[0]) + self.color_rgb[0])
g = int(alpha * (self.highlight_color_rgb[1] - self.color_rgb[1]) + self.color_rgb[1])
b = int(alpha * (self.highlight_color_rgb[2] - self.color_rgb[2]) + self.color_rgb[2])
pulse_color = (r, g, b)
if self.animation_type == "line":
for i in range(12):
angle = i * (pi / 6)
start_x = center_x + cos(angle) * (self.width * 0.8)
start_y = center_y + sin(angle) * (self.height * 0.8)
end_x = center_x + cos(angle) * (self.width * 1.6)
end_y = center_y + sin(angle) * (self.height * 1.6)
self.draw.line([(start_x, start_y), (end_x, end_y)], fill=pulse_color, width=6, joint="curve")
elif self.animation_type == "double_arc":
radius = min(center_x, center_y) * 0.8
bbox = (center_x - radius, center_y - radius, center_x + radius, center_y + radius)
self.draw.arc(bbox, start=0, end=360, fill=pulse_color, width=5)
elif self.animation_type == "counter_arc":
radius_outer = min(center_x, center_y) * 0.8
bbox_outer = (center_x - radius_outer, center_y - radius_outer, center_x + radius_outer, center_y + radius_outer)
self.draw.arc(bbox_outer, start=0, end=360, fill=pulse_color, width=7)
radius_inner = min(center_x, center_y) * 0.6
bbox_inner = (center_x - radius_inner, center_y - radius_inner, center_x + radius_inner, center_y + radius_inner)
self.draw.arc(bbox_inner, start=0, end=360, fill=self.color_rgb, width=7)
def _draw_pillow_line(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
for i in range(12):
angle = self.angle + i * (pi / 6)
start_x = center_x + cos(angle) * (self.width * 0.8)
start_y = center_y + sin(angle) * (self.height * 0.8)
end_x = center_x + cos(angle) * (self.width * 1.6)
end_y = center_y + sin(angle) * (self.height * 1.6)
alpha = (cos(self.angle * 2.5 + i * (pi / 6)) + 1) / 2
r = int(alpha * (self.highlight_color_rgb[0] - self.color_rgb[0]) + self.color_rgb[0])
g = int(alpha * (self.highlight_color_rgb[1] - self.color_rgb[1]) + self.color_rgb[1])
b = int(alpha * (self.highlight_color_rgb[2] - self.color_rgb[2]) + self.color_rgb[2])
color = (r, g, b)
self.draw.line([(start_x, start_y), (end_x, end_y)], fill=color, width=6, joint="curve")
def _draw_pillow_double_arc(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
radius = min(center_x, center_y) * 0.8
bbox = (center_x - radius, center_y - radius, center_x + radius, center_y + radius)
start_angle1 = self.angle * 180 / pi
extent1 = 120 + 60 * sin(self.angle)
self.draw.arc(bbox, start=start_angle1, end=start_angle1 + extent1, fill=self.highlight_color_rgb, width=5)
start_angle2 = (self.angle + pi) * 180 / pi
extent2 = 120 + 60 * sin(self.angle + pi / 2)
self.draw.arc(bbox, start=start_angle2, end=start_angle2 + extent2, fill=self.color_rgb, width=5)
def _draw_pillow_counter_arc(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
radius_outer = min(center_x, center_y) * 0.8
bbox_outer = (center_x - radius_outer, center_y - radius_outer, center_x + radius_outer, center_y + radius_outer)
start_angle1 = self.angle * 180 / pi
self.draw.arc(bbox_outer, start=start_angle1, end=start_angle1 + 150, fill=self.highlight_color_rgb, width=7)
radius_inner = min(center_x, center_y) * 0.6
bbox_inner = (center_x - radius_inner, center_y - radius_inner, center_x + radius_inner, center_y + radius_inner)
start_angle2 = -self.angle * 180 / pi + 60
self.draw.arc(bbox_inner, start=start_angle2, end=start_angle2 + 150, fill=self.color_rgb, width=7)
def _draw_pillow_blink(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
radius = min(center_x, center_y) * 0.8
alpha = (sin(self.angle * 2) + 1) / 2
r = int(alpha * (self.highlight_color_rgb[0] - self.color_rgb[0]) + self.color_rgb[0])
g = int(alpha * (self.highlight_color_rgb[1] - self.color_rgb[1]) + self.color_rgb[1])
b = int(alpha * (self.highlight_color_rgb[2] - self.color_rgb[2]) + self.color_rgb[2])
blink_color = (r, g, b)
self.draw.arc((center_x - radius, center_y - radius, center_x + radius, center_y + radius), start=0, end=360, fill=blink_color, width=10)
def _draw_stopped_frame(self) -> None:
self.delete("all")
original_highlight_color = self.highlight_color
original_highlight_color_rgb = self.highlight_color_rgb
if self.is_disabled:
self.highlight_color = "#8f99aa"
self.highlight_color_rgb = _hex_to_rgb(self.highlight_color)
try:
if self.use_pillow:
self._draw_pillow_stopped_frame()
else:
self._draw_canvas_stopped_frame()
finally:
if self.is_disabled:
self.highlight_color = original_highlight_color
self.highlight_color_rgb = original_highlight_color_rgb
def _draw_canvas_stopped_frame(self) -> None:
if self.animation_type == "line":
self._draw_canvas_line_stopped()
elif self.animation_type == "double_arc":
self._draw_canvas_double_arc_stopped()
elif self.animation_type == "counter_arc":
self._draw_canvas_counter_arc_stopped()
elif self.animation_type == "blink":
self._draw_canvas_blink_stopped()
def _draw_canvas_line_stopped(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
for i in range(8):
angle = i * (pi / 4)
start_x = center_x + cos(angle) * (self.width * 0.2)
start_y = center_y + sin(angle) * (self.height * 0.2)
end_x = center_x + cos(angle) * (self.width * 0.4)
end_y = center_y + sin(angle) * (self.height * 0.4)
self.create_line(start_x, start_y, end_x, end_y, fill=self.highlight_color, width=2)
def _draw_canvas_double_arc_stopped(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
radius = min(center_x, center_y) * 0.8
bbox = (center_x - radius, center_y - radius, center_x + radius, center_y + radius)
self.create_arc(bbox, start=0, extent=359.9, style=tk.ARC, outline=self.highlight_color, width=2)
def _draw_canvas_counter_arc_stopped(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
radius_outer = min(center_x, center_y) * 0.8
bbox_outer = (center_x - radius_outer, center_y - radius_outer, center_x + radius_outer, center_y + radius_outer)
self.create_arc(bbox_outer, start=0, extent=359.9, style=tk.ARC, outline=self.highlight_color, width=2)
radius_inner = min(center_x, center_y) * 0.6
bbox_inner = (center_x - radius_inner, center_y - radius_inner, center_x + radius_inner, center_y + radius_inner)
self.create_arc(bbox_inner, start=0, extent=359.9, style=tk.ARC, outline=self.color, width=2)
def _draw_canvas_blink_stopped(self) -> None:
center_x, center_y = self.width / 2, self.height / 2
radius = min(center_x, center_y) * 0.8
self.create_arc(center_x - radius, center_y - radius, center_x + radius, center_y + radius, start=0, extent=359.9, style=tk.ARC, outline=self.highlight_color, width=4)
def _draw_pillow_stopped_frame(self) -> None:
self.draw.rectangle([0, 0, self.width * 4, self.height * 4], fill=(0, 0, 0, 0))
if self.animation_type == "line":
self._draw_pillow_line_stopped()
elif self.animation_type == "double_arc":
self._draw_pillow_double_arc_stopped()
elif self.animation_type == "counter_arc":
self._draw_pillow_counter_arc_stopped()
elif self.animation_type == "blink":
self._draw_pillow_blink_stopped()
resized_image = self.image.resize((self.width, self.height), Image.Resampling.LANCZOS)
self.photo_image = ImageTk.PhotoImage(resized_image)
self.create_image(0, 0, anchor="nw", image=self.photo_image)
def _draw_pillow_line_stopped(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
for i in range(12):
angle = i * (pi / 6)
start_x = center_x + cos(angle) * (self.width * 0.8)
start_y = center_y + sin(angle) * (self.height * 0.8)
end_x = center_x + cos(angle) * (self.width * 1.6)
end_y = center_y + sin(angle) * (self.height * 1.6)
self.draw.line([(start_x, start_y), (end_x, end_y)], fill=self.highlight_color_rgb, width=6, joint="curve")
def _draw_pillow_double_arc_stopped(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
radius = min(center_x, center_y) * 0.8
bbox = (center_x - radius, center_y - radius, center_x + radius, center_y + radius)
self.draw.arc(bbox, start=0, end=360, fill=self.highlight_color_rgb, width=5)
def _draw_pillow_counter_arc_stopped(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
radius_outer = min(center_x, center_y) * 0.8
bbox_outer = (center_x - radius_outer, center_y - radius_outer, center_x + radius_outer, center_y + radius_outer)
self.draw.arc(bbox_outer, start=0, end=360, fill=self.highlight_color_rgb, width=7)
radius_inner = min(center_x, center_y) * 0.6
bbox_inner = (center_x - radius_inner, center_y - radius_inner, center_x + radius_inner, center_y + radius_inner)
self.draw.arc(bbox_inner, start=0, end=360, fill=self.color_rgb, width=7)
def _draw_pillow_blink_stopped(self) -> None:
center_x, center_y = self.width * 2, self.height * 2
radius = min(center_x, center_y) * 0.8
self.draw.arc((center_x - radius, center_y - radius, center_x + radius, center_y + radius), start=0, end=360, fill=self.highlight_color_rgb, width=10)
def _animate(self) -> None:
"""The main animation loop."""
if self.pause_count > 0 or not self.running or not self.winfo_exists():
return
try:
toplevel = self.winfo_toplevel()
grab_widget = toplevel.grab_current()
if grab_widget is not None and grab_widget != toplevel:
self.after(100, self._animate)
return
except Exception:
self.after(30, self._animate)
return
self.angle += 0.1
if self.angle > 2 * pi:
self.angle -= 2 * pi
self._draw_frame()
self.after(30, self._animate)
def start(self, pulse: bool = False) -> None:
"""
Starts the animation.
Args:
pulse (bool): If True, plays a pulsing animation instead of the main one.
"""
if not self.winfo_exists():
return
self.running = True
self.is_disabled = False
self.pulse_animation = pulse
if self.pause_count == 0:
self._animate()
def stop(self, status: Optional[str] = None) -> None:
"""Stops the animation and shows the static 'stopped' frame."""
if not self.winfo_exists():
return
self.running = False
self.pulse_animation = False
self.is_disabled = status == "DISABLE"
self._draw_stopped_frame()
def hide(self) -> None:
"""Stops the animation and clears the canvas."""
if not self.winfo_exists():
return
self.running = False
self.pulse_animation = False
self.delete("all")
def pause(self) -> None:
"""Pauses the animation and draws a static frame."""
self.pause_count += 1
self._draw_stopped_frame()
def resume(self) -> None:
"""Resumes the animation if the pause count is zero."""
self.pause_count = max(0, self.pause_count - 1)
if self.pause_count == 0 and self.running:
self._animate()
def show_full_circle(self) -> None:
"""Shows the static 'stopped' frame without starting the animation."""
if not self.winfo_exists():
return
if not self.running:
self._draw_stopped_frame()

View File

@@ -289,6 +289,8 @@ class Msg:
"final_warning_system_restore_title": _("FINAL WARNING"),
"final_warning_system_restore_msg": _("ATTENTION: You are about to restore the system. This process cannot be safely interrupted. All changes since the backup will be lost. \n\nThe computer will automatically restart upon completion. \n\nREALLY PROCEED?"),
"btn_continue": _("PROCEED"),
"select_restore_source_title": _("Select Restore Source"),
"select_restore_destination_title": _("Select Restore Destination"),
# Lock Screen
"lock_title": _("System Restore in Progress"),

View File

@@ -1,865 +0,0 @@
" Classes Method and Functions for lx Apps "
import signal
import base64
from contextlib import contextmanager
from .logger import app_logger
from subprocess import CompletedProcess, run
import gettext
import locale
import re
import sys
import shutil
import tkinter as tk
from tkinter import ttk
import os
from typing import Optional, Dict, Any, NoReturn
from pathlib import Path
class CryptoUtil:
"""
This class is for the creation of the folders and files
required by Wire-Py, as well as for decryption
the tunnel from the user's home directory
"""
@staticmethod
def decrypt(user) -> None:
"""
Starts SSL dencrypt
"""
process: CompletedProcess[str] = run(
["pkexec", "/usr/local/bin/ssl_decrypt.py", "--user", user],
capture_output=True,
text=True,
check=False,
)
# Output from Openssl Error
if process.stderr:
app_logger.log(process.stderr)
if process.returncode == 0:
app_logger.log("Files successfully decrypted...")
else:
app_logger.log(
f"Error process decrypt: Code {process.returncode}"
)
@staticmethod
def encrypt(user) -> None:
"""
Starts SSL encryption
"""
process: CompletedProcess[str] = run(
["pkexec", "/usr/local/bin/ssl_encrypt.py", "--user", user],
capture_output=True,
text=True,
check=False,
)
# Output from Openssl Error
if process.stderr:
app_logger.log(process.stderr)
if process.returncode == 0:
app_logger.log("Files successfully encrypted...")
else:
app_logger.log(
f"Error process encrypt: Code {process.returncode}"
)
@staticmethod
def find_key(key: str = "") -> bool:
"""
Checks if the private key already exists in the system using an external script.
Returns True only if the full key is found exactly (no partial match).
"""
process: CompletedProcess[str] = run(
["pkexec", "/usr/local/bin/match_found.py", key],
capture_output=True,
text=True,
check=False,
)
if "True" in process.stdout:
return True
elif "False" in process.stdout:
return False
app_logger.log(
f"Unexpected output from the external script:\nSTDOUT: {process.stdout}\nSTDERR: {process.stderr}"
)
return False
@staticmethod
def is_valid_base64(key: str) -> bool:
"""
Validates if the input is a valid Base64 string (WireGuard private key format).
Returns True only for non-empty strings that match the expected length.
"""
# Check for empty string
if not key or key.strip() == "":
return False
# Regex pattern to validate Base64: [A-Za-z0-9+/]+={0,2}
base64_pattern = r"^[A-Za-z0-9+/]+={0,2}$"
if not re.match(base64_pattern, key):
return False
try:
# Decode and check length (WireGuard private keys are 32 bytes long)
decoded = base64.b64decode(key)
if len(decoded) != 32: # 32 bytes = 256 bits
return False
except Exception as e:
app_logger.log(f"Error on decode Base64: {e}")
return False
return True
class LxTools:
"""
Class LinuxTools methods that can also be used for other apps
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@staticmethod
def center_window_cross_platform(window, width, height):
"""
Centers a window on the primary monitor in a way that works on both X11 and Wayland
Args:
window: The tkinter window to center
width: Window width
height: Window height
"""
# Calculate the position before showing the window
# First attempt: Try to use GDK if available (works on both X11 and Wayland)
try:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
display = Gdk.Display.get_default()
monitor = display.get_primary_monitor() or display.get_monitor(0)
geometry = monitor.get_geometry()
scale_factor = monitor.get_scale_factor()
# Calculate center position on the primary monitor
x = geometry.x + (geometry.width - width // scale_factor) // 2
y = geometry.y + (geometry.height - height // scale_factor) // 2
# Set window geometry
window.geometry(f"{width}x{height}+{x}+{y}")
return
except (ImportError, AttributeError):
pass
# Second attempt: Try xrandr for X11
try:
import subprocess
output = subprocess.check_output(
["xrandr", "--query"], universal_newlines=True
)
# Parse the output to find the primary monitor
primary_info = None
for line in output.splitlines():
if "primary" in line:
parts = line.split()
for part in parts:
if "x" in part and "+" in part:
primary_info = part
break
break
if primary_info:
# Parse the geometry: WIDTH x HEIGHT+X+Y
geometry = primary_info.split("+")
dimensions = geometry[0].split("x")
primary_width = int(dimensions[0])
primary_height = int(dimensions[1])
primary_x = int(geometry[1])
primary_y = int(geometry[2])
# Calculate center position on the primary monitor
x = primary_x + (primary_width - width) // 2
y = primary_y + (primary_height - height) // 2
# Set window geometry
window.geometry(f"{width}x{height}+{x}+{y}")
return
except (ImportError, IndexError, ValueError):
pass
# Final fallback: Use standard Tkinter method
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# Try to make an educated guess for multi-monitor setups
# If screen width is much larger than height, assume multiple monitors side by side
if (
screen_width > screen_height * 1.8
): # Heuristic for detecting multiple monitors
# Assume the primary monitor is on the left half
screen_width = screen_width // 2
x = (screen_width - width) // 2
y = (screen_height - height) // 2
window.geometry(f"{width}x{height}+{x}+{y}")
@staticmethod
def clean_files(tmp_dir: Path = None, file: Path = None) -> None:
"""
Deletes temporary files and directories for cleanup when exiting the application.
This method safely removes an optional directory defined by `AppConfig.TEMP_DIR`
and a single file to free up resources at the end of the program's execution.
All operations are performed securely, and errors such as `FileNotFoundError`
are ignored if the target files or directories do not exist.
:param tmp_dir: (Path, optional): Path to the temporary directory that should be deleted.
If `None`, the value of `AppConfig.TEMP_DIR` is used.
:param file: (Path, optional): Path to the file that should be deleted.
If `None`, no additional file will be deleted.
Returns:
None: The method does not return any value.
"""
if tmp_dir is not None:
shutil.rmtree(tmp_dir, ignore_errors=True)
try:
if file is not None:
Path.unlink(file)
except FileNotFoundError:
pass
@staticmethod
def sigi(file_path: Optional[Path] = None, file: Optional[Path] = None) -> None:
"""
Function for cleanup after a program interruption
:param file: Optional - File to be deleted
:param file_path: Optional - Directory to be deleted
"""
def signal_handler(signum: int, frame: Any) -> NoReturn:
"""
Determines clear text names for signal numbers and handles signals
Args:
signum: The signal number
frame: The current stack frame
Returns:
NoReturn since the function either exits the program or continues execution
"""
signals_to_names_dict: Dict[int, str] = dict(
(getattr(signal, n), n)
for n in dir(signal)
if n.startswith("SIG") and "_" not in n
)
signal_name: str = signals_to_names_dict.get(
signum, f"Unnamed signal: {signum}"
)
# End program for certain signals, report to others only reception
if signum in (signal.SIGINT, signal.SIGTERM):
exit_code: int = 1
app_logger.log(
f"\nSignal {signal_name} {signum} received. => Aborting with exit code {exit_code}."
)
LxTools.clean_files(file_path, file)
app_logger.log("Breakdown by user...")
sys.exit(exit_code)
else:
app_logger.log(f"Signal {signum} received and ignored.")
LxTools.clean_files(file_path, file)
app_logger.log("Process unexpectedly ended...")
# Register signal handlers for various signals
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGHUP, signal_handler)
# ConfigManager with caching
class ConfigManager:
"""
Universal class for managing configuration files with caching support.
This class provides a general solution to load, save, and manage configuration
files across different projects. It uses a caching system to optimize access efficiency.
The `init()` method initializes the configuration file path, while `load()` and `save()`
synchronize data between the file and internal memory structures.
Key Features:
- Caching to minimize I/O operations.
- Default values for missing or corrupted configuration files.
- Reusability across different projects and use cases.
The class is designed for central application configuration management, working closely
with `ThemeManager` to dynamically manage themes or other settings.
"""
_config = None
_config_file = None
@classmethod
def init(cls, config_file):
"""Initial the Configmanager with the given config file"""
cls._config_file = config_file
cls._config = None # Reset the cache
@classmethod
def load(cls):
"""Load the config file and return the config as dict"""
if not cls._config:
try:
lines = Path(cls._config_file).read_text(
encoding="utf-8").splitlines()
cls._config = {
"updates": lines[1].strip(),
"theme": lines[3].strip(),
"tooltips": lines[5].strip()
== "True", # is converted here to boolean!!!
"autostart": lines[7].strip() if len(lines) > 7 else "off",
}
except (IndexError, FileNotFoundError):
# DeDefault values in case of error
cls._config = {
"updates": "on",
"theme": "light",
"tooltips": "True", # Default Value as string!
"autostart": "off",
}
return cls._config
@classmethod
def save(cls):
"""Save the config to the config file"""
if cls._config:
lines = [
"# Configuration\n",
f"{cls._config['updates']}\n",
"# Theme\n",
f"{cls._config['theme']}\n",
"# Tooltips\n",
f"{str(cls._config['tooltips'])}\n",
"# Autostart\n",
f"{cls._config['autostart']}\n",
]
Path(cls._config_file).write_text("".join(lines), encoding="utf-8")
@classmethod
def set(cls, key, value):
"""Sets a configuration value and saves the change"""
cls.load()
cls._config[key] = value
cls.save()
@classmethod
def get(cls, key, default=None):
"""Returns a configuration value"""
config = cls.load()
return config.get(key, default)
class ThemeManager:
"""
Class for central theme management and UI customization.
This static class allows dynamic adjustment of the application's appearance.
The method `change_theme()` updates the current theme and saves
the selection in the configuration file via `ConfigManager`.
It ensures a consistent visual design across the entire project.
Key Features:
- Central control over themes.
- Automatic saving of theme settings to the configuration file.
- Tight integration with `ConfigManager` for persistent storage of preferences.
The class is designed to apply themes consistently throughout the application,
ensuring that changes are traceable and uniform across all parts of the project.
"""
@staticmethod
def change_theme(root, theme_in_use, theme_name=None):
"""
Change application theme centrally.
Args:
root: The root Tkinter window.
theme_in_use (str): The name of the theme to apply.
theme_name (Optional[str]): The name of the theme to save in the config.
If None, the theme is not saved.
"""
root.tk.call("set_theme", theme_in_use)
if theme_in_use == theme_name:
ConfigManager.set("theme", theme_in_use)
class Tooltip:
"""
A flexible tooltip class for Tkinter widgets that supports dynamic activation/deactivation.
This class provides customizable tooltips that appear when the mouse hovers over a widget.
It can be used for simple, always-active tooltips or for tooltips whose visibility is
controlled by a `tk.BooleanVar`, allowing for global enable/disable functionality.
Attributes:
widget (tk.Widget): The Tkinter widget to which the tooltip is attached.
text (str): The text to display in the tooltip.
wraplength (int): The maximum line length for the tooltip text before wrapping.
state_var (Optional[tk.BooleanVar]): An optional Tkinter BooleanVar that controls
the visibility of the tooltip. If True, the tooltip
is active; if False, it is inactive. If None, the
tooltip is always active.
tooltip_window (Optional[tk.Toplevel]): The Toplevel window used to display the tooltip.
id (Optional[str]): The ID of the `after` job used to schedule the tooltip display.
Usage Examples:
# 1. Simple Tooltip (always active):
# Tooltip(my_button, "This is a simple tooltip.")
# 2. State-Controlled Tooltip (can be enabled/disabled globally):
# tooltip_state = tk.BooleanVar(value=True)
# Tooltip(my_button, "This tooltip can be turned off!", state_var=tooltip_state)
# # To toggle visibility:
# # tooltip_state.set(False) # Tooltips will hide
# # tooltip_state.set(True) # Tooltips will show again
"""
def __init__(self, widget, text, wraplength=250, state_var=None):
self.widget = widget
self.text = text
self.wraplength = wraplength
self.state_var = state_var
self.tooltip_window = None
self.id = None
self.update_bindings()
if self.state_var:
self.state_var.trace_add("write", self.update_bindings)
# Add bindings to the top-level window to hide the tooltip when the
# main window loses focus or is iconified.
toplevel = self.widget.winfo_toplevel()
toplevel.bind("<FocusOut>", self.leave, add="+")
toplevel.bind("<Unmap>", self.leave, add="+")
def update_bindings(self, *args):
"""
Updates the event bindings for the widget based on the current state_var.
If state_var is True or None, the <Enter>, <Leave>, and <ButtonPress> events
are bound to show/hide the tooltip. Otherwise, they are unbound.
"""
self.widget.unbind("<Enter>")
self.widget.unbind("<Leave>")
self.widget.unbind("<ButtonPress>")
if self.state_var is None or self.state_var.get():
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
def enter(self, event=None):
"""
Handles the <Enter> event. Schedules the tooltip to be shown after a delay
if tooltips are enabled (via state_var).
"""
# Do not show tooltips if a grab is active on a different window.
# This prevents tooltips from appearing over other modal dialogs.
toplevel = self.widget.winfo_toplevel()
grab_widget = toplevel.grab_current()
if grab_widget is not None and grab_widget != toplevel:
return
if self.state_var is None or self.state_var.get():
self.schedule()
def leave(self, event=None):
"""
Handles the <Leave> event. Unschedules any pending tooltip display
and immediately hides any visible tooltip.
"""
self.unschedule()
self.hide_tooltip()
def schedule(self):
"""
Schedules the `show_tooltip` method to be called after a short delay.
Cancels any previously scheduled calls to prevent flickering.
"""
self.unschedule()
self.id = self.widget.after(250, self.show_tooltip)
def unschedule(self):
"""
Cancels any pending `show_tooltip` calls.
"""
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def show_tooltip(self, event=None):
"""
Displays the tooltip window. The tooltip is a Toplevel window containing a ttk.Label.
It is positioned near the widget and styled for readability.
"""
if self.tooltip_window:
return
text_to_show = self.text() if callable(self.text) else self.text
if not text_to_show:
return
try:
# Position the tooltip just below the widget.
# Using winfo_rootx/y is more reliable than bbox.
x = self.widget.winfo_rootx()
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 5
except tk.TclError:
# This can happen if the widget is destroyed while the tooltip is scheduled.
return
self.tooltip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+" + str(x) + "+" + str(y))
label = ttk.Label(tw, text=text_to_show, justify=tk.LEFT, background="#FFFFE0", foreground="black",
relief=tk.SOLID, borderwidth=1, wraplength=self.wraplength, padding=(4, 2, 4, 2))
label.pack(ipadx=1)
def hide_tooltip(self):
"""
Hides and destroys the tooltip window if it is currently visible.
"""
tw = self.tooltip_window
self.tooltip_window = None
if tw:
tw.destroy()
class LogConfig:
"""
A static class for configuring application-wide logging.
This class provides a convenient way to set up file-based logging for the application.
It ensures that log messages are written to a specified file with a consistent format.
Methods:
logger(file_path: str) -> None:
Configures the root logger to write messages to the specified file.
Usage Example:
# Assuming LOG_FILE_PATH is defined elsewhere (e.g., in a config file)
# LogConfig.logger(LOG_FILE_PATH)
# logging.info("This message will be written to the log file.")
"""
@staticmethod
def logger(file_path) -> None:
"""
Configures the root logger to write messages to the specified file.
Args:
file_path (str): The absolute path to the log file.
"""
file_handler = logging.FileHandler(
filename=f"{file_path}",
mode="a",
encoding="utf-8",
)
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # Set the root logger level
logger.addHandler(file_handler)
class IconManager:
"""
A class for central management and loading of application icons.
This class loads Tkinter PhotoImage objects from a specified base path,
organizing them by logical names and providing a convenient way to retrieve them.
It handles potential errors during image loading by creating a blank image placeholder.
Attributes:
base_path (str): The base directory where icon subfolders (e.g., '16', '32', '48', '64') are located.
icons (Dict[str, tk.PhotoImage]): A dictionary storing loaded PhotoImage objects,
keyed by their logical names (e.g., 'computer_small', 'folder_large').
Methods:
get_icon(name: str) -> Optional[tk.PhotoImage]:
Retrieves a loaded icon by its logical name.
Usage Example:
# Initialize the IconManager with the path to your icon directory
# icon_manager = IconManager(base_path="/usr/share/icons/lx-icons/")
# Retrieve an icon
# computer_icon = icon_manager.get_icon("computer_small")
# if computer_icon:
# my_label = tk.Label(root, image=computer_icon)
# my_label.pack()
"""
def __init__(self, base_path='/usr/share/icons/lx-icons/'):
self.base_path = base_path
self.icons = {}
self._define_icon_paths()
self._load_all()
def _define_icon_paths(self):
self.icon_paths = {
# 16x16
'settings_16': '16/settings.png',
# 32x32
'back': '32/arrow-left.png',
'forward': '32/arrow-right.png',
'up': '32/arrow-up.png',
'copy': '32/copy.png',
'stair': '32/stair.png',
'star': '32/star.png',
'connect': '32/connect.png',
'audio_small': '32/audio.png',
'icon_view': '32/carrel.png',
'computer_small': '32/computer.png',
'device_small': '32/device.png',
'file_small': '32/document.png',
'download_error_small': '32/download_error.png',
'download_small': '32/download.png',
'error_small': '32/error.png',
'python_small': '32/file-python.png',
'documents_small': '32/folder-water-documents.png',
'downloads_small': '32/folder-water-download.png',
'music_small': '32/folder-water-music.png',
'pictures_small': '32/folder-water-pictures.png',
'folder_small': '32/folder-water.png',
'video_small': '32/folder-water-video.png',
'hide': '32/hide.png',
'home': '32/home.png',
'about': '32/about.png',
'info_small': '32/info.png',
'light_small': '32/light.png',
'dark_small': '32/dark.png',
'update_small': '32/update.png',
'no_update_small': '32/no_update.png',
'tooltip_small': '32/tip.png',
'no_tooltip_small': '32/no_tip.png',
'list_view': '32/list.png',
'log_small': '32/log.png',
'log_blue_small': '32/log_blue.png',
'lunix_tools_small': '32/Lunix_Tools.png',
'key_small': '32/lxtools_key.png',
'fork_key_small': '32/fork_key.png',
'iso_small': '32/media-optical.png',
'new_document_small': '32/new-document.png',
'new_folder_small': '32/new-folder.png',
'pdf_small': '32/pdf.png',
'picture_small': '32/picture.png',
'question_mark_small': '32/question_mark.png',
'recursive_small': '32/recursive.png',
'search_small': '32/search.png',
'settings_small': '32/settings.png',
'settings-2_small': '32/settings-2.png',
'archive_small': '32/tar.png',
'unhide': '32/unhide.png',
'usb_small': '32/usb.png',
'video_small_file': '32/video.png',
'warning_small': '32/warning.png',
'export_small': '32/wg_export.png',
'import_small': '32/wg_import.png',
'message_small': '32/wg_msg.png',
'trash_small': '32/wg_trash.png',
'trash_small2': '32/trash.png',
'vpn_small': '32/wg_vpn.png',
'vpn_start_small': '32/wg_vpn-start.png',
'vpn_stop_small': '32/wg_vpn-stop.png',
'hdd_small': '32/hdd.png',
# 48x48
'back_large': '48/arrow-left.png',
'forward_large': '48/arrow-right.png',
'up_large': '48/arrow-up.png',
'copy_large': '48/copy.png',
'stair_large': '48/stair.png',
'star_large': '48/star.png',
'connect_large': '48/connect.png',
'icon_view_large': '48/carrel.png',
'computer_large': '48/computer.png',
'device_large': '48/device.png',
'download_error_large': '48/download_error.png',
'download_large': '48/download.png',
'error_large': '48/error.png',
'documents_large': '48/folder-water-documents.png',
'downloads_large': '48/folder-water-download.png',
'music_large': '48/folder-water-music.png',
'pictures_large': '48/folder-water-pictures.png',
'folder_large_48': '48/folder-water.png',
'video_large_folder': '48/folder-water-video.png',
'hide_large': '48/hide.png',
'home_large': '48/home.png',
'info_large': '48/info.png',
'light_large': '48/light.png',
'dark_large': '48/dark.png',
'update_large': '48/update.png',
'no_update_large': '48/no_update.png',
'tooltip_large': '48/tip.png',
'no_tooltip_large': '48/no_tip.png',
'about_large': '48/about.png',
'list_view_large': '48/list.png',
'log_large': '48/log.png',
'log_blue_large': '48/log_blue.png',
'lunix_tools_large': '48/Lunix_Tools.png',
'fork_key_large': '48/fork_key.png',
'new_document_large': '48/new-document.png',
'new_folder_large': '48/new-folder.png',
'question_mark_large': '48/question_mark.png',
'search_large_48': '48/search.png',
'settings_large': '48/settings.png',
'unhide_large': '48/unhide.png',
'usb_large': '48/usb.png',
'warning_large_48': '48/warning.png',
'export_large': '48/wg_export.png',
'import_large': '48/wg_import.png',
'message_large': '48/wg_msg.png',
'trash_large': '48/wg_trash.png',
'trash_large2': '48/trash.png',
'vpn_large': '48/wg_vpn.png',
'vpn_start_large': '48/wg_vpn-start.png',
'vpn_stop_large': '48/wg_vpn-stop.png',
'hdd_large': '48/hdd.png',
# 64x64
'back_extralarge': '64/arrow-left.png',
'forward_extralarge': '64/arrow-right.png',
'up_extralarge': '64/arrow-up.png',
'copy_extralarge': '64/copy.png',
'stair_extralarge': '64/stair.png',
'star_extralarge': '64/star.png',
'connect_extralarge': '64/connect.png',
'audio_large': '64/audio.png',
'icon_view_extralarge': '64/carrel.png',
'computer_extralarge': '64/computer.png',
'device_extralarge': '64/device.png',
'file_large': '64/document.png',
'lx_backup_large': '64/lx_backup.png',
'download_error_extralarge': '64/download_error.png',
'download_extralarge': '64/download.png',
'error_extralarge': '64/error.png',
'python_large': '64/file-python.png',
'documents_extralarge': '64/folder-water-documents.png',
'downloads_extralarge': '64/folder-water-download.png',
'music_extralarge': '64/folder-water-music.png',
'pictures_extralarge': '64/folder-water-pictures.png',
'folder_large': '64/folder-water.png',
'video_extralarge_folder': '64/folder-water-video.png',
'hide_extralarge': '64/hide.png',
'home_extralarge': '64/home.png',
'info_extralarge': '64/info.png',
'light_extralarge': '64/light.png',
'dark_extralarge': '64/dark.png',
'update_extralarge': '64/update.png',
'no_update_extralarge': '64/no_update.png',
'tooltip_extralarge': '64/tip.png',
'no_tooltip_extralarge': '64/no_tip.png',
'about_extralarge': '64/about.png',
'list_view_extralarge': '64/list.png',
'log_extralarge': '64/log.png',
'log_blue_extralarge': '64/log_blue.png',
'lunix_tools_extralarge': '64/Lunix_Tools.png',
'fork_key_extralarge': '64/fork_key.png',
'iso_large': '64/media-optical.png',
'new_document_extralarge': '64/new-document.png',
'new_folder_extralarge': '64/new-folder.png',
'pdf_large': '64/pdf.png',
'picture_large': '64/picture.png',
'question_mark_extralarge': '64/question_mark.png',
'recursive_large': '64/recursive.png',
'search_large': '64/search.png',
'settings_extralarge': '64/settings.png',
'archive_large': '64/tar.png',
'unhide_extralarge': '64/unhide.png',
'usb_extralarge': '64/usb.png',
'video_large': '64/video.png',
'warning_large': '64/warning.png',
'export_extralarge': '64/wg_export.png',
'import_extralarge': '64/wg_import.png',
'message_extralarge': '64/wg_msg.png',
'trash_extralarge': '64/wg_trash.png',
'trash_extralarge2': '64/trash.png',
'vpn_extralarge': '64/wg_vpn.png',
'vpn_start_extralarge': '64/wg_vpn-start.png',
'vpn_stop_extralarge': '64/wg_vpn-stop.png',
'hdd_extralarge': '64/hdd.png',
}
def _load_all(self):
for key, rel_path in self.icon_paths.items():
full_path = os.path.join(self.base_path, rel_path)
try:
self.icons[key] = tk.PhotoImage(file=full_path)
except tk.TclError as e:
print(f"Error loading icon '{key}' from '{full_path}': {e}")
size = 32 # Default size
if '16' in rel_path:
size = 16
elif '48' in rel_path:
size = 48
elif '64' in rel_path:
size = 64
self.icons[key] = tk.PhotoImage(width=size, height=size)
def get_icon(self, name):
return self.icons.get(name)
class Translate:
@staticmethod
def setup_translations(app_name: str, locale_dir="/usr/share/locale/") -> gettext.gettext:
"""
Initialize translations and set the translation function
Special method for translating strings in this file
Returns:
The gettext translation function
"""
locale.bindtextdomain(app_name, locale_dir)
gettext.bindtextdomain(app_name, locale_dir)
gettext.textdomain(app_name)
return gettext.gettext
@contextmanager
def message_box_animation(animated_icon):
"""
A context manager to handle pausing and resuming an animated icon
around an operation like showing a message box.
Args:
animated_icon: The animated icon object with pause() and resume() methods.
"""
if animated_icon:
animated_icon.pause()
try:
yield
finally:
if animated_icon:
animated_icon.resume()

View File

@@ -6,6 +6,7 @@ import re
from app_config import AppConfig
from shared_libs.logger import app_logger
class DataProcessing:
def __init__(self, app):
self.app = app
@@ -15,22 +16,28 @@ class DataProcessing:
try:
if AppConfig.GENERATED_EXCLUDE_LIST_PATH.exists():
with open(AppConfig.GENERATED_EXCLUDE_LIST_PATH, 'r') as f:
generated_patterns = [line.strip() for line in f if line.strip() and not line.startswith('#')]
generated_patterns = [
line.strip() for line in f if line.strip() and not line.startswith('#')]
all_patterns.update(generated_patterns)
app_logger.log(f"Loaded generated exclusion patterns: {generated_patterns}")
app_logger.log(
f"Loaded generated exclusion patterns: {generated_patterns}")
except FileNotFoundError:
app_logger.log(f"Generated exclusion list not found: {AppConfig.GENERATED_EXCLUDE_LIST_PATH}")
app_logger.log(
f"Generated exclusion list not found: {AppConfig.GENERATED_EXCLUDE_LIST_PATH}")
except IOError as e:
app_logger.log(f"Error loading generated exclusion list: {e}")
try:
if AppConfig.USER_EXCLUDE_LIST_PATH.exists():
with open(AppConfig.USER_EXCLUDE_LIST_PATH, 'r') as f:
user_patterns = [line.strip() for line in f if line.strip() and not line.startswith('#')]
user_patterns = [
line.strip() for line in f if line.strip() and not line.startswith('#')]
all_patterns.update(user_patterns)
app_logger.log(f"Loaded user-defined exclusion patterns: {user_patterns}")
app_logger.log(
f"Loaded user-defined exclusion patterns: {user_patterns}")
except FileNotFoundError:
app_logger.log(f"User-defined exclusion list not found: {AppConfig.USER_EXCLUDE_LIST_PATH}")
app_logger.log(
f"User-defined exclusion list not found: {AppConfig.USER_EXCLUDE_LIST_PATH}")
except IOError as e:
app_logger.log(f"Error loading user-defined exclusion list: {e}")
@@ -45,7 +52,8 @@ class DataProcessing:
# Compile exclude patterns into a single regex for performance
if exclude_patterns:
exclude_regex = re.compile('|'.join(fnmatch.translate(p) for p in exclude_patterns))
exclude_regex = re.compile(
'|'.join(fnmatch.translate(p) for p in exclude_patterns))
else:
exclude_regex = None
@@ -54,7 +62,8 @@ class DataProcessing:
return # Stop the calculation
if exclude_regex:
dirnames[:] = [d for d in dirnames if not exclude_regex.match(os.path.join(dirpath, d))]
dirnames[:] = [d for d in dirnames if not exclude_regex.match(
os.path.join(dirpath, d))]
for f in filenames:
if stop_event.is_set():
@@ -67,7 +76,7 @@ class DataProcessing:
total_size += os.path.getsize(fp)
except OSError:
pass
if not stop_event.is_set():
self.app.queue.put((button_text, total_size))

View File

@@ -9,7 +9,7 @@ from shared_libs.animated_icon import AnimatedIcon
from shared_libs.common_tools import IconManager
from config_manager import ConfigManager
from backup_manager import BackupManager
from app_config import AppConfig, Msg
from app_config import AppConfig, Msg, _
from pyimage_ui.scheduler_frame import SchedulerFrame
from pyimage_ui.backup_content_frame import BackupContentFrame
from pyimage_ui.header_frame import HeaderFrame
@@ -38,7 +38,6 @@ class MainApplication(tk.Tk):
self.style.layout("Sidebar.TButton", self.style.layout(
"SidebarHover.TButton.Borderless.Round"))
# Configure the active state directly for the base style
self.style.map("Toolbutton", background=[
("active", "#000000")], foreground=[("active", "black")])
@@ -46,7 +45,6 @@ class MainApplication(tk.Tk):
self.style.layout("Toolbutton"))
self.style.configure("Gray.Toolbutton", foreground="gray")
# --- Main Layout ---
main_frame = ttk.Frame(self)
main_frame.grid(row=0, column=0, sticky="nsew")
self.grid_rowconfigure(0, weight=1)
@@ -69,7 +67,6 @@ class MainApplication(tk.Tk):
self.content_frame.grid_rowconfigure(6, weight=0)
self.content_frame.grid_columnconfigure(0, weight=1)
# --- Initialize Backend ---
self.backup_manager = BackupManager(app_logger)
self.queue = Queue()
self.image_manager = IconManager()
@@ -89,9 +86,14 @@ class MainApplication(tk.Tk):
self.source_size_bytes = 0
self.destination_used_bytes = 0
self.destination_total_bytes = 0
self.backup_left_canvas_data = {}
self.backup_right_canvas_data = {}
self.restore_left_canvas_data = {}
self.restore_right_canvas_data = {}
self.left_canvas_data = {}
self.right_canvas_data = {}
# Try to set icon
try:
lx_backup_icon = self.image_manager.get_icon('lx_backup_large')
if lx_backup_icon:
@@ -99,11 +101,9 @@ class MainApplication(tk.Tk):
except Exception:
pass
# --- Sidebar ---
# Add the lx_backup_large icon
lx_backup_label = ttk.Label(
sidebar, image=lx_backup_icon, background="#2b3e4f")
lx_backup_label.image = lx_backup_icon # Keep a reference
lx_backup_label.image = lx_backup_icon
lx_backup_label.pack(pady=10)
sidebar_buttons_frame = ttk.Frame(sidebar, style="Custom.TFrame")
@@ -130,11 +130,9 @@ class MainApplication(tk.Tk):
sidebar_buttons_frame, text=Msg.STR["settings"], command=lambda: self.navigation.toggle_settings_frame(4), style="Sidebar.TButton")
settings_button.pack(fill=tk.X, pady=10)
# --- Header ---
self.header_frame = HeaderFrame(self.content_frame, self.image_manager)
self.header_frame.grid(row=0, column=0, sticky="nsew")
# --- Main Content ---
self.top_bar = ttk.Frame(self.content_frame)
self.top_bar.grid(row=1, column=0, sticky="ew", pady=10)
@@ -202,12 +200,6 @@ class MainApplication(tk.Tk):
self.right_canvas.bind(
"<Button-1>", self.actions.on_right_canvas_click)
self.right_canvas_data = {
'icon': 'hdd_extralarge',
'folder': Msg.STR["select_destination"],
'size': ''
}
self._setup_log_window()
self._setup_scheduler_frame()
self._setup_settings_frame()
@@ -251,24 +243,62 @@ class MainApplication(tk.Tk):
target_label_frame, text="0.00 GB / 0.00 GB")
self.target_size_label.pack(side=tk.RIGHT)
self.mode = "backup"
last_mode = self.config_manager.get_setting("last_mode")
if last_mode in ["backup", "restore"]:
self.mode = last_mode
self._load_state_and_initialize()
self.protocol("WM_DELETE_WINDOW", self.on_closing)
if self.mode == "restore":
self.navigation.toggle_mode(
"restore", 1, trigger_calculation=False)
def _load_state_and_initialize(self):
"""Loads saved state from config and initializes the UI."""
last_mode = self.config_manager.get_setting("last_mode", "backup")
# Pre-load data from config before initializing the UI
backup_dest_path = self.config_manager.get_setting("backup_destination_path")
if backup_dest_path and os.path.isdir(backup_dest_path):
self.destination_path = backup_dest_path # Still needed for some logic
total, used, free = shutil.disk_usage(backup_dest_path)
self.backup_right_canvas_data.update({
'folder': os.path.basename(backup_dest_path.rstrip('/')),
'path_display': backup_dest_path,
'size': f"{used / (1024**3):.2f} GB / {total / (1024**3):.2f} GB"
})
self.destination_total_bytes = total
self.destination_used_bytes = used
restore_src_path = self.config_manager.get_setting("restore_source_path")
if restore_src_path and os.path.isdir(restore_src_path):
self.restore_right_canvas_data.update({
'folder': os.path.basename(restore_src_path.rstrip('/')),
'path_display': restore_src_path,
})
restore_dest_path = self.config_manager.get_setting("restore_destination_path")
if restore_dest_path and os.path.isdir(restore_dest_path):
# Find the corresponding button_text for the path
folder_name = ""
for name, path_obj in AppConfig.FOLDER_PATHS.items():
if str(path_obj) == restore_dest_path:
folder_name = name
break
if folder_name:
self.restore_left_canvas_data.update({
'icon': self.buttons_map[folder_name]['icon'],
'folder': folder_name,
'path_display': restore_dest_path,
})
# Initialize UI for the last active mode
self.navigation.initialize_ui_for_mode(last_mode)
# Trigger calculations if needed
if last_mode == 'backup' and backup_dest_path:
self.after(100, self.actions.on_sidebar_button_click, self.backup_left_canvas_data.get('folder', 'Computer'))
elif last_mode == 'restore' and restore_src_path:
self.drawing.calculate_restore_folder_size()
else:
self.navigation.toggle_mode("backup", 0, trigger_calculation=False)
# Default action if no specific state to restore
self.after(100, self.actions.on_sidebar_button_click, "Computer")
self.after(100, self.actions.on_sidebar_button_click, "Computer")
self.data_processing.process_queue()
last_dest = self.config_manager.get_setting("last_destination")
if last_dest and os.path.isdir(last_dest):
self.actions._update_destination_info(last_dest)
def _setup_log_window(self):
self.log_frame = ttk.Frame(self.content_frame)
self.log_window = LogWindow(self.log_frame)
@@ -312,10 +342,8 @@ class MainApplication(tk.Tk):
self.action_frame = ttk.Frame(self.content_frame, padding=10)
self.action_frame.grid(row=6, column=0, sticky="ew")
# Explicitly get the theme's background color for the canvas
bg_color = self.style.lookup('TFrame', 'background')
# Get the animation type from settings, with a default
backup_animation_type = self.config_manager.get_setting(
"backup_animation_type", "counter_arc")
@@ -337,14 +365,37 @@ class MainApplication(tk.Tk):
self.action_frame, text=Msg.STR["start"], command=self.actions.toggle_start_pause, state="disabled")
self.start_pause_button.pack(side=tk.RIGHT, padx=5)
def quit(self):
def on_closing(self):
"""Handles window closing events and saves the app state."""
self.config_manager.set_setting("last_mode", self.mode)
# Save paths from the data dictionaries
if self.backup_right_canvas_data.get('path_display'):
self.config_manager.set_setting("backup_destination_path", self.backup_right_canvas_data['path_display'])
else:
self.config_manager.set_setting("backup_destination_path", None)
if self.restore_left_canvas_data.get('path_display'):
self.config_manager.set_setting("restore_destination_path", self.restore_left_canvas_data['path_display'])
else:
self.config_manager.set_setting("restore_destination_path", None)
if self.restore_right_canvas_data.get('path_display'):
self.config_manager.set_setting("restore_source_path", self.restore_right_canvas_data['path_display'])
else:
self.config_manager.set_setting("restore_source_path", None)
app_logger.log(Msg.STR["app_quit"])
self.destroy()
def quit(self):
self.on_closing()
if __name__ == "__main__":
import argparse
import sys
import shutil
parser = argparse.ArgumentParser(description="Py-Backup Application.")
parser.add_argument(
@@ -359,7 +410,6 @@ if __name__ == "__main__":
args = parser.parse_args()
if args.backup_type and args.destination:
s
from shared_libs.logger import app_logger as cli_logger
backup_manager = BackupManager(cli_logger)
@@ -378,4 +428,4 @@ if __name__ == "__main__":
else:
app = MainApplication()
app.mainloop()
app.mainloop()

View File

@@ -1,34 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN" "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<!--
Policy definitions for ssl_encrypt and ssl_decrypt
Copyright (C) 2025 Désiré Werner Menrath <polunga40@unity-mail.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see
<http://www.gnu.org/licenses/>.
-->
<policyconfig>
<action id="org.pybackup">
<defaults>
<allow_any>auth_admin_keep</allow_any>
<allow_inactive>auth_admin_keep</allow_inactive>
<allow_active>yes</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.exec.path">/usr/local/bin/pybackup.py</annotate>
</action>
</policyconfig>

View File

@@ -7,7 +7,7 @@ from typing import Optional
from shared_libs.message import MessageDialog
from shared_libs.custom_file_dialog import CustomFileDialog
from app_config import AppConfig, Msg
from app_config import AppConfig, Msg, _
from shared_libs.logger import app_logger
from shared_libs.animated_icon import AnimatedIcon
from shared_libs.common_tools import message_box_animation
@@ -26,143 +26,133 @@ class Actions:
else:
self.app.is_first_backup = False
def on_sidebar_button_click(self, button_text):
if not self.app.canvas_frame.winfo_viewable():
self.app.navigation.toggle_mode(self.app.mode, trigger_calculation=False)
self.app.log_window.clear_log()
if not self.app.destination_path:
# Do not calculate size if no destination is selected
folder_path = AppConfig.FOLDER_PATHS.get(button_text)
if not folder_path or not folder_path.exists():
print(f"Folder not found for {button_text}")
return
icon_name = self.app.buttons_map[button_text]['icon']
extra_info = ""
if button_text == "Computer":
extra_info = Msg.STR["system_backup_info"]
self.app.left_canvas_data = {
'icon': icon_name,
'folder': button_text,
'path_display': str(folder_path),
'size': Msg.STR["select_destination_first"],
'calculating': False,
'extra_info': extra_info
}
self.app.drawing.redraw_left_canvas()
return
folder_path = AppConfig.FOLDER_PATHS.get(button_text)
if not folder_path or not folder_path.exists():
print(f"Folder not found for {button_text}")
return
if self.app.calculation_thread and self.app.calculation_thread.is_alive():
self.app.calculation_stop_event.set()
if self.app.calculating_animation:
self.app.calculating_animation.stop()
self.app.calculating_animation.destroy()
self.app.calculating_animation = None
icon_name = self.app.buttons_map[button_text]['icon']
extra_info = ""
if button_text == "Computer":
extra_info = Msg.STR["system_backup_info"]
self.app.left_canvas_data = {
# Unified logic for starting a calculation on the left canvas
self._start_left_canvas_calculation(button_text, str(folder_path), icon_name, extra_info)
def _start_left_canvas_calculation(self, button_text, folder_path, icon_name, extra_info):
if self.app.mode == 'backup' and not self.app.destination_path:
self.app.left_canvas_data.update({
'icon': icon_name,
'folder': button_text,
'path_display': folder_path,
'size': Msg.STR["select_destination_first"],
'calculating': False,
'extra_info': extra_info
})
self.app.drawing.redraw_left_canvas()
return
if self.app.calculation_thread and self.app.calculation_thread.is_alive():
self.app.calculation_stop_event.set()
data_dict = self.app.left_canvas_data
data_dict.update({
'icon': icon_name,
'folder': button_text,
'path_display': str(folder_path),
'size': Msg.STR["calculating_size"],
'path_display': folder_path,
'size': Msg.STR["calculating_size"],
'calculating': True,
'extra_info': extra_info
}
self.app.drawing.redraw_left_canvas()
})
# Get the animation type from settings, with a default
animation_type = self.app.config_manager.get_setting("calculation_animation_type", "double_arc")
if self.app.calculating_animation:
self.app.calculating_animation.destroy()
self.app.calculating_animation = AnimatedIcon(
self.app.left_canvas, width=20, height=20, animation_type=animation_type, use_pillow=True)
self.app.calculating_animation.start()
self.app.drawing.redraw_left_canvas()
self.app.drawing.start_backup_calculation_display()
# CRITICAL: Only load exclude patterns for "Computer"
exclude_patterns = []
if button_text == "Computer":
exclude_patterns = self.app.data_processing.load_exclude_patterns()
self.app.start_pause_button.config(state="disabled")
self.app.calculation_stop_event = threading.Event()
self.app.calculation_thread = threading.Thread(target=self.app.data_processing.get_folder_size_threaded, args=(
folder_path, button_text, self.app.calculation_stop_event, exclude_patterns))
self.app.calculation_thread.daemon = True
self.app.calculation_thread.start()
self._check_for_first_backup()
if self.app.mode == 'backup':
self._check_for_first_backup()
else: # restore mode
self.app.config_manager.set_setting("restore_destination_path", folder_path)
def on_right_canvas_click(self, event):
self.app.after(100, self._open_destination_dialog_from_canvas)
self.app.after(100, self._open_source_or_destination_dialog)
def _open_destination_dialog_from_canvas(self):
with message_box_animation(self.app.calculating_animation):
dest = self._get_destination_from_dialog()
if dest and os.path.isdir(dest):
self._update_destination_info(dest)
def _open_source_or_destination_dialog(self):
title = Msg.STR["select_dest_folder_title"] if self.app.mode == 'backup' else Msg.STR["select_restore_source_title"]
path = self._get_path_from_dialog(title)
if path:
self._update_right_canvas_info(path)
def _get_destination_from_dialog(self) -> Optional[str]:
def _get_path_from_dialog(self, title) -> Optional[str]:
self.app.update_idletasks()
dialog = CustomFileDialog(
self.app, mode="dir", title=Msg.STR["select_dest_folder_title"])
dialog = CustomFileDialog(self.app, mode="dir", title=title)
self.app.wait_window(dialog)
dest = dialog.get_result()
path = dialog.get_result()
dialog.destroy()
return dest
return path
def _update_destination_info(self, path):
def _update_right_canvas_info(self, path):
try:
# Get the root of the backup path to add to the exclude list
backup_root_to_exclude = f"/{path.strip('/').split('/')[0]}"
if self.app.mode == "backup":
backup_root_to_exclude = f"/{path.strip('/').split('/')[0]}"
try:
with open(AppConfig.USER_EXCLUDE_LIST_PATH, 'r+') as f:
lines = f.readlines()
f.seek(0)
if not any(backup_root_to_exclude in line for line in lines):
lines.append(f"\n{backup_root_to_exclude}\n")
f.writelines(lines)
except FileNotFoundError:
with open(AppConfig.USER_EXCLUDE_LIST_PATH, 'w') as f:
f.write(f"{backup_root_to_exclude}\n")
except IOError as e:
app_logger.log(f"Error updating exclusion list: {e}")
# Add the backup destination to the user exclude list
try:
with open(AppConfig.USER_EXCLUDE_LIST_PATH, 'r+') as f:
lines = f.readlines()
f.seek(0)
if not any(backup_root_to_exclude in line for line in lines):
lines.append(f"\n{backup_root_to_exclude}\n")
f.writelines(lines)
except FileNotFoundError:
with open(AppConfig.USER_EXCLUDE_LIST_PATH, 'w') as f:
f.write(f"{backup_root_to_exclude}\n")
except IOError as e:
app_logger.log(f"Error updating exclusion list: {e}")
total, used, free = shutil.disk_usage(path)
self.app.destination_path = path
self.app.destination_total_bytes = total
self.app.destination_used_bytes = used
size_str = f"{used / (1024**3):.2f} GB / {total / (1024**3):.2f} GB"
total, used, free = shutil.disk_usage(path)
self.app.destination_path = path
self.app.destination_total_bytes = total
self.app.destination_used_bytes = used
self.app.right_canvas_data.update({
'folder': os.path.basename(path.rstrip('/')),
'path_display': path,
'size': size_str
})
self.app.config_manager.set_setting("backup_destination_path", path)
self.app.drawing.redraw_right_canvas()
self.app.drawing.update_target_projection()
self.app.start_pause_button.config(state="normal")
size_str = f"{used / (1024**3):.2f} GB / {total / (1024**3):.2f} GB"
self.app.right_canvas_data = {
'icon': 'hdd_extralarge',
'folder': os.path.basename(path.rstrip('/')) ,
'path_display': path,
'size': size_str
}
self.app.drawing.redraw_right_canvas()
self.app.drawing.update_target_projection()
self.app.config_manager.set_setting("last_destination", path)
current_source = self.app.left_canvas_data.get('folder')
if current_source:
self.on_sidebar_button_click(current_source)
self._check_for_first_backup()
self.app.start_pause_button.config(state="normal")
elif self.app.mode == "restore":
self.app.right_canvas_data.update({
'folder': os.path.basename(path.rstrip('/')),
'path_display': path,
'size': ''
})
self.app.config_manager.set_setting("restore_source_path", path)
self.app.drawing.calculate_restore_folder_size()
self.app.start_pause_button.config(state="normal")
current_source = self.app.left_canvas_data.get('folder')
if current_source:
self.on_sidebar_button_click(current_source)
self._check_for_first_backup()
except FileNotFoundError:
with message_box_animation(self.app.calculating_animation):
MessageDialog(master=self.app, message_type="error",
@@ -174,7 +164,15 @@ class Actions:
except OSError as e:
app_logger.log(f"Error creating default user exclude list: {e}")
self.app.config_manager.set_setting("last_destination", None)
self.app.config_manager.set_setting("backup_destination_path", None)
self.app.config_manager.set_setting("restore_source_path", None)
self.app.config_manager.set_setting("restore_destination_path", None)
self.app.backup_left_canvas_data.clear()
self.app.backup_right_canvas_data.clear()
self.app.restore_left_canvas_data.clear()
self.app.restore_right_canvas_data.clear()
AppConfig.generate_and_write_final_exclude_list()
app_logger.log("Settings have been reset to default values.")
@@ -183,18 +181,12 @@ class Actions:
settings_frame.load_and_display_excludes()
self.app.destination_path = None
self.app.right_canvas_data = {
'icon': 'hdd_extralarge',
'folder': Msg.STR["select_destination"],
'path_display': '',
'size': ''
}
self.app.drawing.redraw_right_canvas()
self.app.navigation.initialize_ui_for_mode(self.app.mode)
self.app.start_pause_button.config(state="disabled")
with message_box_animation(self.app.animated_icon):
MessageDialog(master=self.app, message_type="info",
title=Msg.STR["settings_reset_title"], text=Msg.STR["settings_reset_text"]).show()
title=Msg.STR["settings_reset_title"], text=Msg.STR["settings_reset_text"])
def toggle_start_pause(self):
bg_color = self.app.style.lookup('TFrame', 'background')
@@ -259,10 +251,9 @@ class Actions:
if dest.startswith("/home"):
with message_box_animation(self.app.animated_icon):
MessageDialog(master=self.app, message_type="error",
title=Msg.STR["error"], text=Msg.STR["system_backup_in_home_error"]).show()
title=Msg.STR["error"], text=Msg.STR["system_backup_in_home_error"])
return
# Create a list of paths to the exclude files for rsync.
exclude_file_paths = []
if AppConfig.GENERATED_EXCLUDE_LIST_PATH.exists():
exclude_file_paths.append(AppConfig.GENERATED_EXCLUDE_LIST_PATH)
@@ -277,7 +268,7 @@ class Actions:
dest = self.app.destination_path
if not dest:
MessageDialog(master=self.app, message_type="error",
title=Msg.STR["error"], text=Msg.STR["err_no_dest_folder"]).show()
title=Msg.STR["error"], text=Msg.STR["err_no_dest_folder"])
return
is_dry_run = self.app.testlauf_var.get()
@@ -286,4 +277,4 @@ class Actions:
source, dest, False, is_dry_run=is_dry_run, exclude_files=None, on_progress=self.update_task_progress, on_completion=self.on_backup_completion, on_error=self.on_backup_error)
def update_task_progress(self, percentage):
self.app.task_progress["value"] = percentage
self.app.task_progress["value"] = percentage

View File

@@ -1,12 +1,27 @@
# pyimage/ui/drawing.py
import tkinter as tk
from app_config import AppConfig, Msg
import os
import threading
from shared_libs.animated_icon import AnimatedIcon
class Drawing:
def __init__(self, app):
self.app = app
def _start_calculating_animation(self, canvas):
self._stop_calculating_animation() # Ensure no old animation is running
animation_type = self.app.config_manager.get_setting("calculation_animation_type", "double_arc")
self.app.calculating_animation = AnimatedIcon(
canvas, width=20, height=20, animation_type=animation_type, use_pillow=True)
self.app.calculating_animation.start()
def _stop_calculating_animation(self):
if self.app.calculating_animation:
self.app.calculating_animation.stop()
self.app.calculating_animation.destroy()
self.app.calculating_animation = None
def redraw_left_canvas(self, event=None):
canvas = self.app.left_canvas
canvas.delete("all")
@@ -47,16 +62,23 @@ class Drawing:
x=width/2 + 70, y=140, anchor="center")
def redraw_right_canvas(self, event=None):
"""Dispatches to the correct drawing method based on the current mode."""
if self.app.mode == "backup":
self.redraw_right_canvas_backup(event)
else: # "restore"
self.redraw_right_canvas_restore(event)
def redraw_right_canvas_backup(self, event=None):
canvas = self.app.right_canvas
canvas.delete("all")
width = canvas.winfo_width()
height = canvas.winfo_height()
right_canvas_title = Msg.STR["destination"] if self.app.mode == "backup" else Msg.STR["source"]
right_canvas_title = Msg.STR["destination"]
canvas.create_text(10, 10, anchor="nw", text=right_canvas_title, font=(
AppConfig.UI_CONFIG["font_family"], 12, "bold"))
icon_name = self.app.right_canvas_data.get('icon')
icon_name = 'hdd_extralarge'
if icon_name:
icon = self.app.image_manager.get_icon(icon_name)
if icon:
@@ -75,6 +97,76 @@ class Drawing:
canvas.create_text(width / 2, 160, text=path_display, font=(
AppConfig.UI_CONFIG["font_family"], 10), fill="gray")
def redraw_right_canvas_restore(self, event=None):
canvas = self.app.right_canvas
canvas.delete("all")
width = canvas.winfo_width()
height = canvas.winfo_height()
right_canvas_title = Msg.STR["source"]
canvas.create_text(10, 10, anchor="nw", text=right_canvas_title, font=(
AppConfig.UI_CONFIG["font_family"], 12, "bold"))
icon_name = 'hdd_extralarge'
if icon_name:
icon = self.app.image_manager.get_icon(icon_name)
if icon:
canvas.create_image(width / 2, 60, image=icon)
folder_name = self.app.right_canvas_data.get('folder', '')
canvas.create_text(width / 2, 120, text=folder_name, font=(
AppConfig.UI_CONFIG["font_family"], 14, "bold"))
size_text = self.app.right_canvas_data.get('size', '')
if size_text:
canvas.create_text(width / 2, 140, text=size_text)
path_display = self.app.right_canvas_data.get('path_display', '')
if path_display:
canvas.create_text(width / 2, 160, text=path_display, font=(
AppConfig.UI_CONFIG["font_family"], 10), fill="gray")
if self.app.right_canvas_data.get('calculating', False):
if self.app.calculating_animation:
self.app.calculating_animation.place(
x=width/2 + 70, y=140, anchor="center")
def start_backup_calculation_display(self):
self._start_calculating_animation(self.app.left_canvas)
self.redraw_left_canvas()
def calculate_restore_folder_size(self):
path_to_calculate = self.app.right_canvas_data.get('path_display')
if path_to_calculate and os.path.isdir(path_to_calculate):
self.app.right_canvas_data['calculating'] = True
self.app.right_canvas_data['size'] = Msg.STR['calculating_size']
self._start_calculating_animation(self.app.right_canvas)
self.redraw_right_canvas_restore()
threading.Thread(target=self._calculate_and_update_restore_size, args=(path_to_calculate,), daemon=True).start()
def _calculate_and_update_restore_size(self, path):
total_size = 0
try:
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
except OSError as e:
print(f"Error calculating size for {path}: {e}")
size_text = "Error"
else:
size_gb = total_size / (1024**3)
size_text = f"{size_gb:.2f} GB"
def update_ui():
self.app.right_canvas_data['size'] = size_text
self.app.right_canvas_data['calculating'] = False
self._stop_calculating_animation()
self.redraw_right_canvas_restore()
self.app.after(0, update_ui)
def update_target_projection(self):
if self.app.destination_total_bytes == 0:
return
@@ -92,7 +184,6 @@ class Drawing:
info_font = (AppConfig.UI_CONFIG["font_family"], 12, "bold")
# Determine button state and progress bar color based on usage
if projected_total_percentage >= 0.95:
self.app.start_pause_button.config(state="disabled")
canvas.create_rectangle(0, 0, canvas_width, canvas.winfo_height(

View File

@@ -11,24 +11,78 @@ class Navigation:
if self.app.calculation_thread and self.app.calculation_thread.is_alive():
self.app.calculation_stop_event.set()
def initialize_ui_for_mode(self, mode):
"""Resets and initializes the UI components for the given mode."""
self.app.mode = mode
self._cancel_calculation()
# Point to the correct data dictionaries for the mode
if mode == "backup":
self.app.left_canvas_data = self.app.backup_left_canvas_data
self.app.right_canvas_data = self.app.backup_right_canvas_data
active_index = 0
else: # restore
self.app.left_canvas_data = self.app.restore_left_canvas_data
self.app.right_canvas_data = self.app.restore_right_canvas_data
active_index = 1
# Set default content if the dictionaries are empty
if not self.app.left_canvas_data:
if mode == "backup":
# In backup mode, left is source, default to Computer
self.app.left_canvas_data.update({
'icon': 'computer_extralarge',
'folder': 'Computer',
'path_display': '',
'size': ''
})
else: # In restore mode, left is destination
self.app.left_canvas_data.update({
'icon': 'computer_extralarge', # Default icon
'folder': Msg.STR["select_destination"],
'path_display': '',
'size': ''
})
if not self.app.right_canvas_data:
# Right canvas is always the destination/HDD view conceptually
self.app.right_canvas_data.update({
'icon': 'hdd_extralarge',
'folder': Msg.STR["select_destination"] if mode == 'backup' else Msg.STR["source"],
'path_display': '',
'size': ''
})
# Update UI elements
if mode == "backup":
self.app.mode_button_icon = self.app.image_manager.get_icon("forward_extralarge")
self.app.info_label.config(text=Msg.STR["backup_mode_info"])
else: # restore
self.app.mode_button_icon = self.app.image_manager.get_icon("back_extralarge")
self.app.info_label.config(text=Msg.STR["restore_mode_info"])
self.app.mode_button.config(image=self.app.mode_button_icon)
self.app.drawing.update_nav_buttons(active_index)
self.app.drawing.redraw_left_canvas()
self.app.drawing.redraw_right_canvas()
def toggle_mode(self, mode=None, active_index=None, trigger_calculation=True):
self._cancel_calculation()
# Determine the new mode and active_index
if mode:
self.app.mode = mode
# active_index is passed from the top buttons, so it should be correct
else: # This is when the middle arrow is clicked
if self.app.mode == "backup":
self.app.mode = "restore"
active_index = 1 # Set index for Restore
else:
self.app.mode = "backup"
active_index = 0 # Set index for Backup
# Save current state before switching
if self.app.mode == 'backup':
self.app.backup_left_canvas_data = self.app.left_canvas_data
self.app.backup_right_canvas_data = self.app.right_canvas_data
else:
self.app.restore_left_canvas_data = self.app.left_canvas_data
self.app.restore_right_canvas_data = self.app.right_canvas_data
# Now, update the nav buttons with the determined index
if active_index is not None:
self.app.drawing.update_nav_buttons(active_index)
if mode is None: # Clicked the middle arrow button
new_mode = "restore" if self.app.mode == "backup" else "backup"
else:
new_mode = mode
self.initialize_ui_for_mode(new_mode)
# Hide/show frames
self.app.log_frame.grid_remove()
@@ -40,30 +94,15 @@ class Navigation:
self.app.target_size_frame.grid()
self._update_task_bar_visibility(self.app.mode)
# Save the current mode
self.app.config_manager.set_setting("last_mode", self.app.mode)
# Update UI elements based on mode
if self.app.mode == "backup":
self.app.mode_button_icon = self.app.image_manager.get_icon(
"forward_extralarge")
self.app.mode_button.config(image=self.app.mode_button_icon)
self.app.info_label.config(
text=Msg.STR["backup_mode_info"])
else: # restore
self.app.mode_button_icon = self.app.image_manager.get_icon(
"back_extralarge")
self.app.mode_button.config(image=self.app.mode_button_icon)
self.app.info_label.config(
text=Msg.STR["restore_mode_info"])
self.app.drawing.redraw_left_canvas()
self.app.drawing.redraw_right_canvas()
if trigger_calculation:
current_source = self.app.left_canvas_data.get('folder')
if current_source:
self.app.actions.on_sidebar_button_click(current_source)
current_source_folder = self.app.left_canvas_data.get('folder')
if current_source_folder and self.app.mode == 'backup':
self.app.actions.on_sidebar_button_click(current_source_folder)
elif self.app.mode == 'restore':
# In restore mode, the size calculation is triggered by selecting a source (right canvas)
# We might need to re-trigger it if a source was already selected
if self.app.right_canvas_data.get('path_display'):
self.app.drawing.calculate_restore_folder_size()
def _update_task_bar_visibility(self, mode):
if mode in ["backup", "restore"]: