diff --git a/Config/config.ini b/Config/config.ini index 2b1451b..a6e2459 100644 --- a/Config/config.ini +++ b/Config/config.ini @@ -1,11 +1,43 @@ [Paths] SEARCH_ROOT = C:\CNCPrograms\Programs TRASH_DIR = C:\CNCPrograms\Trash +INDEX_FILE = C:\CNCPrograms\search_index.pkl [Features] TRASH_ENABLED = True EDITOR_ENABLED = False AUTO_CLOSE_SECONDS = 300 +WORKER_COUNT = 16 [Copy] -Extension = \ No newline at end of file +Extension = + +[Buttons] +BUTTON_SIZE_SEARCH=15 +BUTTON_SIZE_OPEN=15 +BUTTON_SIZE_SELECT_ALL=15 +BUTTON_SIZE_SAVE=15 +BUTTON_SIZE_COPY=15 +BUTTON_SIZE_TRASH=15 +BUTTON_SIZE_CLOSE=15 +BUTTON_SIZE_MESSAGE=15 +BUTTON_SIZE_YES_NO=15 + +[UI] +TEXT_FONT = Consolas + +SEARCH_WIDTH=400 +SEARCH_HEIGHT=150 +SEARCH_FONT_SIZE=12 + +RESULTS_WIDTH=1000 +RESULTS_HEIGHT=700 +RESULTS_FONT_SIZE=11 + +PREVIEW_WIDTH=1200 +PREVIEW_HEIGHT=900 +PREVIEW_FONT_SIZE=24 + +ERROR_FONT_SIZE=11 +ERROR_WIDTH=400 +ERROR_HEIGHT=100 \ No newline at end of file diff --git a/Indexer.py b/Indexer.py new file mode 100644 index 0000000..4754d75 --- /dev/null +++ b/Indexer.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 + +import os +import pickle +import configparser +from concurrent.futures import ThreadPoolExecutor + +# ============================================================ +# CONFIG +config = configparser.ConfigParser() +config.read(r"C:\ProgramData\Program-Search\config.ini") +SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"] +INDEX_FILE = config["Paths"]["INDEX_FILE"] +WORKER_COUNT = config.getint("Features", "WORKER_COUNT") +# ============================================================ + +SEARCH_INDEX = {} + + +def read_file(path): + try: + with open(path, "r", errors="ignore") as f: + + return ( + path, + { + "filename": os.path.basename(path).lower(), + "content": f.read().lower() + } + ) + + except Exception: + return None + + +def build_index(): + + files = [] + + print("Collecting files...") + + for root, dirs, filenames in os.walk(SEARCH_ROOT): + for filename in filenames: + files.append( + os.path.join(root, filename) + ) + + print(f"Found {len(files)} files") + print("Building index...\n") + + completed = 0 + + with ThreadPoolExecutor( + max_workers=WORKER_COUNT + ) as executor: + + for result in executor.map( + read_file, + files + ): + + completed += 1 + + if completed % 100 == 0: + print( + f"{completed}/{len(files)}" + ) + + if result: + path, data = result + SEARCH_INDEX[path] = data + + print("\nSaving index...") + + os.makedirs( + 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( + f"Index saved:\n" + f"{INDEX_FILE}\n" + f"{len(SEARCH_INDEX)} files\n" + f"{size_mb:.2f} MB" + ) + + +if __name__ == "__main__": + build_index() \ No newline at end of file diff --git a/Search.py b/Search.py index 2cb4300..898f27d 100644 --- a/Search.py +++ b/Search.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 import os import tkinter as tk -from tkinter import filedialog, messagebox, scrolledtext +from tkinter import scrolledtext +import pickle import shutil import ctypes import string @@ -13,14 +14,40 @@ config = configparser.ConfigParser() config.read(r"C:\ProgramData\Program-Search\config.ini") SEARCH_ROOT = config["Paths"]["SEARCH_ROOT"] TRASH_DIR = config["Paths"]["TRASH_DIR"] +INDEX_FILE = config["Paths"]["INDEX_FILE"] TRASH_ENABLED = config.getboolean("Features", "TRASH_ENABLED") EDITOR_ENABLED = config.getboolean("Features", "EDITOR_ENABLED") AUTO_CLOSE_SECONDS = config.getint("Features", "AUTO_CLOSE_SECONDS") -Extension = config["Copy"]["Extension"] +EXTENSION = config["Copy"]["Extension"] +TEXT_FONT = config["UI"]["TEXT_FONT"] +ERROR_FONT_SIZE = config.getint("UI", "ERROR_FONT_SIZE") +SEARCH_WIDTH = config.getint("UI", "SEARCH_WIDTH") +SEARCH_HEIGHT = config.getint("UI", "SEARCH_HEIGHT") +SEARCH_FONT_SIZE = config.getint("UI", "SEARCH_FONT_SIZE") +RESULTS_WIDTH = config.getint("UI", "RESULTS_WIDTH") +RESULTS_HEIGHT = config.getint("UI", "RESULTS_HEIGHT") +RESULTS_FONT_SIZE = config.getint("UI", "RESULTS_FONT_SIZE") +PREVIEW_WIDTH = config.getint("UI", "PREVIEW_WIDTH") +PREVIEW_HEIGHT = config.getint("UI", "PREVIEW_HEIGHT") +PREVIEW_FONT_SIZE = config.getint("UI", "PREVIEW_FONT_SIZE") +ERROR_WIDTH = config.getint("UI", "ERROR_WIDTH") +ERROR_HEIGHT = config.getint("UI", "ERROR_HEIGHT") +BUTTON_SIZE_SEARCH = config.getint("Buttons", "BUTTON_SIZE_SEARCH") +BUTTON_SIZE_OPEN = config.getint("Buttons", "BUTTON_SIZE_OPEN") +BUTTON_SIZE_SELECT_ALL = config.getint("Buttons", "BUTTON_SIZE_SELECT_ALL") +BUTTON_SIZE_SAVE = config.getint("Buttons", "BUTTON_SIZE_SAVE") +BUTTON_SIZE_COPY = config.getint("Buttons", "BUTTON_SIZE_COPY") +BUTTON_SIZE_TRASH = config.getint("Buttons", "BUTTON_SIZE_TRASH") +BUTTON_SIZE_CLOSE = config.getint("Buttons", "BUTTON_SIZE_CLOSE") +BUTTON_SIZE_MESSAGE = config.getint("Buttons", "BUTTON_SIZE_MESSAGE") +BUTTON_SIZE_YES_NO = config.getint("Buttons", "BUTTON_SIZE_YES_NO") # ============================================================ os.makedirs(TRASH_DIR, exist_ok=True) +with open(INDEX_FILE, "rb") as f: + SEARCH_INDEX = pickle.load(f) + def find_external_drives(): drives = [] DRIVE_REMOVABLE = 2 @@ -38,45 +65,117 @@ def find_external_drives(): def popup_search_input(): win = tk.Toplevel() 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) - entry = tk.Entry(win, font=("Consolas", 12)) + tk.Label(win, text="Enter part number or name:", font=(TEXT_FONT, SEARCH_FONT_SIZE)).pack(pady=10) + entry = tk.Entry(win, font=(TEXT_FONT, SEARCH_FONT_SIZE)) entry.pack(pady=5) - entry.focus_set() - - result = {"value": None} + win.lift() + win.attributes("-topmost", True) + win.after(50, lambda: (entry.focus_set(), entry.icursor(tk.END))) + win.after(100, lambda: (win.attributes("-topmost"), False)) + + result = {"value": None, "force_close": False} def submit(): result["value"] = entry.get().strip().lower() win.destroy() - tk.Button(win, text="Search", command=submit).pack(pady=10) + def force_close(): + result["force_close"] = True + win.destroy() + entry.bind("", 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.wait_window() + return result + + +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("", 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=10, font=(TEXT_FONT, BUTTON_SIZE_YES_NO), command=yes).pack(side="left", padx=10) + tk.Button(button_frame, text="No", width=10, 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 search_files(term): + + term = term.lower() + matches = [] - for root, dirs, files in os.walk(SEARCH_ROOT): - for fname in files: - path = os.path.join(root, fname) - fname_lower = fname.lower() + for path, data in SEARCH_INDEX.items(): - filename_match = term in fname_lower - contents_match = False + if term in data.get("filename"): + matches.append(path) - 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) + elif term in data.get("content", ""): + matches.append(path) return matches @@ -84,15 +183,19 @@ def search_files(term): def popup_results_list(matches): win = tk.Toplevel() win.title("Matches Found") - win.geometry("600x400") + win.geometry(f"{RESULTS_WIDTH}x{RESULTS_HEIGHT}") + + tk.Label(win, text="Select files to preview:", font=(TEXT_FONT, RESULTS_FONT_SIZE)).pack(pady=10) - 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 = tk.Listbox(win, selectmode=tk.MULTIPLE, font=(TEXT_FONT, RESULTS_FONT_SIZE)) lb.pack(expand=True, fill="both") + lb.bind("", lambda e: submit()) 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": []} @@ -100,23 +203,35 @@ def popup_results_list(matches): lb.select_set(0, tk.END) def submit(): 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] win.destroy() + + tk.Button(win, text="Open Selected", font=(TEXT_FONT, BUTTON_SIZE_OPEN), command=submit).pack(padx=10) + tk.Button(win, text="Select All", font=(TEXT_FONT, BUTTON_SIZE_SELECT_ALL), command=select_all).pack(padx=10) - tk.Button(win, text="Open Selected", command=submit).pack(padx=10) - tk.Button(win, text="Select All", command=select_all).pack(padx=10) - + center_window(win,RESULTS_WIDTH, RESULTS_HEIGHT) + win.lift() + win.focus_force() win.wait_window() return result["selected"] -def popup_file_preview(path, on_close_callback): +def popup_file_preview(path, on_close_callback, preview_windows): win = tk.Toplevel() + preview_windows.append(win) win.title(path) - win.geometry("900x700") + height = min(PREVIEW_HEIGHT, win.winfo_screenheight() - 80) + win.geometry(f"{PREVIEW_WIDTH}x{height}") + win.bind("", lambda e: close()) - box = scrolledtext.ScrolledText(win, wrap=tk.WORD, font=("Consolas", 11)) - box.pack(expand=True, fill="both") + frame = tk.Frame(win) + 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: with open(path, "r", errors="ignore") as f: @@ -139,8 +254,6 @@ def popup_file_preview(path, on_close_callback): else: box.configure(state="disabled") - frame = tk.Frame(win) - frame.pack(fill="x", pady=10) def save_file(): @@ -148,16 +261,16 @@ def popup_file_preview(path, on_close_callback): 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}") + custom_message("Saved", f"File saved:\n{path}") except Exception as e: - messagebox.showerror("Save Error", str(e)) + custom_message("Save Error", str(e)) 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 copy_to_external(): if EDITOR_ENABLED and modified["changed"]: - ask = messagebox.askyesno( + ask = custom_yesno( "Unsaved Changes", "You have unsaved changes.\nSave before copying?" ) @@ -166,11 +279,11 @@ def popup_file_preview(path, on_close_callback): drives = find_external_drives() if not drives: - messagebox.showerror("No External Drive Found", "No external drive detected.") + custom_message("No External Drive Found", "No external drive detected.") return base_name = os.path.splitext(os.path.basename(path))[0] - new_name = base_name + Extension + new_name = base_name + EXTENSION copied = [] for d in drives: @@ -179,15 +292,15 @@ def popup_file_preview(path, on_close_callback): shutil.copy2(path, dest) copied.append(dest) except Exception as e: - messagebox.showerror("Copy Error", f"Could not copy to {d}:\n{e}") + custom_message("Copy Error", f"Could not copy to {d}:\n{e}") if copied: - messagebox.showinfo("Copied Successfully", "Copied to:\n\n" + "\n".join(copied)) + custom_message("Copied Successfully", "Copied to:\n\n" + "\n".join(copied)) win.destroy() on_close_callback() def move_to_trash(): - confirm = messagebox.askyesno( + confirm = custom_yesno( "Move to Trash", f"Are you sure you want to move this file to trash?\n\n{path}" ) @@ -197,21 +310,19 @@ def popup_file_preview(path, on_close_callback): dest_path = os.path.join(TRASH_DIR, rel_path) os.makedirs(os.path.dirname(dest_path), exist_ok=True) shutil.move(path, dest_path) - messagebox.showinfo("Trashed", f"Moved to trash:\n{dest_path}") + custom_message("Trashed", f"Moved to trash:\n{dest_path}") win.destroy() on_close_callback() except Exception as e: - messagebox.showerror("Trash Error", str(e)) + custom_message("Trash Error", str(e)) def close(): if EDITOR_ENABLED and modified["changed"]: - ask = messagebox.askyesno( - "Unsaved Changes", - "You have unsaved changes.\nSave before closing?" - ) + ask = custom_yesno("Unsaved Changes","You have unsaved changes.\nSave before closing?") if ask: save_file() - + if win in preview_windows: + preview_windows.remove(win) win.destroy() on_close_callback() @@ -220,32 +331,49 @@ def popup_file_preview(path, on_close_callback): win.destroy() on_close_callback() + def close_all(): + confirm = custom_yesno("Close All", "Close all preview windows?") + if not confirm: + return + for preview in preview_windows[:]: + try: + if preview.winfo_exists(): + preview.destroy() + except tk.TclError: + pass + preview_windows.clear() + win.protocol("WM_DELETE_WINDOW", close) win.after(AUTO_CLOSE_SECONDS * 1000, auto_close) - if TRASH_ENABLED == True: - tk.Button(frame, text="Move to Trash", fg="red", command=move_to_trash).pack(side="left", padx=10) + if TRASH_ENABLED: + tk.Button(frame, text="Move to Trash", fg="red", font=(TEXT_FONT, BUTTON_SIZE_TRASH), command=move_to_trash).pack(side="left", padx=10) - tk.Button(frame, text="Copy to External Drive", fg="blue", command=copy_to_external).pack(side="left", padx=10) + tk.Button(frame, text="Copy to External Drive", fg="blue", font=(TEXT_FONT, BUTTON_SIZE_COPY), command=copy_to_external).pack(side="left", padx=10) - tk.Button(frame, text="Close", command=close).pack(side="right", 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 all", font=(TEXT_FONT, BUTTON_SIZE_CLOSE), command=close_all).pack(side="right", padx=10) def main(): root = tk.Tk() root.withdraw() - search_term = popup_search_input() - if not search_term: - root.destroy() - return + while True: + result = popup_search_input() + search_term = result["value"] - matches = search_files(search_term) - - if not matches: - messagebox.showinfo("No Results", "No matching files found.") - root.destroy() - return + if result["force_close"]: + root.destroy() + return + if not search_term: + custom_message("Invalid Search", "Please enter a search term.") + continue + matches = search_files(search_term) + if not matches: + custom_message("No Results", "No matching files found.") + continue + break selected = popup_results_list(matches) if not selected: @@ -255,6 +383,8 @@ def main(): open_windows = {"count": len(selected)} + preview_windows = [] + def window_closed(): open_windows["count"] -= 1 if open_windows["count"] == 0: @@ -262,10 +392,10 @@ def main(): for path in selected: - popup_file_preview(path, window_closed) + popup_file_preview(path, window_closed, preview_windows) root.mainloop() if __name__ == "__main__": - main() + main() \ No newline at end of file