791 lines
No EOL
37 KiB
Python
791 lines
No EOL
37 KiB
Python
# #############################################
|
|
# # SVG to Image Converter (using Inkscape) #
|
|
# #############################################
|
|
#
|
|
# Prerequisites:
|
|
# - Python 3.6+
|
|
# - Inkscape installed and preferably in the system PATH or a standard location.
|
|
#
|
|
# Required libraries (for development/running from source):
|
|
# pip install Pillow tkinterdnd2
|
|
#
|
|
# To create a standalone executable (after installing PyInstaller: pip install pyinstaller):
|
|
# Windows: pyinstaller --onefile --windowed --name SVG_Converter --icon=icon.ico --add-data="path/to/tkinterdnd2;tkinterdnd2" svg_converter_app.py
|
|
# macOS: pyinstaller --onefile --windowed --name SVG_Converter --icon=icon.icns --add-data="path/to/tkinterdnd2:tkinterdnd2" svg_converter_app.py
|
|
# Linux: pyinstaller --onefile --windowed --name SVG_Converter --add-data="path/to/tkinterdnd2:tkinterdnd2" svg_converter_app.py
|
|
#
|
|
# Notes on PyInstaller:
|
|
# - Replace 'path/to/tkinterdnd2' with the actual path to the library in your environment (e.g., find via `pip show tkinterdnd2`).
|
|
# - `--windowed` prevents the console window from appearing.
|
|
# - `--onefile` creates a single executable (may start slower). Remove for a faster-starting folder distribution.
|
|
# - You might need to adjust `--add-data` based on your environment and OS. Test thoroughly.
|
|
# - Icons (.ico for Win, .icns for Mac) are optional.
|
|
# - Pillow is usually picked up automatically by PyInstaller.
|
|
#
|
|
# #############################################
|
|
|
|
import tkinter as tk
|
|
from tkinter import ttk, filedialog, messagebox, scrolledtext
|
|
from tkinterdnd2 import DND_FILES, TkinterDnD # Requires: pip install tkinterdnd2
|
|
import subprocess
|
|
import os
|
|
import sys
|
|
import shutil
|
|
import threading
|
|
import queue
|
|
import json
|
|
from pathlib import Path
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from PIL import Image, ImageTk # Requires: pip install Pillow
|
|
|
|
# --- Constants ---
|
|
APP_NAME = "SVG Converter"
|
|
VERSION = "1.1.0"
|
|
SETTINGS_FILE = "svg_converter_settings.json"
|
|
MAX_CONCURRENT_TASKS = 4 # Default max parallel Inkscape processes
|
|
|
|
# --- Helper Functions ---
|
|
|
|
def find_inkscape_executable():
|
|
"""Attempts to find the Inkscape executable."""
|
|
common_paths = []
|
|
names = ["inkscape", "inkscape.exe", "inkscape.com"] # .com for older windows versions
|
|
|
|
# 1. Check PATH
|
|
for name in names:
|
|
inkscape_path = shutil.which(name)
|
|
if inkscape_path:
|
|
return inkscape_path
|
|
|
|
# 2. Check common installation directories
|
|
if sys.platform == "win32":
|
|
program_files = os.environ.get("ProgramFiles", "C:\\Program Files")
|
|
program_files_x86 = os.environ.get("ProgramFiles(x86)", "C:\\Program Files (x86)")
|
|
common_paths.extend([
|
|
Path(program_files) / "Inkscape" / "bin" / "inkscape.exe",
|
|
Path(program_files_x86) / "Inkscape" / "bin" / "inkscape.exe",
|
|
Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "Inkscape" / "bin" / "inkscape.exe",
|
|
# Add scoop/chocolatey paths if necessary
|
|
])
|
|
elif sys.platform == "darwin": # macOS
|
|
common_paths.extend([
|
|
Path("/Applications/Inkscape.app/Contents/MacOS/inkscape"),
|
|
Path("/usr/local/bin/inkscape"),
|
|
])
|
|
else: # Linux
|
|
common_paths.extend([
|
|
Path("/usr/bin/inkscape"),
|
|
Path("/usr/local/bin/inkscape"),
|
|
# Add Flatpak/Snap paths if necessary
|
|
Path(os.path.expanduser("~/.local/bin/inkscape")),
|
|
])
|
|
|
|
for path in common_paths:
|
|
if path.is_file():
|
|
return str(path)
|
|
|
|
return None # Not found
|
|
|
|
def get_platform_open_command(path):
|
|
"""Returns the command to open a folder in the default file explorer."""
|
|
path = os.path.abspath(path)
|
|
if sys.platform == "win32":
|
|
return lambda: os.startfile(path)
|
|
elif sys.platform == "darwin":
|
|
return lambda: subprocess.run(["open", path], check=True)
|
|
else: # Linux and other POSIX
|
|
return lambda: subprocess.run(["xdg-open", path], check=True)
|
|
|
|
# --- Main Application Class ---
|
|
|
|
class SVGtoPNGConverter(TkinterDnD.Tk): # Inherit from TkinterDnD.Tk for drag & drop
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.title(f"{APP_NAME} v{VERSION}")
|
|
# self.geometry("800x650") # Adjust size as needed
|
|
|
|
# --- Detect Inkscape ---
|
|
self.inkscape_path = find_inkscape_executable()
|
|
if not self.inkscape_path:
|
|
messagebox.showerror("Inkscape Not Found",
|
|
"Inkscape executable could not be found.\n"
|
|
"Please ensure Inkscape is installed and added to your system's PATH,\n"
|
|
"or installed in a standard location.")
|
|
# Optionally disable conversion features if Inkscape isn't found
|
|
# For now, we proceed but conversion will fail.
|
|
|
|
# --- Variables ---
|
|
self.selected_files = []
|
|
self.output_dir = tk.StringVar(value="<Same as source>")
|
|
self.dpi = tk.IntVar(value=150)
|
|
self.background = tk.StringVar(value="#ffffff") # Default white
|
|
self.output_format = tk.StringVar(value="png")
|
|
self.export_width = tk.StringVar(value="")
|
|
self.export_height = tk.StringVar(value="")
|
|
self.jpeg_quality = tk.IntVar(value=90)
|
|
self.auto_open_folder = tk.BooleanVar(value=False)
|
|
self.concurrent_tasks = tk.IntVar(value=MAX_CONCURRENT_TASKS)
|
|
self.conversion_active = False
|
|
self.failed_files = []
|
|
self.log_queue = queue.Queue() # For thread-safe logging
|
|
|
|
# --- Load Settings ---
|
|
self.load_settings()
|
|
|
|
# --- UI Setup ---
|
|
self.setup_ui()
|
|
|
|
# --- Drag and Drop Setup ---
|
|
self.drop_target_register(DND_FILES)
|
|
self.dnd_bind('<<Drop>>', self.handle_drop)
|
|
|
|
# --- Protocol Handlers ---
|
|
self.protocol("WM_DELETE_WINDOW", self.on_closing)
|
|
|
|
# --- Start Log Queue Monitor ---
|
|
self.after(100, self.process_log_queue)
|
|
|
|
def setup_ui(self):
|
|
"""Creates and arranges the GUI elements."""
|
|
self.main_frame = ttk.Frame(self, padding="10")
|
|
self.main_frame.pack(fill=tk.BOTH, expand=True)
|
|
|
|
# --- Top Frame: File Selection ---
|
|
top_frame = ttk.LabelFrame(self.main_frame, text="Files", padding="10")
|
|
top_frame.pack(fill=tk.X, pady=(0, 10))
|
|
|
|
btn_frame = ttk.Frame(top_frame)
|
|
btn_frame.pack(pady=5)
|
|
|
|
ttk.Button(btn_frame, text="Add Files", command=self.add_files).pack(side=tk.LEFT, padx=5)
|
|
ttk.Button(btn_frame, text="Add Folder", command=self.add_folder).pack(side=tk.LEFT, padx=5)
|
|
ttk.Button(btn_frame, text="Clear List", command=self.clear_list).pack(side=tk.LEFT, padx=5)
|
|
|
|
list_frame = ttk.Frame(top_frame)
|
|
list_frame.pack(fill=tk.BOTH, expand=True)
|
|
|
|
self.file_list_scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL)
|
|
self.file_list = tk.Listbox(list_frame, selectmode=tk.EXTENDED, height=10,
|
|
yscrollcommand=self.file_list_scrollbar.set)
|
|
self.file_list_scrollbar.config(command=self.file_list.yview)
|
|
|
|
self.file_list_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
|
self.file_list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
|
self.file_list.bind("<<ListboxSelect>>", self.show_preview) # Bind selection change
|
|
|
|
# --- Middle Frame: Settings ---
|
|
settings_frame = ttk.LabelFrame(self.main_frame, text="Conversion Settings", padding="10")
|
|
settings_frame.pack(fill=tk.X, pady=(0, 10))
|
|
|
|
grid_frame = ttk.Frame(settings_frame)
|
|
grid_frame.pack(fill=tk.X)
|
|
|
|
# Configure grid columns to space out elements
|
|
grid_frame.columnconfigure(0, weight=0) # Label
|
|
grid_frame.columnconfigure(1, weight=1) # Control 1
|
|
grid_frame.columnconfigure(2, weight=0) # Spacer/Label 2
|
|
grid_frame.columnconfigure(3, weight=1) # Control 2
|
|
|
|
# Row 1: DPI & Background
|
|
ttk.Label(grid_frame, text="DPI:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
|
|
dpi_spinbox = ttk.Spinbox(grid_frame, from_=10, to=1200, increment=10, textvariable=self.dpi, width=8)
|
|
dpi_spinbox.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
|
|
|
|
ttk.Label(grid_frame, text="Background:").grid(row=0, column=2, padx=5, pady=5, sticky="w")
|
|
bg_entry = ttk.Entry(grid_frame, textvariable=self.background, width=10)
|
|
bg_entry.grid(row=0, column=3, padx=5, pady=5, sticky="ew")
|
|
ttk.Button(grid_frame, text="Color...", command=self.choose_color).grid(row=0, column=4, padx=(0, 5), pady=5) # Column 4 for button
|
|
|
|
# Row 2: Output Format & JPEG Quality
|
|
ttk.Label(grid_frame, text="Format:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
|
|
format_menu = ttk.OptionMenu(grid_frame, self.output_format, "png", "png", "jpg", "tiff", "pdf", command=self.update_quality_slider_visibility) # webp ? Requires newer Inkscape
|
|
format_menu.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
|
|
|
|
self.quality_label = ttk.Label(grid_frame, text="JPEG Quality:")
|
|
self.quality_scale = ttk.Scale(grid_frame, from_=1, to=100, orient=tk.HORIZONTAL, variable=self.jpeg_quality, length=100)
|
|
self.quality_value_label = ttk.Label(grid_frame, textvariable=self.jpeg_quality, width=4)
|
|
# Place quality slider initially hidden
|
|
self.update_quality_slider_visibility() # Set initial state based on format
|
|
|
|
# Row 3: Dimensions (Width/Height)
|
|
ttk.Label(grid_frame, text="Width (px):").grid(row=2, column=0, padx=5, pady=5, sticky="w")
|
|
width_entry = ttk.Entry(grid_frame, textvariable=self.export_width, width=8)
|
|
width_entry.grid(row=2, column=1, padx=5, pady=5, sticky="ew")
|
|
|
|
ttk.Label(grid_frame, text="Height (px):").grid(row=2, column=2, padx=5, pady=5, sticky="w")
|
|
height_entry = ttk.Entry(grid_frame, textvariable=self.export_height, width=8)
|
|
height_entry.grid(row=2, column=3, padx=5, pady=5, sticky="ew")
|
|
ttk.Label(grid_frame, text="(Optional)").grid(row=2, column=4, padx=(0, 5), pady=5, sticky="w")
|
|
|
|
|
|
# Row 4: Output Directory
|
|
ttk.Label(grid_frame, text="Output Folder:").grid(row=3, column=0, padx=5, pady=5, sticky="w")
|
|
output_entry = ttk.Entry(grid_frame, textvariable=self.output_dir, state='readonly', width=30)
|
|
output_entry.grid(row=3, column=1, columnspan=3, padx=5, pady=5, sticky="ew") # Span 3 columns
|
|
ttk.Button(grid_frame, text="Browse...", command=self.choose_output_dir).grid(row=3, column=4, padx=(0, 5), pady=5)
|
|
|
|
# Row 5: Parallel Tasks & Auto-Open
|
|
ttk.Label(grid_frame, text="Parallel Tasks:").grid(row=4, column=0, padx=5, pady=5, sticky="w")
|
|
tasks_spinbox = ttk.Spinbox(grid_frame, from_=1, to=os.cpu_count() or 4, increment=1, textvariable=self.concurrent_tasks, width=8)
|
|
tasks_spinbox.grid(row=4, column=1, padx=5, pady=5, sticky="ew")
|
|
|
|
auto_open_check = ttk.Checkbutton(grid_frame, text="Auto-open folder on completion", variable=self.auto_open_folder)
|
|
auto_open_check.grid(row=4, column=2, columnspan=3, padx=5, pady=5, sticky="w")
|
|
|
|
|
|
# --- Bottom Frame: Control and Log ---
|
|
bottom_frame = ttk.Frame(self.main_frame)
|
|
bottom_frame.pack(fill=tk.BOTH, expand=True)
|
|
|
|
control_frame = ttk.Frame(bottom_frame)
|
|
control_frame.pack(fill=tk.X, pady=(0, 10))
|
|
|
|
self.convert_button = ttk.Button(control_frame, text="Start Conversion", command=self.start_conversion)
|
|
self.convert_button.pack(side=tk.LEFT, padx=5)
|
|
self.retry_button = ttk.Button(control_frame, text="Retry Failed", command=self.retry_failed, state=tk.DISABLED)
|
|
self.retry_button.pack(side=tk.LEFT, padx=5)
|
|
self.preview_label = ttk.Label(control_frame, text="Preview:", anchor="e")
|
|
self.preview_label.pack(side=tk.LEFT, padx=(10, 2))
|
|
self.preview_canvas = tk.Canvas(control_frame, width=50, height=50, bg="lightgrey", relief="sunken")
|
|
self.preview_canvas.pack(side=tk.LEFT)
|
|
self.preview_image = None # To hold the PhotoImage object
|
|
|
|
|
|
self.progress_label = ttk.Label(control_frame, text="Progress:")
|
|
self.progress_label.pack(side=tk.LEFT, padx=(10, 5))
|
|
self.progress = ttk.Progressbar(control_frame, orient='horizontal', length=200, mode='determinate')
|
|
self.progress.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
|
|
self.status_label = ttk.Label(control_frame, text="", width=15, anchor="e")
|
|
self.status_label.pack(side=tk.RIGHT, padx=5)
|
|
|
|
log_frame = ttk.LabelFrame(bottom_frame, text="Log", padding="5")
|
|
log_frame.pack(fill=tk.BOTH, expand=True)
|
|
|
|
self.log_area = scrolledtext.ScrolledText(log_frame, height=10, wrap=tk.WORD, state='disabled')
|
|
self.log_area.pack(fill=tk.BOTH, expand=True)
|
|
# Configure tags for log levels
|
|
self.log_area.tag_config("info", foreground="black")
|
|
self.log_area.tag_config("success", foreground="green")
|
|
self.log_area.tag_config("warning", foreground="orange")
|
|
self.log_area.tag_config("error", foreground="red")
|
|
self.log_area.tag_config("debug", foreground="grey")
|
|
|
|
def update_quality_slider_visibility(self, *args):
|
|
"""Show JPEG quality slider only when JPEG format is selected."""
|
|
if self.output_format.get().lower() == "jpg":
|
|
self.quality_label.grid(row=1, column=2, padx=5, pady=5, sticky="w")
|
|
self.quality_scale.grid(row=1, column=3, padx=5, pady=5, sticky="ew")
|
|
self.quality_value_label.grid(row=1, column=4, padx=(0, 5), pady=5, sticky="w")
|
|
else:
|
|
self.quality_label.grid_remove()
|
|
self.quality_scale.grid_remove()
|
|
self.quality_value_label.grid_remove()
|
|
|
|
def choose_color(self):
|
|
"""Open color chooser dialog to select background color."""
|
|
from tkinter import colorchooser
|
|
color_code = colorchooser.askcolor(title ="Choose background color", initialcolor=self.background.get())
|
|
if color_code and color_code[1]: # Check if a color was selected (returns tuple: (rgb, hex))
|
|
self.background.set(color_code[1])
|
|
|
|
def log(self, message, level="info"):
|
|
"""Adds a message to the log queue for thread-safe display."""
|
|
self.log_queue.put((message, level))
|
|
|
|
def process_log_queue(self):
|
|
"""Processes messages from the log queue and updates the GUI."""
|
|
while not self.log_queue.empty():
|
|
try:
|
|
message, level = self.log_queue.get_nowait()
|
|
self.log_area.configure(state='normal')
|
|
self.log_area.insert(tk.END, f"{message}\n", level)
|
|
self.log_area.configure(state='disabled')
|
|
self.log_area.see(tk.END) # Auto-scroll
|
|
except queue.Empty:
|
|
break
|
|
except Exception as e:
|
|
# Basic fallback logging if GUI logging fails
|
|
print(f"Log Error: {e}")
|
|
# Reschedule processing
|
|
self.after(100, self.process_log_queue)
|
|
|
|
def handle_drop(self, event):
|
|
"""Handles files dropped onto the application window."""
|
|
files_to_add = []
|
|
# event.data seems to be a string with space-separated, brace-enclosed paths
|
|
# We need to parse this carefully. TkinterDnD's parsing can be tricky.
|
|
try:
|
|
raw_files = self.tk.splitlist(event.data)
|
|
for item in raw_files:
|
|
path = Path(item.strip('{}')) # Remove potential braces and create Path object
|
|
if path.is_file() and path.suffix.lower() == ".svg":
|
|
files_to_add.append(str(path))
|
|
elif path.is_dir():
|
|
self.log(f"Scanning folder: {path}", "debug")
|
|
for sub_item in path.rglob('*.svg'):
|
|
if sub_item.is_file():
|
|
files_to_add.append(str(sub_item))
|
|
if files_to_add:
|
|
self.update_file_list(files_to_add)
|
|
else:
|
|
self.log("Drop contained no valid SVG files or folders.", "warning")
|
|
except Exception as e:
|
|
self.log(f"Error processing dropped files: {e}", "error")
|
|
messagebox.showerror("Drop Error", f"Could not process dropped files:\n{e}")
|
|
|
|
|
|
def update_file_list(self, new_files):
|
|
"""Adds new files to the listbox, avoiding duplicates."""
|
|
count = 0
|
|
current_files_set = set(self.selected_files)
|
|
for file_path in new_files:
|
|
abs_path = str(Path(file_path).resolve()) # Normalize path
|
|
if abs_path not in current_files_set:
|
|
self.selected_files.append(abs_path)
|
|
self.file_list.insert(tk.END, os.path.basename(abs_path)) # Display only filename
|
|
current_files_set.add(abs_path)
|
|
count += 1
|
|
if count > 0:
|
|
self.log(f"Added {count} new SVG file(s). Total: {len(self.selected_files)}")
|
|
self.update_status()
|
|
|
|
def add_files(self):
|
|
"""Opens file dialog to select SVG files."""
|
|
files = filedialog.askopenfilenames(
|
|
title="Select SVG Files",
|
|
filetypes=[("SVG files", "*.svg"), ("All files", "*.*")]
|
|
)
|
|
if files:
|
|
self.update_file_list(files)
|
|
|
|
def add_folder(self):
|
|
"""Opens directory dialog to select a folder containing SVGs."""
|
|
folder = filedialog.askdirectory(title="Select Folder Containing SVGs")
|
|
if folder:
|
|
self.log(f"Scanning folder: {folder}")
|
|
svg_files = [str(p) for p in Path(folder).rglob('*.svg') if p.is_file()]
|
|
if svg_files:
|
|
self.update_file_list(svg_files)
|
|
else:
|
|
self.log(f"No SVG files found in {folder}", "warning")
|
|
|
|
def clear_list(self):
|
|
"""Clears the file list and internal selection."""
|
|
self.selected_files.clear()
|
|
self.file_list.delete(0, tk.END)
|
|
self.failed_files.clear()
|
|
self.retry_button.config(state=tk.DISABLED)
|
|
self.log("File list cleared.")
|
|
self.update_status()
|
|
self.progress['value'] = 0
|
|
self.preview_canvas.delete("all") # Clear preview
|
|
|
|
def choose_output_dir(self):
|
|
"""Allows user to select an output directory."""
|
|
directory = filedialog.askdirectory(title="Select Output Directory")
|
|
if directory:
|
|
self.output_dir.set(directory)
|
|
else:
|
|
# If user cancels, maybe revert to default or keep current
|
|
if not self.output_dir.get() or self.output_dir.get() == "<Same as source>":
|
|
self.output_dir.set("<Same as source>")
|
|
|
|
|
|
def show_preview(self, event=None):
|
|
"""Attempts to show a small preview of the selected SVG."""
|
|
self.preview_canvas.delete("all") # Clear previous preview
|
|
selection_indices = self.file_list.curselection()
|
|
if not selection_indices:
|
|
return
|
|
|
|
try:
|
|
selected_index = selection_indices[0] # Preview only the first selected item
|
|
svg_path = self.selected_files[selected_index]
|
|
|
|
if not self.inkscape_path:
|
|
self.preview_canvas.create_text(25, 25, text="No Inkscape", fill="red", width=45, anchor="center", justify="center")
|
|
return
|
|
|
|
# Generate a temporary PNG preview using Inkscape
|
|
# This is simpler than integrating a full SVG rendering library
|
|
temp_png_path = Path(os.path.expanduser("~")) / f".svg_converter_preview_{os.getpid()}.png" # Temp file
|
|
cmd = [
|
|
self.inkscape_path,
|
|
f"--export-filename={temp_png_path}",
|
|
"--export-type=png",
|
|
"--export-dpi=30", # Low DPI for speed
|
|
f"--export-width=50", # Fixed small size
|
|
f"--export-height=50",
|
|
"--export-background-opacity=0", # Transparent BG
|
|
svg_path
|
|
]
|
|
|
|
try:
|
|
# Use timeout to prevent hanging on complex SVGs for preview
|
|
result = subprocess.run(cmd, capture_output=True, text=True, check=False, timeout=5)
|
|
|
|
if result.returncode == 0 and temp_png_path.exists():
|
|
img = Image.open(temp_png_path)
|
|
img.thumbnail((50, 50), Image.Resampling.LANCZOS) # Resize if needed
|
|
self.preview_image = ImageTk.PhotoImage(img)
|
|
self.preview_canvas.create_image(25, 25, image=self.preview_image, anchor="center")
|
|
else:
|
|
# Failed to generate preview
|
|
self.preview_canvas.create_text(25, 25, text="Preview Failed", fill="orange", width=45, anchor="center", justify="center")
|
|
self.log(f"Preview failed for {os.path.basename(svg_path)}: {result.stderr[:100]}...", "warning")
|
|
|
|
except subprocess.TimeoutExpired:
|
|
self.preview_canvas.create_text(25, 25, text="Preview Timeout", fill="orange", width=45, anchor="center", justify="center")
|
|
self.log(f"Preview timed out for {os.path.basename(svg_path)}", "warning")
|
|
except Exception as e:
|
|
self.preview_canvas.create_text(25, 25, text="Preview Error", fill="red", width=45, anchor="center", justify="center")
|
|
self.log(f"Preview error for {os.path.basename(svg_path)}: {e}", "error")
|
|
finally:
|
|
# Clean up temporary file
|
|
if temp_png_path.exists():
|
|
try:
|
|
temp_png_path.unlink()
|
|
except OSError:
|
|
pass # Ignore cleanup errors
|
|
|
|
except Exception as e:
|
|
self.log(f"Error getting selection for preview: {e}", "error")
|
|
self.preview_canvas.create_text(25, 25, text="Error", fill="red")
|
|
|
|
|
|
def update_status(self, text=""):
|
|
"""Updates the status label, typically showing file counts."""
|
|
if not text:
|
|
total = len(self.selected_files)
|
|
failed = len(self.failed_files)
|
|
if failed > 0:
|
|
text = f"{total} Files ({failed} Failed)"
|
|
else:
|
|
text = f"{total} Files"
|
|
self.status_label.config(text=text)
|
|
|
|
def set_ui_state(self, active):
|
|
"""Enable/disable UI elements during conversion."""
|
|
self.conversion_active = active
|
|
state = tk.DISABLED if active else tk.NORMAL
|
|
# Disable buttons
|
|
for widget in self.main_frame.winfo_children():
|
|
if isinstance(widget, ttk.LabelFrame):
|
|
for sub_widget in widget.winfo_children():
|
|
if isinstance(sub_widget, (ttk.Button, ttk.Spinbox, ttk.Entry, ttk.OptionMenu, ttk.Scale, tk.Listbox, ttk.Checkbutton)):
|
|
try: # OptionMenu might complain if state doesn't exist
|
|
sub_widget.config(state=state)
|
|
except tk.TclError:
|
|
pass
|
|
# Special handling for Convert/Retry buttons
|
|
self.convert_button.config(text="Cancel" if active else "Start Conversion", state=tk.NORMAL) # Always allow cancel
|
|
if not active and self.failed_files:
|
|
self.retry_button.config(state=tk.NORMAL)
|
|
else:
|
|
self.retry_button.config(state=tk.DISABLED)
|
|
# Keep log area scrollable but not editable
|
|
self.log_area.configure(state='disabled')
|
|
# Keep file list scrollable maybe? - Disabled for simplicity during run
|
|
self.file_list.config(state=state)
|
|
|
|
|
|
def start_conversion(self):
|
|
"""Initiates the conversion process."""
|
|
if self.conversion_active:
|
|
# Implement Cancel Logic Here (more complex with threads)
|
|
self.log("Cancellation requested...", "warning")
|
|
# For now, just set a flag - threads need to check this flag
|
|
self.conversion_active = False # Signal threads to stop early if possible
|
|
self.convert_button.config(text="Cancelling...", state=tk.DISABLED) # Indicate cancelling
|
|
# Note: True cancellation requires more sophisticated thread/process management
|
|
return
|
|
|
|
if not self.selected_files:
|
|
messagebox.showwarning("No Files", "Please add SVG files to the list first.")
|
|
return
|
|
|
|
if not self.inkscape_path:
|
|
messagebox.showerror("Inkscape Not Found", "Cannot start conversion without Inkscape.")
|
|
return
|
|
|
|
self.log("="*30)
|
|
self.log(f"Starting conversion for {len(self.selected_files)} file(s)...")
|
|
self.log(f"Settings: DPI={self.dpi.get()}, Format={self.output_format.get()}, BG={self.background.get()}", "debug")
|
|
if self.output_dir.get() != "<Same as source>":
|
|
self.log(f"Output Directory: {self.output_dir.get()}", "debug")
|
|
if self.export_width.get() or self.export_height.get():
|
|
self.log(f"Dimensions: W={self.export_width.get() or 'auto'} H={self.export_height.get() or 'auto'}", "debug")
|
|
if self.output_format.get().lower() == "jpg":
|
|
self.log(f"JPEG Quality: {self.jpeg_quality.get()}", "debug")
|
|
|
|
|
|
self.set_ui_state(active=True)
|
|
self.progress['value'] = 0
|
|
self.progress['maximum'] = len(self.selected_files)
|
|
self.failed_files.clear()
|
|
self.update_status("Running...")
|
|
|
|
# Start the conversion in a separate thread to keep GUI responsive
|
|
self.conversion_thread = threading.Thread(target=self.run_conversion_threaded, daemon=True)
|
|
self.conversion_thread.start()
|
|
|
|
def run_conversion_threaded(self):
|
|
"""Manages the conversion process using a thread pool."""
|
|
files_to_process = list(self.selected_files) # Work on a copy
|
|
total_files = len(files_to_process)
|
|
success_count = 0
|
|
processed_count = 0
|
|
final_output_dir = None # Track the last used output directory
|
|
|
|
max_workers = self.concurrent_tasks.get()
|
|
if max_workers < 1: max_workers = 1
|
|
self.log(f"Using up to {max_workers} parallel tasks.", "debug")
|
|
|
|
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
futures = {executor.submit(self.convert_file, file_path): file_path for file_path in files_to_process}
|
|
|
|
for future in as_completed(futures):
|
|
if not self.conversion_active: # Check for cancellation flag
|
|
self.log("Conversion cancelled by user.", "warning")
|
|
# Attempt to cancel remaining futures (may not stop running processes)
|
|
for f in futures:
|
|
f.cancel()
|
|
break # Exit the loop
|
|
|
|
file_path = futures[future]
|
|
processed_count += 1
|
|
try:
|
|
output_path = future.result() # Get result from convert_file function
|
|
if output_path:
|
|
success_count += 1
|
|
self.log(f"Success: {os.path.basename(file_path)} -> {os.path.basename(output_path)}", "success")
|
|
final_output_dir = os.path.dirname(output_path) # Store output dir
|
|
else:
|
|
# Failure was already logged in convert_file
|
|
self.failed_files.append(file_path)
|
|
|
|
except Exception as exc:
|
|
self.log(f"Error processing {os.path.basename(file_path)}: {exc}", "error")
|
|
self.failed_files.append(file_path)
|
|
|
|
# Update progress bar (needs to be done in main thread)
|
|
self.after(0, self.update_progress, processed_count, total_files)
|
|
|
|
# --- Conversion Finished ---
|
|
# Ensure UI update happens on the main thread
|
|
self.after(0, self.finish_conversion, success_count, total_files, final_output_dir)
|
|
|
|
|
|
def update_progress(self, current, total):
|
|
"""Updates the progress bar value."""
|
|
self.progress['value'] = current
|
|
# Optionally update status label with percentage
|
|
# percentage = int((current / total) * 100)
|
|
# self.update_status(f"Running... {percentage}%")
|
|
|
|
|
|
def finish_conversion(self, success_count, total_files, final_output_dir):
|
|
"""Called after all conversion threads complete."""
|
|
failed_count = len(self.failed_files)
|
|
self.log("="*30)
|
|
if not self.conversion_active and total_files > success_count + failed_count: # Check if cancelled early
|
|
self.log(f"Conversion Cancelled. Processed: {success_count + failed_count}/{total_files}", "warning")
|
|
else:
|
|
self.log(f"Conversion Complete. Success: {success_count}/{total_files}, Failed: {failed_count}")
|
|
|
|
self.set_ui_state(active=False) # Re-enable UI
|
|
self.update_status() # Update file counts
|
|
|
|
if failed_count > 0:
|
|
self.retry_button.config(state=tk.NORMAL)
|
|
messagebox.showwarning("Conversion Issues", f"{failed_count} file(s) failed to convert. Check the log for details.")
|
|
elif success_count > 0:
|
|
messagebox.showinfo("Conversion Complete", f"Successfully converted {success_count} file(s).")
|
|
|
|
# Auto-open folder if requested and successful conversions happened
|
|
if self.auto_open_folder.get() and final_output_dir and success_count > 0:
|
|
try:
|
|
self.log(f"Opening output folder: {final_output_dir}", "info")
|
|
open_folder = get_platform_open_command(final_output_dir)
|
|
open_folder()
|
|
except Exception as e:
|
|
self.log(f"Failed to open output folder: {e}", "error")
|
|
messagebox.showwarning("Open Folder Error", f"Could not automatically open the output folder:\n{final_output_dir}\nError: {e}")
|
|
|
|
|
|
def convert_file(self, svg_path_str):
|
|
"""
|
|
Converts a single SVG file using Inkscape via subprocess.
|
|
Returns the output path on success, None on failure.
|
|
"""
|
|
if not self.conversion_active: return None # Check for cancellation
|
|
|
|
svg_path = Path(svg_path_str)
|
|
base_name = svg_path.stem
|
|
source_dir = svg_path.parent
|
|
|
|
# Determine output directory
|
|
chosen_output_dir = self.output_dir.get()
|
|
if chosen_output_dir == "<Same as source>" or not chosen_output_dir:
|
|
output_dir = source_dir
|
|
else:
|
|
output_dir = Path(chosen_output_dir)
|
|
try:
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
except OSError as e:
|
|
self.log(f"Error creating output directory '{output_dir}': {e}. Saving to source directory instead.", "error")
|
|
output_dir = source_dir # Fallback
|
|
|
|
# Determine output format and filename
|
|
fmt = self.output_format.get().lower()
|
|
output_filename = output_dir / f"{base_name}.{fmt}"
|
|
|
|
# Build Inkscape command
|
|
cmd = [
|
|
self.inkscape_path,
|
|
f"--export-filename={str(output_filename)}",
|
|
f"--export-type={fmt}",
|
|
f"--export-dpi={self.dpi.get()}",
|
|
f"--export-background={self.background.get()}",
|
|
# f"--export-background-opacity=1", # Inkscape defaults to opaque if background is set
|
|
]
|
|
|
|
# Add optional dimensions
|
|
w = self.export_width.get()
|
|
h = self.export_height.get()
|
|
if w: cmd.append(f"--export-width={w}")
|
|
if h: cmd.append(f"--export-height={h}")
|
|
|
|
# Add JPEG quality if applicable
|
|
if fmt == "jpg" and 1 <= self.jpeg_quality.get() <= 100:
|
|
cmd.append(f"--export-jpeg-quality={self.jpeg_quality.get()}")
|
|
|
|
# Add the input file LAST
|
|
cmd.append(str(svg_path))
|
|
|
|
self.log(f"Processing: {svg_path.name} -> {output_filename.name}", "debug")
|
|
# self.log(f"Command: {' '.join(cmd)}", "debug") # For verbose debugging
|
|
|
|
try:
|
|
# Execute Inkscape
|
|
# Use timeout? Maybe long conversions are expected.
|
|
result = subprocess.run(cmd, capture_output=True, text=True, check=False, encoding='utf-8') # Added encoding
|
|
|
|
# Check result
|
|
if result.returncode == 0 and output_filename.exists() and output_filename.stat().st_size > 0:
|
|
# Success logged by the calling thread pool loop
|
|
return str(output_filename)
|
|
else:
|
|
error_msg = f"Failed: {svg_path.name}. Inkscape RC={result.returncode}."
|
|
if result.stderr:
|
|
error_msg += f" Error: {result.stderr.strip()[:200]}..." # Log first part of stderr
|
|
elif result.stdout: # Sometimes errors go to stdout
|
|
error_msg += f" Output: {result.stdout.strip()[:200]}..."
|
|
if not output_filename.exists():
|
|
error_msg += " Output file not created."
|
|
elif output_filename.stat().st_size == 0:
|
|
error_msg += " Output file is empty."
|
|
|
|
self.log(error_msg, "error")
|
|
return None
|
|
|
|
except FileNotFoundError:
|
|
self.log(f"Inkscape command not found at '{self.inkscape_path}'. Conversion failed for {svg_path.name}", "error")
|
|
# Potentially stop all conversions if Inkscape is missing mid-run?
|
|
self.conversion_active = False # Stop processing further files
|
|
return None
|
|
except Exception as e:
|
|
self.log(f"Unexpected error converting {svg_path.name}: {e}", "error")
|
|
return None
|
|
|
|
def retry_failed(self):
|
|
"""Attempts to reconvert files that failed previously."""
|
|
if not self.failed_files:
|
|
self.log("No failed files to retry.", "info")
|
|
return
|
|
|
|
self.log(f"Retrying {len(self.failed_files)} failed file(s)...")
|
|
files_to_retry = list(self.failed_files) # Copy the list
|
|
self.selected_files = files_to_retry # Set the main list to only the failed ones for this run
|
|
self.file_list.delete(0, tk.END) # Clear GUI list
|
|
for f in files_to_retry: # Re-populate GUI list
|
|
self.file_list.insert(tk.END, os.path.basename(f))
|
|
|
|
self.failed_files.clear() # Clear failed list before retry
|
|
self.retry_button.config(state=tk.DISABLED)
|
|
self.start_conversion() # Start the conversion process again
|
|
|
|
|
|
def load_settings(self):
|
|
"""Loads settings from the JSON file."""
|
|
try:
|
|
settings_path = Path(SETTINGS_FILE)
|
|
if settings_path.exists():
|
|
with open(settings_path, 'r') as f:
|
|
settings = json.load(f)
|
|
self.dpi.set(settings.get('dpi', 150))
|
|
self.background.set(settings.get('background', '#ffffff'))
|
|
self.output_format.set(settings.get('output_format', 'png'))
|
|
self.output_dir.set(settings.get('output_dir', '<Same as source>'))
|
|
self.export_width.set(settings.get('export_width', ''))
|
|
self.export_height.set(settings.get('export_height', ''))
|
|
self.jpeg_quality.set(settings.get('jpeg_quality', 90))
|
|
self.auto_open_folder.set(settings.get('auto_open_folder', False))
|
|
self.concurrent_tasks.set(settings.get('concurrent_tasks', MAX_CONCURRENT_TASKS))
|
|
self.log("Settings loaded.", "debug")
|
|
else:
|
|
self.log("Settings file not found, using defaults.", "debug")
|
|
except Exception as e:
|
|
self.log(f"Error loading settings: {e}", "error")
|
|
|
|
|
|
def save_settings(self):
|
|
"""Saves current settings to the JSON file."""
|
|
settings = {
|
|
'dpi': self.dpi.get(),
|
|
'background': self.background.get(),
|
|
'output_format': self.output_format.get(),
|
|
'output_dir': self.output_dir.get(),
|
|
'export_width': self.export_width.get(),
|
|
'export_height': self.export_height.get(),
|
|
'jpeg_quality': self.jpeg_quality.get(),
|
|
'auto_open_folder': self.auto_open_folder.get(),
|
|
'concurrent_tasks': self.concurrent_tasks.get(),
|
|
}
|
|
try:
|
|
settings_path = Path(SETTINGS_FILE)
|
|
with open(settings_path, 'w') as f:
|
|
json.dump(settings, f, indent=4)
|
|
self.log("Settings saved.", "debug")
|
|
except Exception as e:
|
|
self.log(f"Error saving settings: {e}", "error")
|
|
|
|
def on_closing(self):
|
|
"""Handles window close event."""
|
|
if self.conversion_active:
|
|
if messagebox.askyesno("Exit Confirmation", "Conversion in progress. Are you sure you want to exit?"):
|
|
self.conversion_active = False # Signal cancellation
|
|
self.save_settings()
|
|
self.destroy()
|
|
else:
|
|
return # Don't close
|
|
else:
|
|
self.save_settings()
|
|
self.destroy()
|
|
|
|
|
|
# --- Main Execution ---
|
|
if __name__ == "__main__":
|
|
# Optional: Set a theme for a more modern look (if available)
|
|
# try:
|
|
# style = ttk.Style()
|
|
# available_themes = style.theme_names() # ('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
|
|
# if 'clam' in available_themes: # 'clam' often looks better than default
|
|
# style.theme_use('clam')
|
|
# elif 'vista' in available_themes: # Good on Windows
|
|
# style.theme_use('vista')
|
|
# except Exception:
|
|
# pass # Ignore theme setting errors
|
|
|
|
app = SVGtoPNGConverter()
|
|
app.mainloop() |