Untitled conversation
- Usercode
- Assistant
class MatchingFilesDialog(tk.Toplevel):
def __init__(self, master, input_path, matches):
super().__init__(master)
self.master = master
self.input_path = input_path
self.matches = matches
self.tree = None
self._create_ui()
self._populate_initial_data()
self._start_background_tasks()
def _create_ui(self):
self.title("Duplicate Matches")
self.resizable(True, True)
self.master.center_window(self, 800, 400)
content_frame = ttk.Frame(self, padding=10)
content_frame.pack(fill=tk.BOTH, expand=True)
input_label = ttk.Label(content_frame, text=f"Input file: {os.path.basename(self.input_path)}")
input_label.pack(anchor=tk.W, pady=(0, 5))
parent_frame = ttk.Frame(content_frame)
parent_frame.pack(fill=tk.X, pady=(0, 10))
parent_label = ttk.Label(parent_frame, text="Parent folder:")
parent_label.pack(side=tk.LEFT)
parent_path = os.path.dirname(self.input_path)
parent_path_label = ttk.Label(parent_frame, text=parent_path)
parent_path_label.pack(side=tk.LEFT, padx=5)
parent_browse = ttk.Button(parent_frame, text="Browse", command=lambda: open_folder(parent_path))
parent_browse.pack(side=tk.LEFT)
tree_frame = ttk.Frame(content_frame)
tree_frame.pack(fill=tk.BOTH, expand=True)
columns = ("basename", "size", "murmurhash")
tree = ttk.Treeview(tree_frame, columns=columns, show='headings')
self.tree = tree
tree.heading("basename", text="Basename")
tree.heading("size", text="File Size")
tree.heading("murmurhash", text="MurmurHash")
tree.column("basename", stretch=True, anchor=tk.W)
tree.column("size", width=100, minwidth=100, stretch=False, anchor=tk.CENTER)
tree.column("murmurhash", width=150, minwidth=100, stretch=False, anchor=tk.CENTER)
y_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree.yview)
x_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.HORIZONTAL, command=tree.xview)
tree.configure(yscroll=y_scrollbar.set, xscroll=x_scrollbar.set)
tree.grid(row=0, column=0, sticky='nsew')
y_scrollbar.grid(row=0, column=1, sticky='ns')
x_scrollbar.grid(row=1, column=0, sticky='ew')
tree_frame.grid_rowconfigure(0, weight=1)
tree_frame.grid_columnconfigure(0, weight=1)
tree.bind("<Double-1>", lambda event: self.on_dbclick_tree(event, tree, parent_path))
button_frame = ttk.Frame(self, padding=10)
button_frame.pack(fill=tk.X, pady=5)
ok_button = ttk.Button(button_frame, text="OK", command=self.destroy)
ok_button.pack()
def _populate_initial_data(self):
for dup_basename, _, dup_full_path in self.matches:
self.tree.insert("", tk.END, values=(dup_basename, "Calculating...", "Calculating..."))
def _start_background_tasks(self):
thread = threading.Thread(target=lambda: self._compute_hash_and_size(0))
thread.start()
def _compute_hash_and_size(self, index):
# Base condition: when the index reaches the length of matches
if index >= len(self.matches):
return
dup_basename, _, dup_full_path = self.matches[index]
try:
# Try to open the file and read its content
with open(dup_full_path, 'rb') as f:
content = f.read()
# Compute the MurmurHash from the file content
hash_value_int = mmh3.hash(content, seed=0)
hash_value = hex(hash_value_int & 0xFFFFFFFF)
size = os.path.getsize(dup_full_path)
human_readable_size = self.get_human_readable_size(size)
except FileNotFoundError:
# Handle the specific case where the file does not exist
human_readable_size, hash_value = "Not Found", "N/A"
except Exception as e:
# Handle other potential file access or reading errors
print(f"Error processing {dup_full_path}: {e}")
human_readable_size, hash_value = "Error", "Error"
# Update the tree view item
self.tree.item(
self.tree.get_children()[index],
values=(dup_basename, human_readable_size, hash_value)
)
# Schedule the next update
self.tree.after(
100,
lambda: self._compute_hash_and_size(index + 1)
)
@staticmethod
def on_dbclick_tree(event, tree, parent_path):
region = tree.identify("region", event.x, event.y)
if region != "cell":
return
row_id = tree.identify_row(event.y)
if not row_id:
return
basename = tree.set(row_id, "basename")
file_path = os.path.join(parent_path, basename)
if os.path.exists(file_path):
highlight_files(file_path)
else:
messagebox.showerror("File Not Found", f"The file '{file_path}' does not exist.")
@staticmethod
def get_human_readable_size(size, decimal_places=2):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.{decimal_places}f} {unit}"
size /= 1024.0
rewrite this such that the window is memoized.
e.g. calling MatchingFilesDialog(root, 'foo', whatever) once creates the window and focus on it. call it again would just bring the window to the front if its not destroyed. if its destroyed, create the window and focus on it.
basically you memoize master, input_path to a weak window reference
the reference is invalid upon window closed/destroyed
To implement memoization for the MatchingFilesDialog, we can utilize a class-level cache that stores weak references to the dialog instances based on a unique key derived from master and input_path. This ensures that:
master and input_path.master and input_path will bring the existing dialog to the foreground instead of creating a new one.Here is the refactored code implementing these features:
import os
import threading
import weakref
import tkinter as tk
from tkinter import ttk, messagebox
import mmh3 # Ensure you have mmh3 installed: pip install mmh3
# Placeholder functions for open_folder and highlight_files
def open_folder(path):
# Implement folder opening logic, e.g., using os.startfile on Windows
try:
if os.name == 'nt':
os.startfile(path)
elif os.name == 'posix':
subprocess.Popen(['xdg-open', path])
except Exception as e:
messagebox.showerror("Error", f"Cannot open folder: {e}")
def highlight_files(file_path):
# Implement file highlighting logic, e.g., selecting the file in explorer
try:
if os.name == 'nt':
os.startfile(os.path.dirname(file_path))
# Additional logic to highlight the specific file can be added
elif os.name == 'posix':
subprocess.Popen(['xdg-open', os.path.dirname(file_path)])
except Exception as e:
messagebox.showerror("Error", f"Cannot highlight file: {e}")
class MatchingFilesDialog(tk.Toplevel):
# Class-level cache to store weak references to dialog instances
_instances = weakref.WeakValueDictionary()
def __init__(self, master, input_path, matches):
super().__init__(master)
self.master = master
self.input_path = input_path
self.matches = matches
self.tree = None
self.protocol("WM_DELETE_WINDOW", self.on_close) # Ensure cleanup on close
self._create_ui()
self._populate_initial_data()
self._start_background_tasks()
@classmethod
def show(cls, master, input_path, matches):
"""
Show the MatchingFilesDialog. If an instance with the same master and input_path
exists, bring it to the front. Otherwise, create a new instance.
"""
key = (id(master), os.path.abspath(input_path))
instance = cls._instances.get(key)
if instance and tk.Toplevel.winfo_exists(instance):
instance.lift() # Bring the window to the front
instance.focus_force()
else:
instance = cls(master, input_path, matches)
cls._instances[key] = instance
def _create_ui(self):
self.title("Duplicate Matches")
self.resizable(True, True)
self.master.center_window(self, 800, 400)
content_frame = ttk.Frame(self, padding=10)
content_frame.pack(fill=tk.BOTH, expand=True)
input_label = ttk.Label(content_frame, text=f"Input file: {os.path.basename(self.input_path)}")
input_label.pack(anchor=tk.W, pady=(0, 5))
parent_frame = ttk.Frame(content_frame)
parent_frame.pack(fill=tk.X, pady=(0, 10))
parent_label = ttk.Label(parent_frame, text="Parent folder:")
parent_label.pack(side=tk.LEFT)
parent_path = os.path.dirname(self.input_path)
parent_path_label = ttk.Label(parent_frame, text=parent_path)
parent_path_label.pack(side=tk.LEFT, padx=5)
parent_browse = ttk.Button(parent_frame, text="Browse", command=lambda: open_folder(parent_path))
parent_browse.pack(side=tk.LEFT)
tree_frame = ttk.Frame(content_frame)
tree_frame.pack(fill=tk.BOTH, expand=True)
columns = ("basename", "size", "murmurhash")
tree = ttk.Treeview(tree_frame, columns=columns, show='headings')
self.tree = tree
tree.heading("basename", text="Basename")
tree.heading("size", text="File Size")
tree.heading("murmurhash", text="MurmurHash")
tree.column("basename", stretch=True, anchor=tk.W)
tree.column("size", width=100, minwidth=100, stretch=False, anchor=tk.CENTER)
tree.column("murmurhash", width=150, minwidth=100, stretch=False, anchor=tk.CENTER)
y_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree.yview)
x_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.HORIZONTAL, command=tree.xview)
tree.configure(yscroll=y_scrollbar.set, xscroll=x_scrollbar.set)
tree.grid(row=0, column=0, sticky='nsew')
y_scrollbar.grid(row=0, column=1, sticky='ns')
x_scrollbar.grid(row=1, column=0, sticky='ew')
tree_frame.grid_rowconfigure(0, weight=1)
tree_frame.grid_columnconfigure(0, weight=1)
tree.bind("<Double-1>", lambda event: self.on_dbclick_tree(event, tree, os.path.dirname(self.input_path)))
button_frame = ttk.Frame(self, padding=10)
button_frame.pack(fill=tk.X, pady=5)
ok_button = ttk.Button(button_frame, text="OK", command=self.destroy)
ok_button.pack()
def _populate_initial_data(self):
for dup_basename, _, dup_full_path in self.matches:
self.tree.insert("", tk.END, values=(dup_basename, "Calculating...", "Calculating..."))
def _start_background_tasks(self):
thread = threading.Thread(target=self._compute_hash_and_size, daemon=True)
thread.start()
def _compute_hash_and_size(self):
for index, (dup_basename, _, dup_full_path) in enumerate(self.matches):
try:
with open(dup_full_path, 'rb') as f:
content = f.read()
# Compute the MurmurHash from the file content
hash_value_int = mmh3.hash(content, seed=0)
hash_value = hex(hash_value_int & 0xFFFFFFFF)
size = os.path.getsize(dup_full_path)
human_readable_size = self.get_human_readable_size(size)
except FileNotFoundError:
human_readable_size, hash_value = "Not Found", "N/A"
except Exception as e:
print(f"Error processing {dup_full_path}: {e}")
human_readable_size, hash_value = "Error", "Error"
# Schedule the update on the main thread
self.tree.after(0, self._update_tree_item, index, dup_basename, human_readable_size, hash_value)
def _update_tree_item(self, index, basename, size, hash_value):
children = self.tree.get_children()
if index < len(children):
self.tree.item(
children[index],
values=(basename, size, hash_value)
)
@staticmethod
def on_dbclick_tree(event, tree, parent_path):
region = tree.identify("region", event.x, event.y)
if region != "cell":
return
row_id = tree.identify_row(event.y)
if not row_id:
return
basename = tree.set(row_id, "basename")
file_path = os.path.join(parent_path, basename)
if os.path.exists(file_path):
highlight_files(file_path)
else:
messagebox.showerror("File Not Found", f"The file '{file_path}' does not exist.")
@staticmethod
def get_human_readable_size(size, decimal_places=2):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.{decimal_places}f} {unit}"
size /= 1024.0
return f"{size:.{decimal_places}f} PB"
def on_close(self):
"""Handle the window being closed."""
self.destroy()
# Example usage:
if __name__ == "__main__":
import subprocess
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Main Application")
self.geometry("300x200")
# Center window method
self.center_window = lambda win, width, height: self.center(win, width, height)
open_dialog_btn = ttk.Button(self, text="Open Matching Files Dialog", command=self.open_dialog)
open_dialog_btn.pack(pady=50)
def center(self, win, width, height):
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()
x = (screen_width // 2) - (width // 2)
y = (screen_height // 2) - (height // 2)
win.geometry(f'{width}x{height}+{x}+{y}')
def open_dialog(self):
# Sample data: list of tuples (basename, _, full_path)
matches = [
("file1.txt", None, "/path/to/file1.txt"),
("file2.txt", None, "/path/to/file2.txt"),
# Add more sample matches as needed
]
MatchingFilesDialog.show(self, "/path/to/input/file.txt", matches)
app = App()
app.mainloop()
Class-Level Cache with Weak References:
MatchingFilesDialog now has a class-level _instances dictionary that uses weakref.WeakValueDictionary to store weak references to dialog instances.(id(master), absolute_input_path), ensuring uniqueness based on the master window and the input file path.Class Method show:
show method is introduced as a class method to handle the creation or activation of dialog instances.winfo_exists). If so, it brings that window to the front. Otherwise, it creates a new instance and stores it in the _instances cache.Daemon Threads:
daemon=True) to ensure it does not prevent the application from exiting.Immediate GUI Updates:
after, the _compute_hash_and_size method now iterates through all matches and schedules updates for each item. This approach is more efficient and avoids deep recursion.Protocol Handling for Cleanup:
protocol("WM_DELETE_WINDOW", self.on_close) ensures that when the window is closed, any necessary cleanup can be performed. In this case, it simply destroys the window, and the weak reference is automatically removed from the cache.Example Usage:
App class demonstrates how to use the MatchingFilesDialog. It includes a center_window method to center the dialog window on the screen.Placeholder Functions:
open_folder and highlight_files are implemented as placeholders. You should replace these with appropriate implementations based on your application's requirements and the operating system.Thread Safety: Tkinter is not thread-safe. All interactions with the GUI should occur on the main thread. The use of tree.after(0, ...) ensures that updates to the GUI are safely scheduled on the main thread.
Error Handling: Proper error handling is included to manage file access issues gracefully.
Dependencies: Ensure that the mmh3 library is installed. You can install it using pip install mmh3.
This implementation ensures that each MatchingFilesDialog is uniquely identified by its master and input_path, preventing duplicate dialogs and maintaining a clean and efficient user interface.
Not yet included in a published release.