-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser_router.py
More file actions
698 lines (619 loc) · 29.6 KB
/
browser_router.py
File metadata and controls
698 lines (619 loc) · 29.6 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# This code is compiled with:
# "C:\Users\Tuga\AppData\Local\Programs\Python\Python313\Scripts\pyinstaller.exe" --onedir --noconsole --icon "C:\Users\Tuga\Desktop\sandbox\browser_chooser_3\browser_router.ico" browser_router.py
#
# The compiled binary and folder will be used to create an NSIS setup installer.
#
# The exe will be installed to C:\Program Files (x86)\Browser Router\Browser_Router.exe along with the rest of the necessary files.
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import tkinter.font as tkFont
import json
import os
import re
import sys
import subprocess
import winreg
from urllib.parse import urlparse
import shlex
import webbrowser
# Hardcoded download links for browsers
DOWNLOAD_LINKS = {
"Google Chrome": "https://www.google.com/chrome/",
"Pale Moon": "https://www.palemoon.org/",
"Chromium": "https://www.chromium.org/getting-involved/download-chromium",
"Tor Browser": "https://www.torproject.org/download/",
"Mozilla Firefox": "https://www.mozilla.org/firefox/new/",
"Firefox Developer": "https://www.mozilla.org/en-US/firefox/developer/",
"Microsoft Edge": "https://www.microsoft.com/edge",
"Brave Browser": "https://brave.com/download/",
"Opera": "https://www.opera.com/download"
}
# Store config file location in a safe, writable directory
CONFIG_POINTER = os.path.join(os.getenv("LOCALAPPDATA"), "browser_router_config_location.txt")
# Hardcoded browser locations
BROWSER_LOCATIONS = {
"Google Chrome": r"C:\Program Files\Google\Chrome\Application\chrome.exe",
"Pale Moon": r"C:\Program Files\Pale Moon\palemoon.exe",
"Chromium": r"C:\Users\Tuga\AppData\Local\Chromium\Application\chrome.exe",
"Tor Browser": r"C:\Users\Tuga\Desktop\Tor Browser\Browser\firefox.exe",
"Mozilla Firefox": r"C:\Program Files\Mozilla Firefox\firefox.exe",
"Firefox Developer": r"C:\Program Files\Firefox Developer Edition\firefox.exe",
"Microsoft Edge": r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
"Brave Browser": r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
"Opera": os.path.expandvars(r"%LOCALAPPDATA%\Programs\Opera\opera.exe")
}
def get_config_file():
"""Ensure config location is stored in a fixed, writable directory.
When running as a frozen (compiled) binary, the config file is stored
in %LOCALAPPDATA%\Browser Router\browser_rules.json.
"""
if getattr(sys, 'frozen', False):
config_dir = os.path.join(os.getenv("LOCALAPPDATA"), "Browser Router")
if not os.path.exists(config_dir):
os.makedirs(config_dir)
return os.path.join(config_dir, "browser_rules.json")
if os.path.exists(CONFIG_POINTER):
with open(CONFIG_POINTER, "r") as f:
return f.read().strip()
root = tk.Tk()
root.withdraw()
file_path = filedialog.asksaveasfilename(
title="Choose location for browser_rules.json",
defaultextension=".json",
filetypes=[("JSON files", "*.json")],
initialfile="browser_rules.json"
)
if not file_path:
messagebox.showerror("Error", "No config file selected. Exiting.")
sys.exit(1)
with open(CONFIG_POINTER, "w") as f:
f.write(file_path)
return file_path
CONFIG_FILE = get_config_file()
def load_config():
"""Load the JSON configuration file, ensuring it's valid."""
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r") as f:
data = json.load(f)
if not isinstance(data, dict):
raise ValueError("Invalid config format")
return data
except (json.JSONDecodeError, ValueError):
messagebox.showerror("Error", "Config file is corrupted. Resetting...")
return {"rules": [], "default_browser": None, "user_browsers": {}}
return {"rules": [], "default_browser": None, "user_browsers": {}}
def save_config(config):
"""Save the configuration to JSON."""
with open(CONFIG_FILE, "w") as f:
json.dump(config, f, indent=4)
def match_url(url, rules):
"""Match the full URL against the configured rules."""
parsed_url = urlparse(url)
full_url = f"{parsed_url.netloc}{parsed_url.path}"
hostname = parsed_url.hostname or ""
for rule in rules:
pattern = rule["pattern"].replace(".", r"\.").replace("*", r".*")
if rule["pattern"].startswith("*."):
base_domain = rule["pattern"][2:]
if hostname == base_domain:
return rule["browser"]
if re.fullmatch(pattern, hostname) or re.fullmatch(pattern, full_url):
return rule["browser"]
return None
def open_url_in_browser(browser_path, url):
"""Ensure the full URL is passed correctly to the chosen browser."""
try:
subprocess.Popen([browser_path, url], shell=False)
except Exception as e:
messagebox.showerror("Error", f"Failed to open browser:\n{e}")
def handle_url_from_cmd():
"""Handle incoming URL when the script is launched via HTTP/HTTPS."""
if len(sys.argv) > 1 and sys.argv[1].startswith("http"):
url = sys.argv[-1]
config = load_config()
rules = config.get("rules", [])
browser = match_url(url, rules)
if browser:
open_url_in_browser(browser, url)
elif config.get("default_browser"):
open_url_in_browser(config["default_browser"], url)
else:
try:
os.startfile(url)
except Exception as e:
messagebox.showerror("Error", f"Could not open URL:\n{url}\n\n{e}")
def ask_update_download_cancel(title, message):
"""
Create a custom dialog with three buttons:
- Update Path
- Download
- Cancel
Returns a string: "update", "download", or "cancel".
"""
dialog = tk.Toplevel()
dialog.title(title)
dialog.resizable(False, False)
# If user closes window via the X, treat it as "cancel".
user_choice = ["cancel"]
def on_close():
user_choice[0] = "cancel"
dialog.destroy()
dialog.protocol("WM_DELETE_WINDOW", on_close)
label = tk.Label(dialog, text=message, wraplength=400)
label.pack(padx=20, pady=10)
btn_frame = tk.Frame(dialog)
btn_frame.pack(pady=10)
def update_click():
user_choice[0] = "update"
dialog.destroy()
def download_click():
user_choice[0] = "download"
dialog.destroy()
def cancel_click():
user_choice[0] = "cancel"
dialog.destroy()
update_btn = tk.Button(btn_frame, text="Update Path", width=12, command=update_click)
update_btn.pack(side="left", padx=5)
download_btn = tk.Button(btn_frame, text="Download", width=12, command=download_click)
download_btn.pack(side="left", padx=5)
cancel_btn = tk.Button(btn_frame, text="Cancel", width=12, command=cancel_click)
cancel_btn.pack(side="left", padx=5)
# Center the dialog
dialog.update_idletasks()
w = dialog.winfo_width()
h = dialog.winfo_height()
ws = dialog.winfo_screenwidth()
hs = dialog.winfo_screenheight()
x = (ws // 2) - (w // 2)
y = (hs // 2) - (h // 2)
dialog.geometry(f"+{x}+{y}")
dialog.grab_set()
dialog.wait_window()
return user_choice[0]
def check_browser_installation(browser_name, browser_path, config=None):
"""
Check if the selected browser is installed (i.e. its path exists).
If not, show a 3-button prompt: Update Path, Download, Cancel.
Returns the updated (or original) path if installation is confirmed,
or None if the user chooses Cancel or never provides a valid path.
The 'config' parameter (if provided) is used to check if a default browser is set.
"""
if os.path.exists(browser_path):
return browser_path
user_choice = ask_update_download_cancel(
"Browser Not Installed",
f"The selected browser '{browser_name}' does not appear to be installed.\n"
f"(path not found:\n{browser_path})\n\n"
"Please choose an option:"
)
if user_choice == "update":
new_path = filedialog.askopenfilename(title=f"Select installation for {browser_name}")
if new_path and os.path.exists(new_path):
# Guard against selecting your own EXE.
try:
if os.path.samefile(new_path, sys.executable):
messagebox.showerror(
"Error",
"You selected the same EXE as Browser Router for the browser path!\n"
"That will cause recursion. Please pick a real browser."
)
return None
except Exception:
# os.path.samefile might fail on some systems, so ignore it if it does.
pass
return new_path
else:
messagebox.showerror("Error", "Invalid path selected. Browser path not updated.")
return None
elif user_choice == "download":
download_link = DOWNLOAD_LINKS.get(browser_name)
if not download_link:
messagebox.showinfo("Download", "No download link available for this browser.")
return None
try:
# If user has set a default browser in the app and it exists, use it.
if config and config.get("default_browser") and os.path.exists(config.get("default_browser")):
open_url_in_browser(config.get("default_browser"), download_link)
return None
# Otherwise, force Microsoft Edge.
edge_path_1 = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
edge_path_2 = r"C:\Program Files\Microsoft\Edge\Application\msedge.exe"
if os.path.exists(edge_path_1):
subprocess.Popen([edge_path_1, download_link])
elif os.path.exists(edge_path_2):
subprocess.Popen([edge_path_2, download_link])
else:
webbrowser.open(download_link)
except Exception as e:
messagebox.showerror("Error", f"Failed to open download link:\n{e}")
return None
else:
# user_choice == "cancel"
return None
class RuleManagerApp:
def __init__(self, root):
self.root = root
self.root.title("URL Rule Manager")
# Sorting state
self.sort_column = None
self.sort_reverse = False
# Load config and ensure "user_browsers" exists.
self.config = load_config()
if "user_browsers" not in self.config:
self.config["user_browsers"] = {}
self.rules = self.config.get("rules", [])
# Merge hardcoded list with any user modifications.
self.browsers = self.get_available_browsers()
# Ensure each rule has a friendly "display_browser" (for older rules).
for rule in self.rules:
if "display_browser" not in rule:
for name, path in self.browsers.items():
if path == rule["browser"]:
rule["display_browser"] = name
break
else:
rule["display_browser"] = os.path.basename(rule["browser"])
save_config(self.config)
self.frame = tk.Frame(root)
self.frame.pack(padx=10, pady=10)
self.pattern_label = tk.Label(self.frame, text="Domain Pattern (e.g., *.example.com):")
self.pattern_label.grid(row=0, column=0, sticky="w")
self.pattern_entry = tk.Entry(self.frame, width=40)
self.pattern_entry.grid(row=1, column=0, padx=5, pady=5)
self.browser_var = tk.StringVar()
self.browser_dropdown = ttk.Combobox(self.frame, textvariable=self.browser_var, state="readonly", width=40)
self.browser_dropdown.grid(row=1, column=1, padx=5)
self.browser_dropdown["values"] = list(self.browsers.keys())
self.manual_browser_button = tk.Button(self.frame, text="Browse...", command=self.choose_browser)
self.manual_browser_button.grid(row=1, column=2, padx=5)
# Button to manage the browser list.
self.manage_browsers_button = tk.Button(self.frame, text="Manage Browsers", command=self.manage_browsers)
self.manage_browsers_button.grid(row=1, column=3, padx=5)
self.add_button = tk.Button(self.frame, text="Add Rule", command=self.add_rule)
self.add_button.grid(row=2, column=0, columnspan=2, pady=5)
# Treeview for rules.
self.tree_frame = tk.Frame(self.frame)
self.tree_frame.grid(row=3, column=0, columnspan=4, pady=10, sticky="nsew")
self.rule_tree = ttk.Treeview(
self.tree_frame,
columns=("pattern", "display_browser"),
show="headings",
selectmode="browse"
)
self.rule_tree.heading("pattern", text="Rule", command=lambda: self.sort_treeview("pattern"))
self.rule_tree.heading("display_browser", text="Browser", command=lambda: self.sort_treeview("display_browser"))
self.rule_tree.column("pattern", anchor="w", stretch=True)
self.rule_tree.column("display_browser", anchor="w", stretch=True)
self.rule_tree.pack(side="left", fill="both", expand=True)
self.tree_scrollbar = tk.Scrollbar(self.tree_frame, orient="vertical", command=self.rule_tree.yview)
self.rule_tree.configure(yscrollcommand=self.tree_scrollbar.set)
self.tree_scrollbar.pack(side="right", fill="y")
self.rule_tree.bind("<Double-1>", self.load_rule_from_tree)
self.update_treeview()
self.delete_button = tk.Button(self.frame, text="Delete Selected", command=self.delete_rule)
self.delete_button.grid(row=4, column=0, columnspan=4, pady=5)
self.default_browser_button = tk.Button(self.frame, text="Set Default Browser", command=self.set_default_browser)
self.default_browser_button.grid(row=5, column=0, columnspan=4, pady=5)
default_browser_text = "None"
if self.config.get("default_browser"):
browser_path = self.config["default_browser"]
for name, path in self.browsers.items():
if path == browser_path:
default_browser_text = name
break
else:
default_browser_text = os.path.basename(browser_path)
self.default_browser_label = tk.Label(self.frame, text="Default Browser: " + default_browser_text)
self.default_browser_label.grid(row=6, column=0, columnspan=4, pady=5)
def get_available_browsers(self):
"""
Use the hardcoded BROWSER_LOCATIONS as the default.
If config already has a "user_browsers" list, use that.
The returned dictionary is sorted by key.
"""
user_defined = self.config.get("user_browsers", {})
if not user_defined:
self.config["user_browsers"] = BROWSER_LOCATIONS.copy()
save_config(self.config)
user_defined = self.config["user_browsers"]
return dict(sorted(user_defined.items(), key=lambda x: x[0]))
def update_treeview(self):
"""Refresh the rules Treeview."""
for item in self.rule_tree.get_children():
self.rule_tree.delete(item)
for index, rule in enumerate(self.rules):
display_browser = rule.get("display_browser", rule["browser"])
self.rule_tree.insert("", "end", iid=str(index), values=(rule["pattern"], display_browser))
def choose_browser(self):
"""Allow manual selection of a browser executable."""
path = filedialog.askopenfilename(title="Select Browser Executable")
if path:
self.browser_var.set(path)
def add_rule(self):
"""
Add or update a rule.
Prevent empty rule patterns or browser selections.
If the pattern exists, ask the user if they want to update it.
Also verify that the selected browser's path exists or offer update/download/cancel.
"""
pattern = self.pattern_entry.get().strip()
selected_browser = self.browser_var.get().strip()
if not pattern or not selected_browser:
messagebox.showerror("Error", "Please enter a valid rule pattern and select a browser.")
return
# Determine browser path and display name.
if selected_browser in self.browsers:
browser_path = self.browsers[selected_browser]
display_browser = selected_browser
else:
browser_path = selected_browser
display_browser = os.path.basename(browser_path)
# Check if the browser path exists; if not, prompt with 3-button dialog.
new_path = check_browser_installation(display_browser, browser_path, self.config)
if new_path is None:
return # User canceled or downloaded, so do not add/update rule.
# Possibly updated path
browser_path = new_path
# If the user typed a custom name that isn't in self.browsers, keep display_browser as a basename.
if selected_browser not in self.browsers:
display_browser = os.path.basename(browser_path)
# Check if the rule pattern already exists
existing_rule = next((r for r in self.rules if r["pattern"] == pattern), None)
if existing_rule:
confirm = messagebox.askyesno(
"Rule Exists",
f"A rule with pattern '{pattern}' already exists.\nDo you want to update it with the new browser?"
)
if confirm:
existing_rule["browser"] = browser_path
existing_rule["display_browser"] = display_browser
save_config(self.config)
self.update_treeview()
return
else:
new_rule = {"pattern": pattern, "browser": browser_path, "display_browser": display_browser}
self.rules.append(new_rule)
self.config["rules"] = self.rules
save_config(self.config)
self.update_treeview()
def delete_rule(self):
"""Delete the selected rule from the Treeview and config, with confirmation."""
selected = self.rule_tree.selection()
if not selected:
messagebox.showwarning("Selection Required", "Please select a rule first before attempting to delete.")
return
confirm = messagebox.askyesno("Confirm Delete", "Are you sure you want to delete the selected rule?")
if not confirm:
return
index = int(selected[0])
del self.rules[index]
self.config["rules"] = self.rules
save_config(self.config)
self.update_treeview()
def load_rule_from_tree(self, event):
"""Load the double-clicked rule into the input fields for editing."""
selected = self.rule_tree.selection()
if selected:
index = int(selected[0])
rule = self.rules[index]
self.pattern_entry.delete(0, tk.END)
self.pattern_entry.insert(0, rule["pattern"])
self.browser_var.set(rule.get("display_browser", rule["browser"]))
def set_default_browser(self):
"""
Set the default browser to be used if no rules match.
If no browser is selected, or if the browser path doesn't exist,
prompt the user to update the path or download the browser.
"""
selected = self.browser_var.get().strip()
if not selected:
messagebox.showerror("Error", "Please select a browser before setting it as default.")
return
if selected in self.browsers:
browser_path = self.browsers[selected]
display_browser = selected
else:
browser_path = selected
display_browser = os.path.basename(browser_path)
# Check if the browser path exists; if not, prompt with 3-button dialog.
new_path = check_browser_installation(display_browser, browser_path, self.config)
if new_path is None:
messagebox.showinfo("Info", "Default browser not changed.")
return
self.config["default_browser"] = new_path
save_config(self.config)
messagebox.showinfo("Success", f"Default browser set to: {display_browser}")
self.default_browser_label.config(text="Default Browser: " + display_browser)
def import_config(self):
"""Import browser rules from a JSON file."""
file_path = filedialog.askopenfilename(title="Import Config", filetypes=[("JSON files", "*.json")])
if not file_path:
return
try:
with open(file_path, "r") as f:
imported_config = json.load(f)
if isinstance(imported_config, dict) and "rules" in imported_config and "default_browser" in imported_config:
self.config = imported_config
if "user_browsers" not in self.config:
self.config["user_browsers"] = {}
self.rules = imported_config["rules"]
for rule in self.rules:
if "display_browser" not in rule:
for key, val in self.get_available_browsers().items():
if val == rule["browser"]:
rule["display_browser"] = key
break
else:
rule["display_browser"] = os.path.basename(rule["browser"])
save_config(self.config)
self.update_treeview()
default_browser_text = "None"
if self.config.get("default_browser"):
browser_path = self.config["default_browser"]
for name, path in self.get_available_browsers().items():
if path == browser_path:
default_browser_text = name
break
else:
default_browser_text = os.path.basename(browser_path)
self.default_browser_label.config(text="Default Browser: " + default_browser_text)
messagebox.showinfo("Success", "Configuration imported successfully.")
else:
messagebox.showerror("Error", "Invalid JSON format.")
except Exception as e:
messagebox.showerror("Error", f"Failed to import config:\n{e}")
def export_config(self):
"""Export browser rules to a JSON file."""
file_path = filedialog.asksaveasfilename(
title="Export Config",
defaultextension=".json",
filetypes=[("JSON files", "*.json")],
initialfile="browser_rules.json"
)
if not file_path:
return
try:
with open(file_path, "w") as f:
json.dump(self.config, f, indent=4)
messagebox.showinfo("Success", "Configuration exported successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to export config:\n{e}")
def sort_treeview(self, column):
"""
Sort the Treeview by the given column.
Clicking the same column again toggles ascending/descending order.
"""
if self.sort_column == column:
self.sort_reverse = not self.sort_reverse
else:
self.sort_column = column
self.sort_reverse = False
self.rules.sort(key=lambda r: r[column], reverse=self.sort_reverse)
self.update_treeview()
# ----- New Methods for Managing Browsers -----
def manage_browsers(self):
"""Open a dialog for managing the hardcoded browser list (stored in config)."""
top = tk.Toplevel(self.root)
top.title("Manage Browsers")
top.update_idletasks()
w = top.winfo_width()
h = top.winfo_height()
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws // 2) - (w // 2)
y = (hs // 2) - (h // 2)
top.geometry(f"+{x}+{y}")
list_frame = tk.Frame(top)
list_frame.pack(padx=10, pady=10, fill="both", expand=True)
self.browser_listbox = tk.Listbox(list_frame, width=50, height=10)
self.browser_listbox.pack(side="left", fill="both", expand=True)
scrollbar = tk.Scrollbar(list_frame, orient="vertical", command=self.browser_listbox.yview)
scrollbar.pack(side="right", fill="y")
self.browser_listbox.config(yscrollcommand=scrollbar.set)
user_browsers = self.config.get("user_browsers", {})
for name in user_browsers:
self.browser_listbox.insert(tk.END, name)
button_frame = tk.Frame(top)
button_frame.pack(padx=10, pady=10)
add_btn = tk.Button(button_frame, text="Add Browser", command=lambda: self.add_browser_dialog(top))
add_btn.pack(side="left", padx=5)
remove_btn = tk.Button(button_frame, text="Remove Selected", command=self.remove_selected_browser)
remove_btn.pack(side="left", padx=5)
close_btn = tk.Button(button_frame, text="Close", command=top.destroy)
close_btn.pack(side="left", padx=5)
self.browser_listbox_window = top
def add_browser_dialog(self, parent):
"""Open a dialog to add a new browser (name and path) and center it on the screen."""
dialog = tk.Toplevel(parent)
dialog.title("Add Browser")
dialog.update_idletasks()
w = dialog.winfo_width()
h = dialog.winfo_height()
ws = dialog.winfo_screenwidth()
hs = dialog.winfo_screenheight()
x = (ws // 2) - (w // 2)
y = (hs // 2) - (h // 2)
dialog.geometry(f"+{x}+{y}")
tk.Label(dialog, text="Browser Name:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
name_entry = tk.Entry(dialog, width=40)
name_entry.grid(row=0, column=1, padx=5, pady=5)
tk.Label(dialog, text="Browser Path:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
path_entry = tk.Entry(dialog, width=40)
path_entry.grid(row=1, column=1, padx=5, pady=5)
browse_btn = tk.Button(dialog, text="Browse...", command=lambda: self.browse_for_browser_path(path_entry))
browse_btn.grid(row=1, column=2, padx=5, pady=5)
ok_btn = tk.Button(dialog, text="OK", command=lambda: self.add_browser(name_entry.get().strip(), path_entry.get().strip(), dialog))
ok_btn.grid(row=2, column=0, padx=5, pady=5)
cancel_btn = tk.Button(dialog, text="Cancel", command=dialog.destroy)
cancel_btn.grid(row=2, column=1, padx=5, pady=5)
def browse_for_browser_path(self, entry_widget):
"""Allow user to browse for a browser executable and update the entry widget."""
path = filedialog.askopenfilename(title="Select Browser Executable")
if path:
entry_widget.delete(0, tk.END)
entry_widget.insert(0, path)
def add_browser(self, name, path, dialog):
"""Add a new browser (or update an existing one) in the config."""
if not name or not path:
messagebox.showerror("Error", "Both name and path must be provided.")
return
user_browsers = self.config.get("user_browsers", {})
if name in user_browsers:
confirm = messagebox.askyesno("Browser Exists", f"A browser with name '{name}' already exists. Update it?")
if not confirm:
return
user_browsers[name] = path
self.config["user_browsers"] = user_browsers
save_config(self.config)
if hasattr(self, 'browser_listbox') and self.browser_listbox:
self.browser_listbox.delete(0, tk.END)
for n in user_browsers:
self.browser_listbox.insert(tk.END, n)
self.browsers = self.get_available_browsers()
self.browser_dropdown["values"] = list(self.browsers.keys())
dialog.destroy()
def remove_selected_browser(self):
"""Remove the selected browser from the user-defined list in config."""
selection = self.browser_listbox.curselection()
if selection:
index = selection[0]
name = self.browser_listbox.get(index)
confirm = messagebox.askyesno("Confirm Remove", f"Are you sure you want to remove browser '{name}'?")
if confirm:
user_browsers = self.config.get("user_browsers", {})
if name in user_browsers:
del user_browsers[name]
self.config["user_browsers"] = user_browsers
save_config(self.config)
self.browser_listbox.delete(index)
self.browsers = self.get_available_browsers()
self.browser_dropdown["values"] = list(self.browsers.keys())
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1].startswith("http"):
handle_url_from_cmd()
else:
root = tk.Tk()
default_font = tkFont.nametofont("TkDefaultFont")
current_size = default_font.cget("size")
new_size = int(current_size * 1.25)
default_font.configure(size=new_size)
style = ttk.Style(root)
style.configure("Treeview", font=(default_font.cget("family"), new_size), rowheight=new_size + 8)
style.configure("Treeview.Heading", font=(default_font.cget("family"), new_size))
app = RuleManagerApp(root)
# Menubar with "File" menu for Import/Export
menubar = tk.Menu(root)
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="Import Config", command=app.import_config)
file_menu.add_command(label="Export Config", command=app.export_config)
menubar.add_cascade(label="File", menu=file_menu)
root.config(menu=menubar)
root.resizable(False, False)
root.update_idletasks()
width = root.winfo_width()
height = root.winfo_height()
x = (root.winfo_screenwidth() // 2) - (width // 2)
y = (root.winfo_screenheight() // 2) - (height // 2)
root.geometry(f"+{x}+{y}")
root.mainloop()