Files
CNC-tools/Restore.py
T

228 lines
6.2 KiB
Python

#!/usr/bin/env python3
import os
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import shutil
import ctypes
import string
import configparser
# ============================================================
# CONFIG:
config = configparser.ConfigParser()
config.read(r"C:\ProgramData\Program-Search\config.ini")
SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"]
TRASH_DIR = config["Paths"]["TRASH_DIR"]
EDITOR_ENABLED = config.getboolean("Features", "EDITOR_ENABLED")
AUTO_CLOSE_SECONDS = config.getint("Features", "AUTO_CLOSE_SECONDS")
# ============================================================
os.makedirs(TRASH_DIR, exist_ok=True)
def popup_search_input():
win = tk.Toplevel()
win.title("Search")
win.geometry("400x150")
tk.Label(win, text="Enter part number or name:", font=("Consolas", 12)).pack(pady=10)
entry = tk.Entry(win, font=("Consolas", 12))
entry.pack(pady=5)
entry.focus_set()
result = {"value": None}
def submit():
result["value"] = entry.get().strip().lower()
win.destroy()
tk.Button(win, text="Search", command=submit).pack(pady=10)
win.wait_window()
return result["value"]
def search_files(term):
matches = []
for root, dirs, files in os.walk(TRASH_DIR):
for fname in files:
path = os.path.join(root, fname)
fname_lower = fname.lower()
filename_match = term in fname_lower
contents_match = False
try:
with open(path, "r", errors="ignore") as f:
if term in f.read().lower():
contents_match = True
except:
pass
if filename_match or contents_match:
matches.append(path)
return matches
def popup_results_list(matches):
win = tk.Toplevel()
win.title("Matches Found")
win.geometry("600x400")
tk.Label(win, text="Select files to preview:", font=("Consolas", 12)).pack(pady=10)
lb = tk.Listbox(win, selectmode=tk.MULTIPLE, font=("Consolas", 11))
lb.pack(expand=True, fill="both")
for m in matches:
lb.insert(tk.END, m)
result = {"selected": []}
def select_all():
lb.select_set(0, tk.END)
def submit():
sel = lb.curselection()
result["selected"] = [matches[i] for i in sel]
win.destroy()
tk.Button(win, text="Open Selected", command=submit).pack(padx=10)
tk.Button(win, text="Select All", command=select_all).pack(padx=10)
win.wait_window()
return result["selected"]
def popup_file_preview(path, on_close_callback):
win = tk.Toplevel()
win.title(path)
win.geometry("900x700")
box = scrolledtext.ScrolledText(win, wrap=tk.WORD, font=("Consolas", 11))
box.pack(expand=True, fill="both")
try:
with open(path, "r", errors="ignore") as f:
original_text = f.read()
box.insert(tk.END, original_text)
box.edit_modified(False)
except Exception as e:
original_text = ""
box.insert(tk.END, f"Error reading file:\n{e}")
modified = {"changed": False}
def mark_modified(event=None):
if box.edit_modified():
modified["changed"] = True
box.edit_modified(False)
if EDITOR_ENABLED:
box.bind("<<Modified>>", mark_modified)
else:
box.configure(state="disabled")
frame = tk.Frame(win)
frame.pack(fill="x", pady=10)
def save_file():
try:
with open(path, "w", errors="ignore") as f:
f.write(box.get("1.0", tk.END))
modified["changed"] = False
messagebox.showinfo("Saved", f"File saved:\n{path}")
except Exception as e:
messagebox.showerror("Save Error", str(e))
if EDITOR_ENABLED:
tk.Button(frame, text="Save", fg="green", command=save_file).pack(side="left", padx=10)
def restore_file():
if EDITOR_ENABLED and modified["changed"]:
ask = messagebox.askyesno(
"Unsaved Changes",
"You have unsaved changes.\nSave before restoring?"
)
if ask:
save_file()
try:
rel_path = os.path.relpath(path, TRASH_DIR)
dest_path = os.path.join(SEARCH_ROOT, rel_path)
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
shutil.move(path, dest_path)
messagebox.showinfo("Restored", f"File restored to:\n{dest_path}")
win.destroy()
on_close_callback()
except Exception as e:
messagebox.showerror("Restore Error", str(e))
def close():
if EDITOR_ENABLED and modified["changed"]:
ask = messagebox.askyesno(
"Unsaved Changes",
"You have unsaved changes.\nSave before closing?"
)
if ask:
save_file()
win.destroy()
on_close_callback()
def auto_close():
if win.winfo_exists():
win.destroy()
on_close_callback()
win.protocol("WM_DELETE_WINDOW", close)
win.after(AUTO_CLOSE_SECONDS * 1000, auto_close)
tk.Button(frame, text="Restore File", fg="blue", command=restore_file).pack(side="left", padx=10)
tk.Button(frame, text="Close", command=close).pack(side="right", padx=10)
def main():
root = tk.Tk()
root.withdraw()
search_term = popup_search_input()
if not search_term:
root.destroy()
return
matches = search_files(search_term)
if not matches:
messagebox.showinfo("No Results", "No matching files found.")
root.destroy()
return
selected = popup_results_list(matches)
if not selected:
root.destroy()
return
open_windows = {"count": len(selected)}
def window_closed():
open_windows["count"] -= 1
if open_windows["count"] == 0:
root.destroy()
for path in selected:
popup_file_preview(path, window_closed)
root.mainloop()
if __name__ == "__main__":
main()