This repository was archived by the owner on Feb 27, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
327 lines (268 loc) · 12.7 KB
/
main.py
File metadata and controls
327 lines (268 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import json
import os
import time
from datetime import datetime
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox, filedialog
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import sv_ttk
import darkdetect as dd
log_path = f"./logs/{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log"
if not os.path.exists(log_path):
os.makedirs(os.path.dirname(log_path), exist_ok=True)
logging.basicConfig(level=logging.DEBUG,
format="[%(asctime)s %(name)s] (%(levelname)s) %(message)s",
filename=f"./logs/{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log",
encoding="utf-8")
log = logging.getLogger()
VERSION = "0.1.2.1a"
VERSION_CODENAME = "Cherry Grove"
VERSION_DESCRIPTION = f"v{VERSION} ({VERSION_CODENAME})"
class NewFileHandler(FileSystemEventHandler):
def __init__(self, callback):
self.callback = callback
super().__init__()
def on_created(self, event):
if not event.is_directory:
# 稍微延迟一下以确保文件完全写入
time.sleep(0.1)
self.callback(event.src_path)
class NoMessyDesktopApp:
def __init__(self, config: dict):
try:
self.desktop_path = config["watch_dir"]
except KeyError as exc:
log.error(f"KeyError: {exc} when reading config")
log.warning("No desktop path found in config. Ask again and save it.")
ask_desktop_path_and_save()
self.desktop_path = read_config()["watch_dir"]
self.observer = Observer()
# 初始化主窗口但不显示
self.root = Tk()
self.root.withdraw() # 隐藏主窗口
self.pending_files = [] # 存储待处理的文件
self.processing = False # 标记是否正在处理文件
def start_monitoring(self):
event_handler = NewFileHandler(self.on_new_file)
self.observer.schedule(event_handler, self.desktop_path, recursive=False)
self.observer.start()
log.info(f"Start monitoring {self.desktop_path}")
# 定期检查是否有新文件需要处理
self.root.after(100, self.process_pending_files)
try:
# 启动GUI主循环
sv_ttk.set_theme(dd.theme())
self.root.mainloop()
except KeyboardInterrupt:
self.stop_monitoring()
def on_new_file(self, file_path):
# 将新文件添加到待处理列表
log.debug(f"New file: {file_path}")
self.pending_files.append(file_path)
def process_pending_files(self):
# 在主线程中处理待处理的文件
if self.pending_files and not self.processing:
self.processing = True
file_path = self.pending_files.pop(0)
self.show_file_dialog(file_path)
self.processing = False
# 继续定期检查
self.root.after(100, self.process_pending_files)
def show_file_dialog(self, file_path):
# 创建并显示文件信息对话框
dialog = Toplevel(self.root)
dialog.title(f"New file {os.path.basename(file_path)} at {self.desktop_path}"
f" - NoMessyDesktop {VERSION_DESCRIPTION}")
dialog.geometry("500x150")
dialog.resizable(False, False)
dialog.attributes('-topmost', True) # 窗口置顶
# 获取文件信息
file_stat = os.stat(file_path)
log.info(f"New file stat: {file_stat}")
# 文件名
Label(dialog, text="New File Detected", font=("MiSans", 20, "bold")).pack(pady=(10, 5))
# 文件路径
Label(dialog, text=file_path, font=("JetBrains Maple Mono", 12)).pack(pady=5)
# 操作框架
action_frame = Frame(dialog)
action_frame.pack(pady=10)
def show_details():
# 显示详细属性窗口
self.show_file_details(file_path)
def move_file():
# 选择目标文件夹
destination_folder = filedialog.askdirectory(
title="Choose target folder",
initialdir=os.path.dirname(self.desktop_path)
)
log.debug("Select Moving")
if destination_folder:
try:
# 移动文件
file_name = os.path.basename(file_path)
destination_path = os.path.join(destination_folder, file_name)
# 如果目标文件已存在,添加数字后缀
counter = 1
base_name, extension = os.path.splitext(file_name)
while os.path.exists(destination_path):
new_name = f"{base_name}_{counter}{extension}"
destination_path = os.path.join(destination_folder, new_name)
counter += 1
os.rename(file_path, destination_path)
messagebox.showinfo("Done!", f"File moved successfully to:\n{destination_path}")
log.info(f"Move file {file_path!r} to {destination_path!r}")
dialog.destroy()
except Exception as e:
messagebox.showerror("Error!", f"Failed to move to:\n{str(e)}")
def ignore_file():
log.debug("Select Ignore, Closing dialog")
dialog.destroy()
Button(action_frame, text="Property", command=show_details, width=15).pack(side="left", padx=5)
Button(action_frame, text="Move to…", command=move_file, width=15).pack(side="left", padx=5)
Button(action_frame, text="Ignore", command=ignore_file, width=15).pack(side="left", padx=5)
# 居中显示对话框
dialog.update_idletasks()
x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
dialog.geometry(f"+{x}+{y}")
sv_ttk.set_theme(dd.theme())
dialog.focus_force()
dialog.mainloop()
def show_file_details(self, file_path):
# 创建并显示文件详细信息对话框
details_dialog = Toplevel(self.root)
details_dialog.title(f"Property of {os.path.basename(file_path)} - NoMessyDesktop {VERSION_DESCRIPTION}")
details_dialog.geometry("500x300")
details_dialog.resizable(False, False)
details_dialog.attributes('-topmost', True) # 窗口置顶
# 获取文件详细信息
file_stat = os.stat(file_path)
file_size = file_stat.st_size
creation_time = datetime.fromtimestamp(file_stat.st_ctime)
modification_time = datetime.fromtimestamp(file_stat.st_mtime)
try:
# 尝试获取访问时间
access_time = datetime.fromtimestamp(file_stat.st_atime)
except Exception as exc:
access_time = "Unavailable"
log.warning(f"Get access time error: {exc}")
Label(details_dialog, text=f"Property of {os.path.basename(file_path)}:",
font=("MiSans", 15, "bold")).pack(pady=(10, 10))
info_frame = Frame(details_dialog)
info_frame.pack(pady=10, padx=20, fill="x")
(Label(info_frame, text="File Name:", anchor="w", font=("JetBrains Maple Mono", 10))
.grid(row=0, column=0, sticky="w"))
(Label(info_frame, text=os.path.basename(file_path), anchor="w",
font=("JetBrains Maple Mono", 10)).grid(row=0, column=1, sticky="w"))
(Label(info_frame, text="File Path:", anchor="w", font=("JetBrains Maple Mono", 10)).
grid(row=1, column=0, sticky="w"))
(Label(info_frame, text=file_path, anchor="w", font=("JetBrains Maple Mono", 10))
.grid(row=1, column=1, sticky="w"))
(Label(info_frame, text="File Size:", anchor="w", font=("JetBrains Maple Mono", 10)).
grid(row=2, column=0, sticky="w"))
(Label(info_frame, text=f"{file_size} B", anchor="w", font=("JetBrains Maple Mono", 10))
.grid(row=2, column=1, sticky="w"))
(Label(info_frame, text="Create T.:", anchor="w", font=("JetBrains Maple Mono", 10)).
grid(row=3, column=0, sticky="w"))
(Label(info_frame, text=creation_time.strftime("%Y-%m-%d %H:%M:%S"), anchor="w",
font=("JetBrains Maple Mono", 10))
.grid(row=3, column=1, sticky="w"))
(Label(info_frame, text="Edit Time:", anchor="w", font=("JetBrains Maple Mono", 10)).
grid(row=4, column=0, sticky="w"))
(Label(info_frame, text=modification_time.strftime("%Y-%m-%d %H:%M:%S"), anchor="w",
font=("JetBrains Maple Mono", 10))
.grid(row=4, column=1, sticky="w"))
(Label(info_frame, text="Read Time:", anchor="w", font=("JetBrains Maple Mono", 10)).
grid(row=5, column=0, sticky="w"))
(Label(info_frame, text=access_time if access_time == "Unavailable" else
access_time.strftime("%Y-%m-%d %H:%M:%S"), anchor="w", font=("JetBrains Maple Mono", 10))
.grid(row=5, column=1, sticky="w"))
close_btn = Button(details_dialog, text="Close", command=details_dialog.destroy, width=15)
close_btn.pack(pady=20)
# 居中显示对话框
details_dialog.update_idletasks()
x = (details_dialog.winfo_screenwidth() // 2) - (details_dialog.winfo_width() // 2)
y = (details_dialog.winfo_screenheight() // 2) - (details_dialog.winfo_height() // 2)
details_dialog.geometry(f"+{x}+{y}")
sv_ttk.set_theme(dd.theme())
details_dialog.focus_force()
details_dialog.mainloop()
def stop_monitoring(self):
self.observer.stop()
self.observer.join()
log.info("App stopped")
self.root.quit()
exit()
def ask_desktop_path_and_save():
"""
向用户询问桌面的路径并且保存为JSON配置文件。
"""
auto_gen_path = os.path.join(os.path.expanduser('~'), 'Desktop')
log.debug(f"Auto generated desktop folder {auto_gen_path!r}")
config = {"watch_dir": ""}
def path_asker():
config["watch_dir"] = filedialog.askdirectory(
initialdir=auto_gen_path, title="Choose Desktop Folder...", mustexist=True, parent=initializer)
messagebox.showinfo("Set successful!", f"Desktop folder: \n{config['watch_dir']}")
initializer.destroy()
def use_auto_gen_path():
config["watch_dir"] = auto_gen_path
messagebox.showinfo("Using auto generated path.", f"Desktop folder: \n{config['watch_dir']}")
initializer.destroy()
initializer = Tk()
initializer.geometry("550x200")
initializer.resizable(False, False)
initializer.title(f"Asking Desktop Path... - NoMessyDesktop {VERSION_DESCRIPTION}")
(Label(initializer, text="Choose the desktop folder to monitor:", font=("MiSans", 15, "bold"))
.pack(anchor="center", padx=5, pady=(10, 0), fill="none", side="top"))
(Label(initializer, text=f"Auto generated: {auto_gen_path}", font=("JetBrains Maple Mono", 12))
.pack(anchor="center", padx=5, pady=5, fill="none", side="top"))
(Button(initializer, text="Choose...", command=path_asker)
.pack(anchor="center", padx=20, pady=0, fill="both", side="bottom", ipady=4))
(Button(initializer, text="Use Auto Generated Path", command=use_auto_gen_path)
.pack(anchor="center", padx=20, pady=5, fill="both", side="bottom", ipady=4))
sv_ttk.set_theme(dd.theme())
initializer.mainloop()
log.debug(f"Get config: {config}")
with open("./config/config.json", "w", encoding="utf-8") as fp:
json.dump(config, fp, indent=4)
def read_config(path: str = "./config/config.json") -> dict:
"""
读取JSON格式的配置文件。
:param path: 配置文件的来源。默认为./config/config.json。
:return: 读取到的配置文件。当找不到配置文件时,返回空字典。
"""
try:
with open(path, "r", encoding="utf-8") as fp:
config = json.load(fp)
except FileNotFoundError:
log.warning("Config file not found. Returning {}.")
return {} # 返回空值
log.debug(f"Read config: {config}")
return config
def check_config(config: dict) -> bool:
"""
检查配置文件的可用性。
:param config: 读取的配置,以字典的形式呈现。
:return: 配置文件是否可用。
"""
log.debug(f"Checking config: {config}")
watch_dir = config.get("watch_dir", "")
if not os.path.exists(watch_dir):
log.warning(f"Watch directory {watch_dir} not exists. Failed checking.")
return False
return True
if __name__ == "__main__":
os.makedirs("./config", exist_ok=True)
while True:
config = read_config()
if check_config(config):
break
else:
ask_desktop_path_and_save()
continue
app = NoMessyDesktopApp(config)
app.start_monitoring()