updated programs and added FileManager

This commit is contained in:
CosmicKillsSouls committed 2026-11-19 13:31:15 -06:00
1 parent 55177b1444
commit 4c994a28f0
7 files changed
+682 -213

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
__pycache__/
*.py[cod]
+1 -1
View File
@@ -38,6 +38,6 @@ PREVIEW_WIDTH=1200
PREVIEW_HEIGHT=900 PREVIEW_HEIGHT=900
PREVIEW_FONT_SIZE=24 PREVIEW_FONT_SIZE=24
ERROR_FONT_SIZE=11
ERROR_WIDTH=400 ERROR_WIDTH=400
ERROR_HEIGHT=100 ERROR_HEIGHT=100
ERROR_FONT_SIZE=20
+380
View File
@@ -0,0 +1,380 @@
import os
import re
import csv
import hashlib
import tkinter as tk
from pathlib import Path
# ============================================================
# GUI
# ============================================================
def select_folder():
return input("Enter folder path: ").strip().strip("'\"")
# ============================================================
# Helper Functions
# ============================================================
def normalize_nc_content(text):
output = []
for line in text.splitlines():
line = line.upper()
# Remove comments
line = re.sub(r"\(.*?\)", "", line)
line = re.sub(r";.*", "", line)
# Remove tool numbers
line = re.sub(r"\bT\d+\b", "", line)
# Remove spindle speeds
line = re.sub(r"\bS[-+]?\d*\.?\d+\b", "", line)
line = line.strip()
if line:
output.append(line)
return "\n".join(output)
def calculate_file_hash(file_path):
sha = hashlib.sha256()
with open(file_path, "rb") as f:
while True:
chunk = f.read(8192)
if not chunk:
break
sha.update(chunk)
return sha.hexdigest()
# ============================================================
# Geometry Comparison
# ============================================================
AXIS_PATTERN = re.compile(r"([XYZIJKR])([-+]?\d*\.?\d+)")
COMMAND_PATTERN = re.compile(r"\b(G\d+|M\d+)\b")
def extract_toolpath(file_path):
motions = []
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
for raw_line in f:
line = normalize_nc_content(raw_line)
if not line:
continue
commands = COMMAND_PATTERN.findall(line)
axes = {
axis: float(value)
for axis, value in AXIS_PATTERN.findall(line)
}
if commands or axes:
motions.append({
"commands": tuple(commands),
"axes": axes
})
return motions
def compare_program_structure(file1, file2, tolerance=0.005):
path1 = extract_toolpath(file1)
path2 = extract_toolpath(file2)
if len(path1) != len(path2):
return False, None
max_diff = 0
for move1, move2 in zip(path1, path2):
if move1["commands"] != move2["commands"]:
return False, None
axes = set(move1["axes"]) | set(move2["axes"])
for axis in axes:
if axis not in move1["axes"]:
return False, None
if axis not in move2["axes"]:
return False, None
diff = abs(
move1["axes"][axis]
- move2["axes"][axis]
)
max_diff = max(max_diff, diff)
if diff > tolerance:
return False, max_diff
return True, max_diff
# ============================================================
# Extension Normalization
# ============================================================
def normalize_extensions(root_folder):
root_path = Path(root_folder)
if not root_path.exists():
raise FileNotFoundError(root_folder)
for file in root_path.rglob("*"):
if not file.is_file():
continue
suffix = file.suffix.lower()
if suffix == "":
new_file = file.with_name(
file.name + ".txt"
)
elif suffix == ".nc":
new_file = file.with_suffix(".txt")
elif suffix == ".txt":
if file.suffix == ".txt":
continue
new_file = file.with_suffix(".txt")
else:
continue
try:
file.rename(new_file)
except Exception as e:
print(f"Failed: {file}")
print(e)
print("Extension normalization complete.")
# ============================================================
# Program Splitting
# ============================================================
def split_file_by_key(input_file, output_dir):
os.makedirs(output_dir, exist_ok=True)
current_output = None
with open(input_file, "r", encoding="utf-8", errors="ignore") as infile:
for line in infile:
if line.startswith("O"):
if current_output:
current_output.write("%\n")
current_output.close()
filename = line[:6].strip()
output_path = os.path.join(output_dir, f"{filename}.txt")
current_output = open(output_path, "w", encoding="utf-8")
current_output.write("%\n")
if current_output:
current_output.write(line)
if current_output:
current_output.write("%\n")
current_output.close()
print(f"Finished: {input_file}")
# ============================================================
# Exact Duplicate Removal
# ============================================================
def remove_exact_duplicates(root_dir):
known_hashes = {}
deleted = []
for file in Path(root_dir).rglob("*.txt"):
file_hash = calculate_file_hash(file)
if file_hash in known_hashes:
print(f"Removing exact duplicate: {file}")
file.unlink()
deleted.append(file)
else:
known_hashes[file_hash] = file
print(
f"Removed {len(deleted)} exact duplicates."
)
# ============================================================
# Geometry Duplicate Removal
# ============================================================
def remove_geometry_duplicates(root_dir, tolerance=0.005):
files = list(Path(root_dir).rglob("*.txt"))
removed = set()
for i in range(len(files)):
if files[i] in removed:
continue
for j in range(i + 1, len(files)):
if files[j] in removed:
continue
duplicate, max_diff = compare_program_structure(files[i], files[j], tolerance)
if duplicate:
print(
f"Removing geometric duplicate:\n"
f" Keep: {files[i].name}\n"
f" Delete: {files[j].name}\n"
f" Max Delta: {max_diff:.5f}"
)
files[j].unlink()
removed.add(files[j])
print(
f"Removed {len(removed)} geometry duplicates."
)
# ============================================================
# Similarity Report
# ============================================================
def generate_similarity_report(
root_dir,
tolerance=0.005,
output_csv="similarity_report.csv"
):
files = list(Path(root_dir).rglob("*.txt"))
with open(output_csv, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow([
"File1",
"File2",
"Duplicate",
"MaxCoordinateDelta"
])
for i in range(len(files)):
for j in range(i + 1, len(files)):
duplicate, delta = compare_program_structure(files[i], files[j], tolerance)
writer.writerow([
files[i].name,
files[j].name,
duplicate,
delta
])
print(
f"Similarity report written to {output_csv}"
)
# ============================================================
# Main
# ============================================================
if __name__ == "__main__":
input_dir = select_folder()
if not os.path.isdir(input_dir):
print("Invalid folder.")
raise SystemExit(1)
normalize_extensions(input_dir)
master_output_dir = os.path.join(input_dir, "Split_Output")
os.makedirs(master_output_dir, exist_ok=True)
for root, dirs, files in os.walk(input_dir):
if os.path.abspath(root).startswith(os.path.abspath(master_output_dir)):
continue
for filename in files:
if not filename.lower().endswith(".pgm"):
continue
input_file = os.path.join(root, filename)
program_output_dir = os.path.join(master_output_dir, os.path.splitext(filename)[0])
split_file_by_key(input_file, program_output_dir)
remove_exact_duplicates(master_output_dir)
remove_geometry_duplicates(master_output_dir, tolerance=0.005)
generate_similarity_report(master_output_dir, tolerance=0.005)
print("All files processed.")
+98 -54
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import sys
import pickle import pickle
import configparser import configparser
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
@@ -9,94 +10,137 @@ from concurrent.futures import ThreadPoolExecutor
# CONFIG # CONFIG
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(r"C:\ProgramData\Program-Search\config.ini") config.read(r"C:\ProgramData\Program-Search\config.ini")
# PATHS
SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"] SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"]
INDEX_FILE = config["Paths"]["INDEX_FILE"] INDEX_FILE = config["Paths"]["INDEX_FILE"]
WORKER_COUNT = config.getint("Features", "WORKER_COUNT") # FEATURES
WORKER_COUNT = config.getint("Features", "WORKER_COUNT", fallback=8)
# ============================================================ # ============================================================
SEARCH_INDEX = {}
def read_file(path, mtime, size):
def read_file(path):
try: try:
with open(path, "r", errors="ignore") as f: with open(path, "r", errors="ignore") as f:
return ( return (
path, path,
{ {
"filename": os.path.basename(path).lower(), "filename": os.path.basename(path).lower(),
"content": f.read().lower() "content": f.read().lower(),
"mtime": mtime,
"size": size,
} }
) )
except Exception: except Exception:
return None return None
def build_index(): def scan_files(root):
"""Return {path: (mtime, size)} for every file under root."""
found = {}
stack = [root]
files = [] while stack:
current = stack.pop()
try:
with os.scandir(current) as it:
for entry in it:
try:
if entry.is_dir(follow_symlinks=False):
stack.append(entry.path)
elif entry.is_file():
st = entry.stat()
found[entry.path] = (st.st_mtime, st.st_size)
except OSError:
pass
except OSError:
pass
print("Collecting files...") return found
for root, dirs, filenames in os.walk(SEARCH_ROOT):
for filename in filenames: def load_index():
files.append( try:
os.path.join(root, filename) with open(INDEX_FILE, "rb") as f:
return pickle.load(f)
except Exception:
return {}
def save_index(index):
os.makedirs(os.path.dirname(INDEX_FILE), exist_ok=True)
# Write to a temp file first so a crash never leaves a corrupt index.
tmp_file = INDEX_FILE + ".tmp"
with open(tmp_file, "wb") as f:
pickle.dump(index, f, protocol=pickle.HIGHEST_PROTOCOL)
os.replace(tmp_file, INDEX_FILE)
def update_index(index, verbose=False):
"""
Bring index up to date with SEARCH_ROOT in place.
Only new or changed files are re-read; deleted files are removed.
Returns True if anything changed.
"""
if verbose:
print("Scanning files...")
on_disk = scan_files(SEARCH_ROOT)
removed = [p for p in index if p not in on_disk]
for p in removed:
del index[p]
to_read = []
for path, (mtime, size) in on_disk.items():
data = index.get(path)
if (
data is None
or data.get("mtime") != mtime
or data.get("size") != size
):
to_read.append((path, mtime, size))
if verbose:
print(
f"Found {len(on_disk)} files: "
f"{len(to_read)} new/changed, {len(removed)} removed"
) )
print(f"Found {len(files)} files")
print("Building index...\n")
completed = 0 completed = 0
with ThreadPoolExecutor(max_workers=WORKER_COUNT) as executor:
with ThreadPoolExecutor( for result in executor.map(lambda a: read_file(*a), to_read):
max_workers=WORKER_COUNT
) as executor:
for result in executor.map(
read_file,
files
):
completed += 1 completed += 1
if verbose and completed % 100 == 0:
if completed % 100 == 0: print(f"{completed}/{len(to_read)}")
print(
f"{completed}/{len(files)}"
)
if result: if result:
path, data = result path, data = result
SEARCH_INDEX[path] = data index[path] = data
return bool(removed or to_read)
def build_index(full=False):
index = {} if full else load_index()
changed = update_index(index, verbose=True)
if not changed and os.path.exists(INDEX_FILE):
print("\nIndex already up to date.")
return
print("\nSaving index...") print("\nSaving index...")
save_index(index)
os.makedirs( size_mb = os.path.getsize(INDEX_FILE) / 1024 / 1024
os.path.dirname(INDEX_FILE),
exist_ok=True
)
with open(INDEX_FILE, "wb") as f:
pickle.dump(
SEARCH_INDEX,
f,
protocol=pickle.HIGHEST_PROTOCOL
)
size_mb = (
os.path.getsize(INDEX_FILE)
/ 1024
/ 1024
)
print( print(
f"Index saved:\n" f"Index saved:\n"
f"{INDEX_FILE}\n" f"{INDEX_FILE}\n"
f"{len(SEARCH_INDEX)} files\n" f"{len(index)} files\n"
f"{size_mb:.2f} MB" f"{size_mb:.2f} MB"
) )
if __name__ == "__main__": if __name__ == "__main__":
build_index() # Run with --full to rebuild the index from scratch.
build_index(full="--full" in sys.argv)
-64
View File
@@ -1,64 +0,0 @@
import os
def split_file_by_key(input_file, output_dir):
os.makedirs(output_dir, exist_ok=True)
current_output = None
key = "O"
with open(input_file, "r", encoding="utf-8") as infile:
for line in infile:
if line.startswith(key):
if current_output:
current_output.write("%\n")
current_output.close()
filename = line[:6].strip()
output_path = os.path.join(output_dir, f"{filename}.txt")
current_output = open(output_path, "w", encoding="utf-8")
current_output.write("%\n")
if current_output:
current_output.write(line)
if current_output:
current_output.write("%\n")
current_output.close()
print(f"Finished: {input_file}")
if __name__ == "__main__":
input_dir = input("Input folder: ").strip().strip("'\"")
if not os.path.isdir(input_dir):
print(f"Folder not found: {input_dir}")
exit(1)
master_output_dir = os.path.join(input_dir, "Split_Output")
os.makedirs(master_output_dir, exist_ok=True)
for root, dirs, files in os.walk(input_dir):
if os.path.abspath(root).startswith(os.path.abspath(master_output_dir)):
continue
for filename in files:
if not filename.lower().endswith(".pgm"):
continue
input_file = os.path.join(root, filename)
program_output_dir = os.path.join(
master_output_dir,
os.path.splitext(filename)[0]
)
split_file_by_key(
input_file,
program_output_dir
)
print("All files processed.")
+163 -65
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import tkinter as tk import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext from tkinter import scrolledtext
import shutil import shutil
import ctypes import ctypes
import string import string
@@ -11,52 +11,155 @@ import configparser
# CONFIG: # CONFIG:
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(r"C:\ProgramData\Program-Search\config.ini") config.read(r"C:\ProgramData\Program-Search\config.ini")
# PATHS
SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"] SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"]
TRASH_DIR = config["Paths"]["TRASH_DIR"] TRASH_DIR = config["Paths"]["TRASH_DIR"]
EDITOR_ENABLED = config.getboolean("Features", "EDITOR_ENABLED") # FEATURES
AUTO_CLOSE_SECONDS = config.getint("Features", "AUTO_CLOSE_SECONDS") EDITOR_ENABLED = config.getboolean("Features", "EDITOR_ENABLED", fallback=True)
# ============================================================ AUTO_CLOSE_SECONDS = config.getint("Features", "AUTO_CLOSE_SECONDS", fallback=30)
# UI
TEXT_FONT = config.get("UI", "TEXT-font", fallback="Consolas")
SEARCH_WIDTH = config.getint("UI", "SEARCH_WIDTH", fallback=400)
SEARCH_HEIGHT = config.getint("UI", "SEARCH_HEIGHT", fallback=150)
SEARCH_FONT_SIZE = config.getint("UI", "SEARCH_FONT_SIZE", fallback=12)
RESULTS_WIDTH = config.getint("UI", "RESULTS_WIDTH", fallback=1000)
RESULTS_HEIGHT = config.getint("UI", "RESULTS_HEIGHT", fallback=700)
RESULTS_FONT_SIZE = config.getint("UI", "RESULTS_FONT_SIZE", fallback=11)
PREVIEW_WIDTH = config.getint("UI", "PREVIEW_WIDTH", fallback=1200)
PREVIEW_HEIGHT = config.getint("UI", "PREVIEW_HEIGHT", fallback=900)
PREVIEW_FONT_SIZE = config.getint("UI", "PREVIEW_FONT_SIZE", fallback=24)
ERROR_WIDTH = config.getint("UI", "ERROR_WIDTH", fallback=400)
ERROR_HEIGHT = config.getint("UI", "ERROR_HEIGHT", fallback=100)
ERROR_FONT_SIZE = config.getint("UI", "ERROR_FONT_SIZE", fallback=11)
# BUTTONS
BUTTON_SIZE_SEARCH = config.getint("Buttons", "BUTTON_SIZE_SEARCH", fallback=15)
BUTTON_SIZE_OPEN = config.getint("Buttons", "BUTTON_SIZE_OPEN", fallback=15)
BUTTON_SIZE_SELECT_ALL = config.getint("Buttons", "BUTTON_SIZE_SELECT_ALL", fallback=15)
BUTTON_SIZE_SAVE = config.getint("Buttons", "BUTTON_SIZE_SAVE", fallback=15)
BUTTON_SIZE_COPY = config.getint("Buttons", "BUTTON_SIZE_COPY", fallback=15)
BUTTON_SIZE_TRASH = config.getint("Buttons", "BUTTON_SIZE_TRASH", fallback=15)
BUTTON_SIZE_CLOSE = config.getint("Buttons", "BUTTON_SIZE_CLOSE", fallback=15)
BUTTON_SIZE_MESSAGE = config.getint("Buttons", "BUTTON_SIZE_MESSAGE", fallback=15)
BUTTON_SIZE_YES_NO = config.getint("Buttons", "BUTTON_SIZE_YES_NO", fallback=15)
# ============================================================
os.makedirs(TRASH_DIR, exist_ok=True) os.makedirs(TRASH_DIR, exist_ok=True)
def center_window(win, width, height):
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()
x = int((screen_width / 2) - (width / 2))
y = int((screen_height / 2) - (height / 2))
win.geometry(f"{width}x{height}+{x}+{y}")
def custom_message(title, message):
win = tk.Toplevel()
win.title(title)
win.protocol("WM_DELETE_WINDOW", win.destroy)
tk.Label(
win,
text=message,
font=(TEXT_FONT, ERROR_FONT_SIZE),
wraplength=ERROR_WIDTH - 30,
justify="center"
).pack(padx=15, pady=15)
tk.Button(win, text="OK", font=(TEXT_FONT, BUTTON_SIZE_MESSAGE), command=win.destroy).pack(pady=10)
win.bind("<Return>", lambda e: win.destroy())
center_window(win, ERROR_WIDTH, ERROR_HEIGHT)
win.lift()
win.focus_force()
win.transient()
win.grab_set()
win.update()
win.wait_window()
def custom_yesno(title, message):
win = tk.Toplevel()
win.title(title)
result = {"value": False}
tk.Label(
win,
text=message,
font=(TEXT_FONT, ERROR_FONT_SIZE),
wraplength=ERROR_WIDTH - 30,
justify="center"
).pack(padx=15, pady=15)
button_frame = tk.Frame(win)
button_frame.pack(pady=10)
def yes():
result["value"] = True
win.destroy()
def no():
result["value"] = False
win.destroy()
tk.Button(button_frame, text="Yes", width=BUTTON_SIZE_YES_NO, font=(TEXT_FONT, BUTTON_SIZE_YES_NO), command=yes).pack(side="left", padx=10)
tk.Button(button_frame, text="No", width=BUTTON_SIZE_YES_NO, font=(TEXT_FONT, BUTTON_SIZE_YES_NO), command=no).pack(side="left", padx=10)
win.protocol("WM_DELETE_WINDOW", no)
center_window(win, ERROR_WIDTH, ERROR_HEIGHT)
win.lift()
win.focus_force()
win.grab_set()
win.wait_window()
return result["value"]
def popup_search_input(): def popup_search_input():
win = tk.Toplevel() win = tk.Toplevel()
win.title("Search") win.title("Search")
win.geometry("400x150") win.geometry(f"{SEARCH_WIDTH}x{SEARCH_HEIGHT}")
tk.Label(win, text="Enter part number or name:", font=("Consolas", 12)).pack(pady=10) tk.Label(win, text="Enter part number or name:", font=(TEXT_FONT, SEARCH_FONT_SIZE)).pack(pady=10)
entry = tk.Entry(win, font=("Consolas", 12)) entry = tk.Entry(win, font=(TEXT_FONT, SEARCH_FONT_SIZE))
entry.pack(pady=5) entry.pack(pady=5)
entry.focus_set() win.lift()
win.attributes("-topmost", True)
result = {"value": None} result = {"value": None, "force_close": False}
def submit(): def submit():
result["value"] = entry.get().strip().lower() result["value"] = entry.get().strip().lower()
win.destroy() win.destroy()
tk.Button(win, text="Search", command=submit).pack(pady=10) def force_close():
result["force_close"] = True
win.destroy()
entry.bind("<Return>", lambda e: submit())
tk.Button(win, text="Search", font=(TEXT_FONT, BUTTON_SIZE_SEARCH), command=submit).pack(pady=10)
center_window(win, SEARCH_WIDTH, SEARCH_HEIGHT)
win.protocol("WM_DELETE_WINDOW", force_close)
win.after(50, lambda: (entry.focus_set(), entry.icursor(tk.END)))
win.after(100, lambda: win.attributes("-topmost", False))
win.wait_window() win.wait_window()
return result["value"] return result["value"]
def search_files(term): def search_files(term):
matches = [] matches = []
term_lower = term.lower()
for root, dirs, files in os.walk(TRASH_DIR): for root, dirs, files in os.walk(TRASH_DIR):
for fname in files: for fname in files:
path = os.path.join(root, fname) path = os.path.join(root, fname)
fname_lower = fname.lower()
filename_match = term in fname_lower filename_match = term_lower in fname.lower()
contents_match = False contents_match = False
try: try:
with open(path, "r", errors="ignore") as f: with open(path, "r", errors="ignore") as f:
if term in f.read().lower(): if term_lower in f.read().lower():
contents_match = True contents_match = True
except: except Exception:
pass pass
if filename_match or contents_match: if filename_match or contents_match:
@@ -64,43 +167,55 @@ def search_files(term):
return matches return matches
def popup_results_list(matches): def popup_results_list(matches):
win = tk.Toplevel() win = tk.Toplevel()
win.title("Matches Found") win.title("Matches Found")
win.geometry("600x400") win.geometry(f"{RESULTS_WIDTH}x{RESULTS_HEIGHT}")
tk.Label(win, text="Select files to preview:", font=("Consolas", 12)).pack(pady=10) tk.Label(win, text="Select files to preview:", font=(TEXT_FONT, RESULTS_FONT_SIZE)).pack(pady=10)
lb = tk.Listbox(win, selectmode=tk.MULTIPLE, font=("Consolas", 11)) lb = tk.Listbox(win, selectmode=tk.MULTIPLE, font=(TEXT_FONT, RESULTS_FONT_SIZE))
lb.pack(expand=True, fill="both") lb.pack(expand=True, fill="both")
lb.bind("<Return>", lambda e: submit())
for m in matches: for m in matches:
lb.insert(tk.END, m) parent = os.path.basename(os.path.dirname(m))
filename = os.path.basename(m)
display = f"{parent}\\{filename}"
lb.insert(tk.END, display)
result = {"selected": []} result = {"selected": []}
def select_all(): def select_all():
lb.select_set(0, tk.END) lb.select_set(0, tk.END)
def submit(): def submit():
sel = lb.curselection() sel = lb.curselection()
if not sel:
custom_message("No Selection", "Please select at least 1 file.")
return
result["selected"] = [matches[i] for i in sel] result["selected"] = [matches[i] for i in sel]
win.destroy() win.destroy()
tk.Button(win, text="Open Selected", command=submit).pack(padx=10) tk.Button(win, text="Open Selected", font=(TEXT_FONT, BUTTON_SIZE_OPEN), command=submit).pack(padx=10)
tk.Button(win, text="Select All", command=select_all).pack(padx=10) tk.Button(win, text="Select All", font=(TEXT_FONT, BUTTON_SIZE_SELECT_ALL), command=select_all).pack(padx=10)
center_window(win, RESULTS_WIDTH, RESULTS_HEIGHT)
win.lift()
win.focus_force()
win.wait_window() win.wait_window()
return result["selected"] return result["selected"]
def popup_file_preview(path, on_close_callback): def popup_file_preview(path, on_close_callback):
win = tk.Toplevel() win = tk.Toplevel()
win.title(path) height = min(PREVIEW_HEIGHT, win.winfo_screenheight() - 80)
win.geometry("900x700") win.geometry(f"{PREVIEW_WIDTH}x{height}")
box = scrolledtext.ScrolledText(win, wrap=tk.WORD, font=("Consolas", 11)) frame = tk.Frame(win)
box.pack(expand=True, fill="both") frame.pack(side="bottom", fill="x")
box = scrolledtext.ScrolledText(win, wrap=tk.WORD, font=(TEXT_FONT, PREVIEW_FONT_SIZE))
box.pack(expand=True, fill="both", padx=5, pady=10)
try: try:
with open(path, "r", errors="ignore") as f: with open(path, "r", errors="ignore") as f:
@@ -123,54 +238,38 @@ def popup_file_preview(path, on_close_callback):
else: else:
box.configure(state="disabled") box.configure(state="disabled")
frame = tk.Frame(win)
frame.pack(fill="x", pady=10)
def save_file(): def save_file():
try: try:
with open(path, "w", errors="ignore") as f: with open(path, "w", errors="ignore") as f:
f.write(box.get("1.0", tk.END)) f.write(box.get("1.0", tk.END))
modified["changed"] = False modified["changed"] = False
messagebox.showinfo("Saved", f"File saved:\n{path}") custom_message("Saved", f"File saved:\n{path}")
except Exception as e: except Exception as e:
messagebox.showerror("Save Error", str(e)) custom_message("Save Error", str(e))
if EDITOR_ENABLED: if EDITOR_ENABLED:
tk.Button(frame, text="Save", fg="green", command=save_file).pack(side="left", padx=10) tk.Button(frame, text="Save", fg="green", font=(TEXT_FONT, BUTTON_SIZE_SAVE), command=save_file).pack(side="left", padx=10)
def restore_file(): def restore_file():
if EDITOR_ENABLED and modified["changed"]: if EDITOR_ENABLED and modified["changed"]:
ask = messagebox.askyesno( ask = custom_yesno("Unsaved Changes", "You have unsaved changes.\nSave before restoring?")
"Unsaved Changes",
"You have unsaved changes.\nSave before restoring?"
)
if ask: if ask:
save_file() save_file()
try: try:
rel_path = os.path.relpath(path, TRASH_DIR) rel_path = os.path.relpath(path, TRASH_DIR)
dest_path = os.path.join(SEARCH_ROOT, rel_path) dest_path = os.path.join(SEARCH_ROOT, rel_path)
os.makedirs(os.path.dirname(dest_path), exist_ok=True) os.makedirs(os.path.dirname(dest_path), exist_ok=True)
shutil.move(path, dest_path) shutil.move(path, dest_path)
custom_message("Restored", f"File restored to:\n{dest_path}")
messagebox.showinfo("Restored", f"File restored to:\n{dest_path}")
win.destroy()
on_close_callback()
except Exception as e: except Exception as e:
messagebox.showerror("Restore Error", str(e)) custom_message("Restore Error", str(e))
def close(): def close():
if EDITOR_ENABLED and modified["changed"]: if EDITOR_ENABLED and modified["changed"]:
ask = messagebox.askyesno( ask = custom_yesno("Unsaved Changes", "You have unsaved changes.\nSave before closing?")
"Unsaved Changes",
"You have unsaved changes.\nSave before closing?"
)
if ask: if ask:
save_file() save_file()
win.destroy() win.destroy()
on_close_callback() on_close_callback()
@@ -182,33 +281,34 @@ def popup_file_preview(path, on_close_callback):
win.protocol("WM_DELETE_WINDOW", close) win.protocol("WM_DELETE_WINDOW", close)
win.after(AUTO_CLOSE_SECONDS * 1000, auto_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="Restore File", fg="blue", font=(TEXT_FONT, BUTTON_SIZE_CLOSE), command=restore_file).pack(side="left", padx=10)
tk.Button(frame, text="Close", font=(TEXT_FONT, BUTTON_SIZE_CLOSE), command=close).pack(side="right", padx=10)
tk.Button(frame, text="Close", command=close).pack(side="right", padx=10)
def main(): def main():
root = tk.Tk() root = tk.Tk()
root.withdraw() root.withdraw()
search_term = popup_search_input() while True:
result = popup_search_input()
search_term = result["value"]
if result["force_close"]:
root.destroy()
return
if not search_term: if not search_term:
root.destroy() custom_message("Invalid Search", "Please enter a search term.")
return continue
matches = search_files(search_term) matches = search_files(search_term)
if not matches: if not matches:
messagebox.showinfo("No Results", "No matching files found.") custom_message("No Results", "No matching files found.")
root.destroy() continue
return break
selected = popup_results_list(matches) selected = popup_results_list(matches)
if not selected: if not selected:
root.destroy() root.destroy()
return return
open_windows = {"count": len(selected)} open_windows = {"count": len(selected)}
def window_closed(): def window_closed():
@@ -216,12 +316,10 @@ def main():
if open_windows["count"] == 0: if open_windows["count"] == 0:
root.destroy() root.destroy()
for path in selected: for path in selected:
popup_file_preview(path, window_closed) popup_file_preview(path, window_closed)
root.mainloop() root.mainloop()
if __name__ == "__main__": if __name__ == "__main__":
main() main()
+38 -29
View File
@@ -2,51 +2,60 @@
import os import os
import tkinter as tk import tkinter as tk
from tkinter import scrolledtext from tkinter import scrolledtext
import pickle
import shutil import shutil
import ctypes import ctypes
import string import string
import configparser import configparser
import Indexer
# ============================================================ # ============================================================
# CONFIG: # CONFIG:
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(r"C:\ProgramData\Program-Search\config.ini") config.read(r"C:\ProgramData\Program-Search\config.ini")
# PATHS
SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"] SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"]
TRASH_DIR = config["Paths"]["TRASH_DIR"] TRASH_DIR = config["Paths"]["TRASH_DIR"]
INDEX_FILE = config["Paths"]["INDEX_FILE"] INDEX_FILE = config["Paths"]["INDEX_FILE"]
TRASH_ENABLED = config.getboolean("Features", "TRASH_ENABLED") # FEATURES
EDITOR_ENABLED = config.getboolean("Features", "EDITOR_ENABLED") TRASH_ENABLED = config.getboolean("Features", "TRASH_ENABLED", fallback=False)
AUTO_CLOSE_SECONDS = config.getint("Features", "AUTO_CLOSE_SECONDS") EDITOR_ENABLED = config.getboolean("Features", "EDITOR_ENABLED", fallback=False)
EXTENSION = config["Copy"]["Extension"] AUTO_CLOSE_SECONDS = config.getint("Features", "AUTO_CLOSE_SECONDS", fallback=3600)
TEXT_FONT = config["UI"]["TEXT_FONT"] # COPY
ERROR_FONT_SIZE = config.getint("UI", "ERROR_FONT_SIZE") EXTENSION = config.get("Copy", "Extension", fallback="")
SEARCH_WIDTH = config.getint("UI", "SEARCH_WIDTH") # UI
SEARCH_HEIGHT = config.getint("UI", "SEARCH_HEIGHT") TEXT_FONT = config.get("UI","TEXT_FONT", fallback="Consolas")
SEARCH_FONT_SIZE = config.getint("UI", "SEARCH_FONT_SIZE") SEARCH_WIDTH = config.getint("UI", "SEARCH_WIDTH", fallback=400)
RESULTS_WIDTH = config.getint("UI", "RESULTS_WIDTH") SEARCH_HEIGHT = config.getint("UI", "SEARCH_HEIGHT", fallback=150)
RESULTS_HEIGHT = config.getint("UI", "RESULTS_HEIGHT") SEARCH_FONT_SIZE = config.getint("UI", "SEARCH_FONT_SIZE", fallback=12)
RESULTS_FONT_SIZE = config.getint("UI", "RESULTS_FONT_SIZE") RESULTS_WIDTH = config.getint("UI", "RESULTS_WIDTH", fallback=1000)
PREVIEW_WIDTH = config.getint("UI", "PREVIEW_WIDTH") RESULTS_HEIGHT = config.getint("UI", "RESULTS_HEIGHT", fallback=700)
PREVIEW_HEIGHT = config.getint("UI", "PREVIEW_HEIGHT") RESULTS_FONT_SIZE = config.getint("UI", "RESULTS_FONT_SIZE", fallback=11)
PREVIEW_FONT_SIZE = config.getint("UI", "PREVIEW_FONT_SIZE") PREVIEW_WIDTH = config.getint("UI", "PREVIEW_WIDTH", fallback=1200)
ERROR_WIDTH = config.getint("UI", "ERROR_WIDTH") PREVIEW_HEIGHT = config.getint("UI", "PREVIEW_HEIGHT", fallback=900)
ERROR_HEIGHT = config.getint("UI", "ERROR_HEIGHT") PREVIEW_FONT_SIZE = config.getint("UI", "PREVIEW_FONT_SIZE", fallback=24)
BUTTON_SIZE_SEARCH = config.getint("Buttons", "BUTTON_SIZE_SEARCH") ERROR_WIDTH = config.getint("UI", "ERROR_WIDTH", fallback=400)
BUTTON_SIZE_OPEN = config.getint("Buttons", "BUTTON_SIZE_OPEN") ERROR_HEIGHT = config.getint("UI", "ERROR_HEIGHT", fallback=100)
BUTTON_SIZE_SELECT_ALL = config.getint("Buttons", "BUTTON_SIZE_SELECT_ALL") ERROR_FONT_SIZE = config.getint("UI", "ERROR_FONT_SIZE", fallback=11)
BUTTON_SIZE_SAVE = config.getint("Buttons", "BUTTON_SIZE_SAVE") # BUTTONS
BUTTON_SIZE_COPY = config.getint("Buttons", "BUTTON_SIZE_COPY") BUTTON_SIZE_SEARCH = config.getint("Buttons", "BUTTON_SIZE_SEARCH", fallback=15)
BUTTON_SIZE_TRASH = config.getint("Buttons", "BUTTON_SIZE_TRASH") BUTTON_SIZE_OPEN = config.getint("Buttons", "BUTTON_SIZE_OPEN", fallback=15)
BUTTON_SIZE_CLOSE = config.getint("Buttons", "BUTTON_SIZE_CLOSE") BUTTON_SIZE_SELECT_ALL = config.getint("Buttons", "BUTTON_SIZE_SELECT_ALL", fallback=15)
BUTTON_SIZE_MESSAGE = config.getint("Buttons", "BUTTON_SIZE_MESSAGE") BUTTON_SIZE_SAVE = config.getint("Buttons", "BUTTON_SIZE_SAVE", fallback=15)
BUTTON_SIZE_YES_NO = config.getint("Buttons", "BUTTON_SIZE_YES_NO") BUTTON_SIZE_COPY = config.getint("Buttons", "BUTTON_SIZE_COPY", fallback=15)
BUTTON_SIZE_TRASH = config.getint("Buttons", "BUTTON_SIZE_TRASH", fallback=15)
BUTTON_SIZE_CLOSE = config.getint("Buttons", "BUTTON_SIZE_CLOSE", fallback=15)
BUTTON_SIZE_MESSAGE = config.getint("Buttons", "BUTTON_SIZE_MESSAGE", fallback=15)
BUTTON_SIZE_YES_NO = config.getint("Buttons", "BUTTON_SIZE_YES_NO", fallback=15)
# ============================================================ # ============================================================
os.makedirs(TRASH_DIR, exist_ok=True) os.makedirs(TRASH_DIR, exist_ok=True)
with open(INDEX_FILE, "rb") as f: SEARCH_INDEX = Indexer.load_index()
SEARCH_INDEX = pickle.load(f) if Indexer.update_index(SEARCH_INDEX):
try:
Indexer.save_index(SEARCH_INDEX)
except Exception:
pass
def find_external_drives(): def find_external_drives():
drives = [] drives = []