· 11 months ago · Oct 31, 2024, 04:41 AM
1import tkinter as tk
2from tkinter import filedialog, messagebox, scrolledtext
3import os
4import sqlite3
5import subprocess
6
7# Filtered extensions
8EXTENSIONS = {".py", ".pyw", ".txt", ".bat", ".reg", ".vbs", ".ahk", ".au3", ".m3u", ".m3u8", ".ini"}
9
10class ScriptDataManager:
11 def __init__(self, root):
12 self.root = root
13 self.root.title("Najeeb Advanced Script Data Manager")
14 self.root.geometry("1024x700")
15 self.root.config(bg="lightblue")
16
17 # Font configuration
18 self.big_font = ("Arial", 12, "bold")
19
20 # Top Row: Search, Add, Show All in One Line
21 style_button = {"bg": "#4CAF50", "fg": "white", "width": 14, "padx": 2, "pady": 2}
22
23 # Button frame at the top
24 self.button_frame = tk.Frame(self.root)
25 self.button_frame.pack(side=tk.TOP, fill=tk.X, padx=10, pady=10)
26
27 # Buttons for actions in two rows
28 self.browse_button = tk.Button(self.button_frame, text="Browse Folder", font=self.big_font, command=self.browse_folder, **style_button)
29 self.browse_button.grid(row=0, column=0, padx=5, pady=5)
30
31 self.browse_new_db_button = tk.Button(self.button_frame, text="Browse Database", font=self.big_font, command=self.browse_new_database, **style_button)
32 self.browse_new_db_button.grid(row=0, column=1, padx=5, pady=5)
33
34 self.save_button = tk.Button(self.button_frame, text="Save", font=self.big_font, command=self.save_file, **style_button)
35 self.save_button.grid(row=0, column=2, padx=5, pady=5)
36
37 self.delete_button = tk.Button(self.button_frame, text="Delete", font=self.big_font, command=self.delete_file, **style_button)
38 self.delete_button.grid(row=0, column=3, padx=5, pady=5)
39
40 self.edit_button = tk.Button(self.button_frame, text="Edit", font=self.big_font, command=self.enable_editing, **style_button)
41 self.edit_button.grid(row=0, column=4, padx=5, pady=5)
42
43 self.run_button = tk.Button(self.button_frame, text="Run Script", font=self.big_font, command=self.run_script, **style_button)
44 self.run_button.grid(row=0, column=5, padx=5, pady=5)
45
46 self.show_all_button = tk.Button(self.button_frame, text="Show All Scripts", font=self.big_font, command=self.show_all_scripts, **style_button)
47 self.show_all_button.grid(row=1, column=0, padx=5, pady=5)
48
49 # Search Script field and button
50 self.search_entry = tk.Entry(self.button_frame, font=self.big_font, width=20)
51 self.search_entry.grid(row=1, column=1, padx=5, pady=5)
52 self.search_button = tk.Button(self.button_frame, text="Search Script", font=self.big_font, command=self.search_script, **style_button)
53 self.search_button.grid(row=1, column=2, padx=5, pady=5)
54
55 # Run Cmd command field and button
56 self.command_entry = tk.Entry(self.button_frame, font=self.big_font, width=20)
57 self.command_entry.grid(row=1, column=3, padx=5, pady=5)
58 self.run_cmd_button = tk.Button(self.button_frame, text="Run Cmd", font=self.big_font, command=self.run_cmd, **style_button)
59 self.run_cmd_button.grid(row=1, column=4, padx=5, pady=5)
60
61 # Copy to Clipboard Button
62 self.copy_button = tk.Button(self.button_frame, text="Copy to Clipboard", font=self.big_font, command=self.copy_to_clipboard, **style_button)
63 self.copy_button.grid(row=1, column=5, padx=5, pady=5)
64
65 # File browsing frame with Listbox and scrollbar
66 self.file_frame = tk.Frame(self.root)
67 self.file_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)
68
69 self.scrollbar = tk.Scrollbar(self.file_frame)
70 self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
71
72 self.file_list = tk.Listbox(self.file_frame, selectmode=tk.SINGLE, width=30, height=25, font=self.big_font, yscrollcommand=self.scrollbar.set)
73 self.file_list.pack(side=tk.LEFT, fill=tk.Y)
74 self.scrollbar.config(command=self.file_list.yview)
75 self.file_list.bind("<<ListboxSelect>>", self.load_selected_file)
76
77 # Big view data frame for content display/edit
78 self.data_frame = tk.Frame(self.root)
79 self.data_frame.pack(side=tk.RIGHT, expand=True, fill=tk.BOTH, padx=10, pady=10)
80
81 self.text_viewer = scrolledtext.ScrolledText(self.data_frame, wrap=tk.WORD, state='disabled', font=self.big_font)
82 self.text_viewer.pack(fill=tk.BOTH, expand=True)
83
84 # Initialize database
85 self.init_db()
86
87 # Selected file path and folder path
88 self.current_file = None
89 self.folder_path = ""
90
91 def init_db(self):
92 """Initialize the SQLite database and create table if it doesn't exist."""
93 self.conn = sqlite3.connect("ScriptData.db")
94 self.cursor = self.conn.cursor()
95 self.cursor.execute('''CREATE TABLE IF NOT EXISTS Scripts
96 (id INTEGER PRIMARY KEY AUTOINCREMENT,
97 name TEXT, path TEXT, content TEXT)''')
98 self.conn.commit()
99
100 def browse_folder(self):
101 """Browse and load files from a folder with specific extensions, save to database."""
102 self.folder_path = filedialog.askdirectory()
103 if not self.folder_path:
104 return
105 self.load_files()
106
107 def browse_new_database(self):
108 """Browse a new folder as a database source."""
109 self.folder_path = filedialog.askdirectory()
110 if not self.folder_path:
111 return
112 self.load_files()
113
114 def load_files(self):
115 """Load files with allowed extensions into the Listbox and database."""
116 self.file_list.delete(0, tk.END)
117 for file_name in os.listdir(self.folder_path):
118 if any(file_name.endswith(ext) for ext in EXTENSIONS):
119 file_path = os.path.join(self.folder_path, file_name)
120
121 # Insert into Listbox
122 self.file_list.insert(tk.END, file_name) # Only show name with extension
123
124 # Check if file is already in database
125 self.cursor.execute("SELECT * FROM Scripts WHERE path=?", (file_path,))
126 if not self.cursor.fetchone():
127 with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
128 content = file.read()
129 self.cursor.execute("INSERT INTO Scripts (name, path, content) VALUES (?, ?, ?)",
130 (file_name, file_path, content))
131 self.conn.commit()
132
133 def load_selected_file(self, event):
134 """Load selected file content in text viewer."""
135 selected_index = self.file_list.curselection()
136 if not selected_index:
137 return
138
139 # Get the selected file name and fetch the content from the database
140 file_name = self.file_list.get(selected_index[0])
141 self.cursor.execute("SELECT path, content FROM Scripts WHERE name=?", (file_name,))
142 result = self.cursor.fetchone()
143
144 if result:
145 self.current_file, file_content = result
146 # Display content in viewer
147 self.text_viewer.config(state='normal')
148 self.text_viewer.delete(1.0, tk.END)
149 self.text_viewer.insert(tk.END, file_content)
150 self.text_viewer.config(state='disabled')
151
152 def enable_editing(self):
153 """Enable editing mode in the text viewer."""
154 self.text_viewer.config(state='normal')
155
156 def save_file(self):
157 """Save changes to the current file and update the database."""
158 if not self.current_file:
159 messagebox.showwarning("Warning", "No file selected!")
160 return
161
162 file_content = self.text_viewer.get(1.0, tk.END).strip()
163 self.cursor.execute("UPDATE Scripts SET content=? WHERE path=?", (file_content, self.current_file))
164 self.conn.commit()
165 messagebox.showinfo("Info", "File saved successfully!")
166
167 def delete_file(self):
168 """Delete the currently selected file from database and Listbox."""
169 if not self.current_file:
170 messagebox.showwarning("Warning", "No file selected!")
171 return
172
173 self.cursor.execute("DELETE FROM Scripts WHERE path=?", (self.current_file,))
174 self.conn.commit()
175 self.file_list.delete(self.file_list.curselection()[0])
176 self.text_viewer.delete(1.0, tk.END)
177 self.current_file = None
178 messagebox.showinfo("Info", "File deleted successfully!")
179
180 def run_script(self):
181 """Run the selected script if it is executable."""
182 if not self.current_file:
183 messagebox.showwarning("Warning", "No file selected!")
184 return
185
186 if self.current_file.endswith(tuple(EXTENSIONS)):
187 try:
188 if self.current_file.endswith('.ahk'):
189 subprocess.run(['AutoHotkey', self.current_file])
190 else:
191 subprocess.run(self.current_file, shell=True)
192 messagebox.showinfo("Info", "Script executed successfully!")
193 except Exception as e:
194 messagebox.showerror("Error", f"Failed to execute script: {e}")
195 else:
196 messagebox.showwarning("Warning", "Cannot execute this file type.")
197
198 def show_all_scripts(self):
199 """Show all scripts in the database."""
200 self.file_list.delete(0, tk.END)
201 self.cursor.execute("SELECT name FROM Scripts")
202 for (name,) in self.cursor.fetchall():
203 self.file_list.insert(tk.END, name)
204
205 def search_script(self):
206 """Search for a script by name and display results in the Listbox."""
207 query = self.search_entry.get()
208 self.file_list.delete(0, tk.END)
209 self.cursor.execute("SELECT name FROM Scripts WHERE name LIKE ?", ('%' + query + '%',))
210 for (name,) in self.cursor.fetchall():
211 self.file_list.insert(tk.END, name)
212
213 def run_cmd(self):
214 """Run the command in the command entry."""
215 command = self.command_entry.get()
216 if command:
217 try:
218 subprocess.run(command, shell=True)
219 messagebox.showinfo("Info", "Command executed successfully!")
220 except Exception as e:
221 messagebox.showerror("Error", f"Failed to execute command: {e}")
222 else:
223 messagebox.showwarning("Warning", "No command entered!")
224
225 def copy_to_clipboard(self):
226 """Copy selected text from the viewer to the clipboard."""
227 try:
228 selected_text = self.text_viewer.get(tk.SEL_FIRST, tk.SEL_LAST)
229 self.root.clipboard_clear()
230 self.root.clipboard_append(selected_text)
231 messagebox.showinfo("Info", "Copied to clipboard!")
232 except tk.TclError:
233 messagebox.showwarning("Warning", "No text selected!")
234
235
236# Run the application
237if __name__ == "__main__":
238 root = tk.Tk()
239 app = ScriptDataManager(root)
240 root.mainloop()
241