-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1612 lines (1420 loc) · 77.4 KB
/
main.py
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import json
import os
import re
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QWidget, QLineEdit,
QPushButton, QHBoxLayout, QLabel, QComboBox, QDialog, QFormLayout, QTabWidget, QTextEdit, QCheckBox,
QFileDialog, QMessageBox, QListWidget, QListWidgetItem, QToolBar, QStatusBar,
QAction, QStyle, QSizePolicy, QSpacerItem, QScrollArea, QInputDialog, QMenu, QSystemTrayIcon,
QProgressBar, QDialogButtonBox
)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage, QWebEngineSettings, QWebEngineDownloadItem
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor
from PyQt5.QtCore import QUrl, Qt, QSize, QTimer, QEvent, QRect, QDir
from PyQt5.QtGui import QIcon, QKeySequence, QFont, QPalette, QColor, QDesktopServices
import requests
from addon import ExtensionManager
from MojoPrivacy import PrivacyEngine, PrivacyPage, initialize_privacy
PRIMARY_COLOR = "#3B82F6"
SECONDARY_COLOR = "#475569"
TEXT_COLOR = "#ffffff"
ACCENT_COLOR = "#F59E0B"
BACKGROUND_COLOR = "#F3F4F6"
DARK_MODE_BACKGROUND = "#111827"
DARK_MODE_TEXT = "#D1D5DB"
DARK_MODE_ACCENT = "#1F2A44"
LIGHT_MODE_BACKGROUND = "#FFFFFF"
LIGHT_MODE_TEXT = "#1F2937"
LIGHT_MODE_ACCENT = "#F3F4F6"
BORDER_RADIUS = "8px"
BUTTON_BORDER_RADIUS = "5px"
BUTTON_HOVER_COLOR = "#60A5FA"
BUTTON_PRESSED_COLOR = "#2563EB"
UI_FONT = QFont("Nunito", 13)
FALLBACK_FONT = QFont("Arial", 13)
class ExtensionsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.setWindowTitle("Extensions")
self.setGeometry(300, 300, 450, 350)
self.setFont(UI_FONT)
layout = QVBoxLayout()
layout.setContentsMargins(15, 15, 15, 15)
layout.setSpacing(12)
self.extensions_list = QListWidget()
self.extensions_list.setStyleSheet(self.parent.get_list_style())
self.parent.extension_manager.load_extensions()
for ext_name in self.parent.extension_manager.extensions.keys():
item = QListWidgetItem(ext_name)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked if self.parent.extension_manager.extension_status.get(ext_name) == 'enabled' else Qt.Unchecked)
self.extensions_list.addItem(item)
layout.addWidget(self.extensions_list)
buttons_layout = QHBoxLayout()
enable_button = QPushButton("Enable")
enable_button.setStyleSheet(self.parent.get_button_style(PRIMARY_COLOR, BUTTON_HOVER_COLOR, BUTTON_PRESSED_COLOR))
enable_button.clicked.connect(self.enable_selected_extension)
disable_button = QPushButton("Disable")
disable_button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
disable_button.clicked.connect(self.disable_selected_extension)
download_button = QPushButton("Download")
download_button.setStyleSheet(self.parent.get_button_style(ACCENT_COLOR, "#FBBF24", "#D97706"))
download_button.clicked.connect(self.download_extension)
store_button = QPushButton("Get from MojoX")
store_button.setStyleSheet(self.parent.get_button_style(ACCENT_COLOR, "#FBBF24", "#D97706"))
store_button.clicked.connect(self.fetch_store_extensions)
buttons_layout.addWidget(enable_button)
buttons_layout.addWidget(disable_button)
buttons_layout.addWidget(download_button)
buttons_layout.addWidget(store_button)
buttons_layout.addStretch()
layout.addLayout(buttons_layout)
close_button = QPushButton("Close")
close_button.setStyleSheet(self.parent.get_button_style(PRIMARY_COLOR, BUTTON_HOVER_COLOR, BUTTON_PRESSED_COLOR))
close_button.clicked.connect(self.close_dialog)
layout.addWidget(close_button)
self.setLayout(layout)
def enable_selected_extension(self):
selected = self.extensions_list.currentItem()
if selected and selected.checkState() != Qt.Checked:
ext_name = selected.text()
self.parent.extension_manager.enable_extension(ext_name)
selected.setCheckState(Qt.Checked)
def disable_selected_extension(self):
selected = self.extensions_list.currentItem()
if selected and selected.checkState() == Qt.Checked:
ext_name = selected.text()
self.parent.extension_manager.disable_extension(ext_name)
selected.setCheckState(Qt.Unchecked)
def download_extension(self):
url, ok = QInputDialog.getText(self, "Download Extension", "Enter the URL of the .js extension:")
if ok and url:
ext_name = self.parent.extension_manager.download_extension(url)
if ext_name:
item = QListWidgetItem(ext_name)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Unchecked)
self.extensions_list.addItem(item)
else:
QMessageBox.warning(self, "Download Failed", "Failed to download the extension.", QMessageBox.Ok)
def fetch_store_extensions(self):
extensions = self.parent.extension_manager.fetch_store_extensions()
if not extensions:
QMessageBox.warning(self, "Fetch Failed", "Failed to fetch extensions from the store.", QMessageBox.Ok)
return
dialog = QDialog(self)
dialog.setWindowTitle("MojoX Extension Store")
dialog.setGeometry(300, 300, 600, 400)
layout = QVBoxLayout()
store_list = QListWidget()
store_list.setSpacing(6)
for ext in extensions:
item_widget = QWidget()
item_layout = QHBoxLayout()
item_layout.setContentsMargins(6, 6, 6, 6)
text_widget = QWidget()
text_layout = QVBoxLayout()
name_label = QLabel(ext["name"])
name_label.setStyleSheet("font-weight: bold; font-size: 14px;")
desc_label = QLabel(ext["description"])
desc_label.setWordWrap(True)
desc_label.setStyleSheet("font-size: 12px;")
author_label = QLabel(f"By: {ext['author']}")
author_label.setStyleSheet("font-size: 10px; color: #888;")
text_layout.addWidget(name_label)
text_layout.addWidget(desc_label)
text_layout.addWidget(author_label)
text_widget.setLayout(text_layout)
item_layout.addWidget(text_widget)
checkbox = QCheckBox()
item_layout.addWidget(checkbox)
item_widget.setLayout(item_layout)
item = QListWidgetItem()
item.setSizeHint(item_widget.sizeHint())
item.setData(Qt.UserRole, ext["url"])
item.setData(Qt.UserRole + 1, ext["name"])
store_list.addItem(item)
store_list.setItemWidget(item, item_widget)
layout.addWidget(store_list)
download_button = QPushButton("Download Selected")
download_button.setStyleSheet(self.parent.get_button_style(PRIMARY_COLOR, BUTTON_HOVER_COLOR, BUTTON_PRESSED_COLOR))
download_button.clicked.connect(lambda: self.download_selected_extensions(store_list, dialog))
layout.addWidget(download_button)
dialog.setLayout(layout)
dialog.exec_()
def download_selected_extensions(self, store_list, dialog):
for i in range(store_list.count()):
item = store_list.item(i)
checkbox = store_list.itemWidget(item).findChild(QCheckBox)
if checkbox and checkbox.isChecked():
url = item.data(Qt.UserRole)
ext_name = self.parent.extension_manager.download_extension(url)
if ext_name:
list_item = QListWidgetItem(ext_name)
list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)
list_item.setCheckState(Qt.Unchecked)
self.extensions_list.addItem(list_item)
dialog.accept()
def close_dialog(self):
for i in range(self.extensions_list.count()):
item = self.extensions_list.item(i)
ext_name = item.text()
is_enabled = item.checkState() == Qt.Checked
if is_enabled:
self.parent.extension_manager.enable_extension(ext_name)
else:
self.parent.extension_manager.disable_extension(ext_name)
self.accept()
class SettingsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.setWindowTitle("Settings")
self.setGeometry(300, 300, 700, 600)
self.setFont(UI_FONT)
self.setWindowFlags(self.windowFlags() | Qt.WindowMinMaxButtonsHint)
self.tabs = QTabWidget()
self.tabs.setStyleSheet(self.get_tab_widget_style())
self.tabs.setFont(UI_FONT)
self.general_tab = QWidget()
self.security_tab = QWidget()
self.data_management_tab = QWidget()
self.performance_tab = QWidget()
self.about_tab = QWidget()
self.tabs.addTab(self.general_tab, QIcon("icons/general.png") if os.path.exists("icons/general.png") else QIcon.fromTheme("preferences-desktop"), "General")
self.tabs.addTab(self.security_tab, "Security")
self.tabs.addTab(self.data_management_tab, "Data Management")
self.tabs.addTab(self.performance_tab, "Performance")
self.tabs.addTab(self.about_tab, "About Us")
self.setup_general_tab()
self.setup_security_tab()
self.setup_data_management_tab()
self.setup_performance_tab()
self.setup_about_tab()
self.button_layout = QHBoxLayout()
self.save_button = QPushButton("Save Settings")
self.save_button.setStyleSheet(self.parent.get_button_style(PRIMARY_COLOR, BUTTON_HOVER_COLOR, BUTTON_PRESSED_COLOR))
self.save_button.clicked.connect(self.save_settings)
self.cancel_button = QPushButton("Cancel")
self.cancel_button.setStyleSheet(self.parent.get_button_style(SECONDARY_COLOR, "#6B7280", "#374151"))
self.cancel_button.clicked.connect(self.reject)
self.button_layout.addStretch()
self.button_layout.addWidget(self.cancel_button)
self.button_layout.addWidget(self.save_button)
self.layout = QVBoxLayout()
self.layout.addWidget(self.tabs)
self.layout.addLayout(self.button_layout)
self.layout.setSpacing(12)
self.setLayout(self.layout)
self.update_cache_size()
self.apply_theme()
def get_tab_widget_style(self):
theme = self.parent.theme
tab_text_color, tab_background_color, tab_selected_background = (
(DARK_MODE_TEXT, DARK_MODE_ACCENT, DARK_MODE_BACKGROUND) if theme == "Dark"
else (LIGHT_MODE_TEXT, LIGHT_MODE_ACCENT, LIGHT_MODE_BACKGROUND)
)
return (
f"QTabWidget::pane {{ border: none; border-radius: {BORDER_RADIUS}; "
f"background-color: {tab_selected_background}; padding: 12px; }}"
f"QTabBar::tab {{ background-color: {tab_background_color}; color: {tab_text_color}; "
f"border: 1px solid {'#4B5563' if theme == 'Dark' else '#D1D5DB'}; border-bottom: none; "
f"padding: 12px 24px; border-top-left-radius: {BORDER_RADIUS}; "
f"border-top-right-radius: {BORDER_RADIUS}; margin-right: 2px; font-weight: 500; font-size: 14px; }}"
f"QTabBar::tab:selected {{ background: {tab_selected_background}; "
f"border-bottom: 3px solid {PRIMARY_COLOR}; font-weight: bold; }}"
"QTabBar::tab:!selected {{ margin-top: 3px; }}"
f"QTabBar::tab:hover {{ background: {'#374151' if theme == 'Dark' else '#E5E7EB'}; }}"
"QTabWidget::tab-bar {{ alignment: center; }}"
)
def setup_general_tab(self):
layout = QFormLayout()
layout.setContentsMargins(15, 15, 15, 15)
layout.setSpacing(12)
self.general_tab.setLayout(layout)
self.home_page_input = QLineEdit()
self.home_page_input.setStyleSheet(self.parent.get_input_style())
self.home_page_input.setPlaceholderText("Enter your home page URL...")
layout.addRow(QLabel("Home Page:").setStyleSheet(self.parent.get_label_style()), self.home_page_input)
self.search_engine_dropdown = QComboBox()
self.search_engine_dropdown.setStyleSheet(self.parent.get_input_style())
self.search_engine_dropdown.addItems(["Lilo", "Mojeek", "Google", "Bing", "DuckDuckGo", "Yahoo", "Ecosia", "Qwant", "Brave", "SearchXNG"])
layout.addRow(QLabel("Search Engine:").setStyleSheet(self.parent.get_label_style()), self.search_engine_dropdown)
self.theme_dropdown = QComboBox()
self.theme_dropdown.setStyleSheet(self.parent.get_input_style())
self.theme_dropdown.addItems(["Dark", "Light", "System"])
self.theme_dropdown.currentTextChanged.connect(self.preview_theme)
layout.addRow(QLabel("Theme:").setStyleSheet(self.parent.get_label_style()), self.theme_dropdown)
self.new_tab_behavior = QComboBox()
self.new_tab_behavior.setStyleSheet(self.parent.get_input_style())
self.new_tab_behavior.addItems(["Home Page", "Blank Page", "Last Page"])
layout.addRow(QLabel("New Tab Opens:").setStyleSheet(self.parent.get_label_style()), self.new_tab_behavior)
def setup_security_tab(self):
layout = QFormLayout()
layout.setContentsMargins(15, 15, 15, 15)
layout.setSpacing(12)
self.security_tab.setLayout(layout)
checkboxes = [
("javascript_checkbox", "Enable JavaScript", True),
("popup_checkbox", "Block Pop-ups", True),
("mixed_content_checkbox", "Block Mixed Content", True),
("dnt_checkbox", "Send Do Not Track", True),
("third_party_cookies_checkbox", "Block Third-Party Cookies", True),
("tracker_block_checkbox", "Block Trackers/Ads", False),
("clear_on_exit_checkbox", "Clear Data on Exit", False),
("private_browsing_checkbox", "Enable Private Browsing", False),
("https_only_checkbox", "Enforce HTTPS-Only", self.parent.privacy_engine.https_only),
("proxy_checkbox", "Enable Proxy", True),
("fingerprint_protection", "Enable Fingerprint Protection", False)
]
for name, text, default in checkboxes:
checkbox = QCheckBox(text)
checkbox.setStyleSheet(self.parent.get_checkbox_style())
checkbox.setChecked(default)
setattr(self, name, checkbox)
layout.addRow(checkbox)
self.proxy_dropdown = QComboBox()
self.proxy_dropdown.setStyleSheet(self.parent.get_input_style())
self.proxy_dropdown.addItem("Random Proxy")
self.proxy_dropdown.addItems(self.parent.privacy_engine.proxy_list)
layout.addRow(QLabel("Select Proxy:").setStyleSheet(self.parent.get_label_style()), self.proxy_dropdown)
self.clear_cookies_button = QPushButton("Clear Cookies")
self.clear_cookies_button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
self.clear_cookies_button.clicked.connect(self.clear_cookies)
layout.addWidget(self.clear_cookies_button)
def setup_data_management_tab(self):
layout = QVBoxLayout()
layout.setContentsMargins(15, 15, 15, 15)
layout.setSpacing(12)
self.data_management_tab.setLayout(layout)
buttons = [
("clear_cache_button", "Clear Cache", self.clear_cache),
("clear_history_button", "Clear History", self.clear_history),
("clear_all_data_button", "Clear All Data", self.clear_all_data)
]
for name, text, handler in buttons:
button = QPushButton(text)
button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
button.clicked.connect(handler)
setattr(self, name, button)
layout.addWidget(button)
self.cache_size_label = QLabel("Cache Size: Calculating...")
self.cache_size_label.setStyleSheet(self.parent.get_label_style())
layout.addWidget(self.cache_size_label)
auto_clear_layout = QHBoxLayout()
auto_clear_label = QLabel("Auto-clear interval:")
auto_clear_label.setStyleSheet(self.parent.get_label_style())
self.auto_clear_interval = QComboBox()
self.auto_clear_interval.setStyleSheet(self.parent.get_input_style())
self.auto_clear_interval.addItems(["Never", "Daily", "Weekly", "Monthly"])
auto_clear_layout.addWidget(auto_clear_label)
auto_clear_layout.addWidget(self.auto_clear_interval)
layout.addLayout(auto_clear_layout)
layout.addStretch()
def setup_performance_tab(self):
layout = QFormLayout()
layout.setContentsMargins(15, 15, 15, 15)
layout.setSpacing(12)
self.performance_tab.setLayout(layout)
self.hardware_acceleration = QCheckBox("Enable Hardware Acceleration")
self.hardware_acceleration.setStyleSheet(self.parent.get_checkbox_style())
self.hardware_acceleration.setChecked(True)
layout.addRow(self.hardware_acceleration)
self.preload_pages = QCheckBox("Preload Pages for Faster Browsing")
self.preload_pages.setStyleSheet(self.parent.get_checkbox_style())
layout.addRow(self.preload_pages)
self.cache_size_limit = QComboBox()
self.cache_size_limit.setStyleSheet(self.parent.get_input_style())
self.cache_size_limit.addItems(["50 MB", "100 MB", "250 MB", "500 MB", "Unlimited"])
layout.addRow(QLabel("Cache Size Limit:").setStyleSheet(self.parent.get_label_style()), self.cache_size_limit)
def setup_about_tab(self):
layout = QVBoxLayout()
layout.setContentsMargins(15, 15, 15, 15)
layout.setSpacing(12)
self.about_tab.setLayout(layout)
self.about_text = QTextEdit()
self.about_text.setReadOnly(True)
self.about_text.setStyleSheet(self.parent.get_input_style())
self.about_text.setText(
"Mojo Browser | v0.2.5 Alpha\n\n"
"Developed using PyQt5 & Python.\nEnhanced Features:\n"
"- Dark/Light/System themes\n- Multiple search engines\n- Advanced security options\n"
"- Performance optimizations\n- Proxy & fingerprint protection\n"
"- System tray integration\n- Improved UI/UX\n- JavaScript extension support from mojox.org\n"
"** Mojo Browser ** : an idea by Muhammad Noraeii"
"\n"
"GitHub: https://Github.com/Muhammad-Noraeii\nhttps://Github.com/Guguss-31/"
)
layout.addWidget(self.about_text)
def preview_theme(self, theme):
temp_theme = theme if theme != "System" else ("Dark" if QApplication.palette().color(QPalette.Window).lightness() < 128 else "Light")
self.apply_theme(temp_theme)
def update_cache_size(self):
try:
profile = QWebEngineProfile.defaultProfile()
size_mb = self.get_directory_size(profile.cachePath()) / (1024 * 1024)
self.cache_size_label.setText(f"Cache Size: {size_mb:.2f} MB")
except Exception as e:
self.cache_size_label.setText(f"Cache Size: Error ({str(e)})")
def get_directory_size(self, directory):
total_size = 0
try:
for dirpath, _, filenames in os.walk(directory):
for f in filenames:
total_size += os.path.getsize(os.path.join(dirpath, f))
except Exception:
pass
return total_size
def clear_cookies(self):
try:
current_tab = self.parent.tabs.currentWidget()
if isinstance(current_tab, QWebEngineView):
current_tab.page().profile().clearHttpCache()
current_tab.page().profile().clearAllVisitedLinks()
QMessageBox.information(self.parent, "Cookies Cleared", "Cookies have been cleared.", QMessageBox.Ok)
else:
QMessageBox.warning(self.parent, "Error", "Current tab is not a web page.", QMessageBox.Ok)
except Exception as e:
QMessageBox.warning(self.parent, "Error", f"Failed to clear cookies: {str(e)}", QMessageBox.Ok)
def clear_cache(self):
QWebEngineProfile.defaultProfile().clearHttpCache()
self.update_cache_size()
QMessageBox.information(self.parent, "Cache Cleared", "Cache has been cleared.", QMessageBox.Ok)
def clear_history(self):
self.parent.tabs.currentWidget().page().profile().clearAllVisitedLinks()
self.parent.clear_history_data()
def clear_all_data(self):
if QMessageBox.question(self.parent, "Confirm", "Clear all browsing data?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes:
self.parent.settings_persistence.clear_all_private_data()
self.update_cache_size()
def save_settings(self):
settings = self.parent.settings_persistence.privacy_settings
settings.update({
"do_not_track": self.dnt_checkbox.isChecked(),
"block_third_party_cookies": self.third_party_cookies_checkbox.isChecked(),
"clear_data_on_exit": self.clear_on_exit_checkbox.isChecked(),
"private_browsing": self.private_browsing_checkbox.isChecked(),
"block_trackers": self.tracker_block_checkbox.isChecked(),
"fingerprint_protection": self.fingerprint_protection.isChecked()
})
self.parent.privacy_engine.https_only = self.https_only_checkbox.isChecked()
if self.proxy_checkbox.isChecked():
selected_proxy = self.proxy_dropdown.currentText()
if selected_proxy == "Random Proxy":
self.parent.privacy_engine.set_random_proxy()
else:
self.parent.privacy_engine.set_random_proxy(specific_proxy=selected_proxy)
else:
self.parent.privacy_engine.proxy_settings = None
self.parent.statusBar().showMessage("Proxy disabled", 5000)
self.parent.privacy_engine.save_privacy_settings()
self.parent.apply_settings(
self.home_page_input.text(),
self.search_engine_dropdown.currentText(),
self.theme_dropdown.currentText(),
self.javascript_checkbox.isChecked(),
self.popup_checkbox.isChecked(),
self.mixed_content_checkbox.isChecked(),
self.new_tab_behavior.currentText(),
self.hardware_acceleration.isChecked(),
self.preload_pages.isChecked(),
self.cache_size_limit.currentText()
)
self.accept()
def apply_theme(self, theme=None):
theme = theme or self.parent.theme
dialog_background, text_color, input_background, input_border = (
(DARK_MODE_BACKGROUND, DARK_MODE_TEXT, DARK_MODE_ACCENT, "#4B5563") if theme == "Dark"
else (LIGHT_MODE_BACKGROUND, LIGHT_MODE_TEXT, LIGHT_MODE_ACCENT, "#D1D5DB")
)
self.setStyleSheet(
f"QDialog {{ background-color: {dialog_background}; color: {text_color}; "
f"border-radius: {BORDER_RADIUS}; padding: 15px; }}"
f"QLabel {{ color: {text_color}; font-size: 14px; }}"
f"QTabWidget::tab-bar {{ font-size: 14px; font-family: 'Nunito'; }}"
)
self.save_button.setStyleSheet(self.parent.get_button_style(PRIMARY_COLOR, BUTTON_HOVER_COLOR, BUTTON_PRESSED_COLOR))
self.cancel_button.setStyleSheet(self.parent.get_button_style(SECONDARY_COLOR, "#6B7280", "#374151"))
self.clear_cache_button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
self.clear_cookies_button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
self.clear_history_button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
self.clear_all_data_button.setStyleSheet(self.parent.get_button_style("#EF4444", "#F87171", "#DC2626"))
self.tabs.setStyleSheet(self.get_tab_widget_style())
class PrivacyInterceptor(QWebEngineUrlRequestInterceptor):
def __init__(self, parent):
super().__init__()
self.parent = parent
def interceptRequest(self, info):
settings = self.parent.settings_persistence.privacy_settings
if settings["block_third_party_cookies"]:
info.setHttpHeader(b"Cookie", b"")
if settings["do_not_track"]:
info.setHttpHeader(b"DNT", b"1")
if settings["block_trackers"]:
url = info.requestUrl().toString()
if any(tracker in url.lower() for tracker in ["ads.", "tracking", "analytics", "doubleclick"]):
info.block(True)
if settings["fingerprint_protection"]:
info.setHttpHeader(b"User-Agent", b"MojoBrowser/0.2 (Generic)")
self.enhance_fingerprint_protection(info)
def enhance_fingerprint_protection(self, info):
if self.parent.settings_persistence.privacy_settings["fingerprint_protection"]:
info.setHttpHeader(b"Accept-Language", b"en-US,en;q=0.9")
info.setHttpHeader(b"Accept", b"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
js_spoof = """
Object.defineProperty(window, 'screen', {
value: { width: 1920, height: 1080, availWidth: 1920, availHeight: 1080 },
writable: false
});
"""
self.parent.tabs.currentWidget().page().runJavaScript(js_spoof)
class DownloadDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Downloads")
self.setGeometry(300, 300, 500, 400)
self.active_downloads = 0
self.parent_browser = parent
self.layout = QVBoxLayout()
self.downloads_layout = QVBoxLayout()
self.scroll_area = QScrollArea()
self.scroll_widget = QWidget()
self.scroll_widget.setLayout(self.downloads_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setStyleSheet(f"QScrollArea {{ border: 1px solid {'#4B5563' if parent.theme == 'Dark' else '#D1D5DB'}; border-radius: {BORDER_RADIUS}; }}")
self.layout.addWidget(self.scroll_area)
self.button_layout = QHBoxLayout()
self.close_button = QPushButton("Close")
self.close_button.setStyleSheet(parent.get_button_style(PRIMARY_COLOR, BUTTON_HOVER_COLOR, BUTTON_PRESSED_COLOR))
self.close_button.clicked.connect(self.close)
self.button_layout.addStretch()
self.button_layout.addWidget(self.close_button)
self.layout.addLayout(self.button_layout)
self.setLayout(self.layout)
self.setStyleSheet(
f"QDialog {{ background-color: {DARK_MODE_BACKGROUND if parent.theme == 'Dark' else LIGHT_MODE_BACKGROUND}; "
f"color: {DARK_MODE_TEXT if parent.theme == 'Dark' else LIGHT_MODE_TEXT}; border-radius: {BORDER_RADIUS}; padding: 15px; }}"
f"QLabel {{ font-size: 14px; padding: 6px; }}"
f"QProgressBar {{ border: 1px solid {'#4B5563' if parent.theme == 'Dark' else '#D1D5DB'}; border-radius: 5px; text-align: center; }}"
"QProgressBar::chunk { background-color: #3B82F6; border-radius: 3px; }"
)
def add_download(self, download):
self.active_downloads += 1
download_widget = QWidget()
download_layout = QHBoxLayout()
label = QLabel(download.suggestedFileName())
label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
progress = QProgressBar()
progress.setMaximum(100)
progress.setMinimumWidth(120)
progress.setMaximumWidth(220)
speed_label = QLabel("0 KB/s")
speed_label.setMinimumWidth(70)
time_label = QLabel("Calculating...")
time_label.setMinimumWidth(100)
cancel_button = QPushButton("Cancel")
pause_button = QPushButton("Pause")
pause_button.setStyleSheet(self.parent_browser.get_button_style("#F59E0B", "#FBBF24", "#D97706"))
download_layout.addWidget(label)
download_layout.addWidget(progress)
download_layout.addWidget(speed_label)
download_layout.addWidget(time_label)
download_layout.addWidget(pause_button)
download_layout.addWidget(cancel_button)
download_widget.setLayout(download_layout)
self.downloads_layout.addWidget(download_widget)
last_received = [0]
start_time = QTimer()
start_time.start()
def update_speed(received, total):
elapsed_time = start_time.elapsed() / 1000
speed = (received - last_received[0]) / 1024
speed_label.setText(f"{speed:.1f} KB/s")
last_received[0] = received
progress.setValue(int((received / total) * 100))
if speed > 0:
remaining_time = (total - received) / (speed * 1024)
time_label.setText(f"{int(remaining_time // 60)}m {int(remaining_time % 60)}s remaining")
else:
time_label.setText("Calculating...")
download.downloadProgress.connect(update_speed)
download.finished.connect(lambda: self.on_download_finished(download, download_widget))
download.stateChanged.connect(lambda state: self.on_state_changed(state, download_widget, pause_button))
cancel_button.clicked.connect(download.cancel)
pause_button.clicked.connect(lambda: download.pause() if download.state() == QWebEngineDownloadItem.DownloadInProgress else download.resume())
def on_download_finished(self, download, widget):
self.active_downloads -= 1
if download.state() == QWebEngineDownloadItem.DownloadCompleted:
widget.findChild(QLabel).setText(f"{download.suggestedFileName()} - Completed")
widget.findChild(QPushButton).hide()
if self.active_downloads == 0:
QTimer.singleShot(1000, self.close)
def on_state_changed(self, state, widget, pause_button):
if state == QWebEngineDownloadItem.DownloadCancelled:
self.active_downloads -= 1
widget.findChild(QLabel).setText(f"{widget.findChild(QLabel).text()} - Cancelled")
widget.findChild(QPushButton, "Cancel").hide()
if self.active_downloads == 0:
QTimer.singleShot(1000, self.close)
elif state == QWebEngineDownloadItem.DownloadInterrupted:
pause_button.setText("Resume")
elif state == QWebEngineDownloadItem.DownloadInProgress:
pause_button.setText("Pause")
class MojoBrowser(QMainWindow):
DEFAULT_HOME_PAGE = "https://mojox.org/search"
def __init__(self):
super().__init__()
self.setWindowTitle("Mojo Browser")
self.setGeometry(100, 100, 1280, 800)
self.setFont(UI_FONT)
self.setWindowIcon(QIcon("icons/Mojo.ico"))
self.settings_persistence = SettingsPersistence(self)
self.extension_manager = ExtensionManager(self)
self.privacy_engine = initialize_privacy(self)
self.profiles = {"Default": QWebEngineProfile.defaultProfile()}
self.downloads = {}
self.private_profile = None
self.download_dialog = None
self._initialize_settings()
self._initialize_ui()
self._initialize_timers()
def _initialize_settings(self):
self.extension_manager.load_extension_status()
self.extension_manager.load_extensions()
self.settings_persistence.load_settings()
def _initialize_ui(self):
self.central_widget = QWidget(self)
self.setCentralWidget(self.central_widget)
self.layout = QVBoxLayout(self.central_widget)
self.layout.setContentsMargins(10, 10, 10, 10)
self.layout.setSpacing(10)
self.create_tool_bar()
self.create_tabs()
self.setup_system_tray()
self.setup_download_manager()
self.status_bar = QStatusBar()
self.status_bar.setFont(UI_FONT)
self.setStatusBar(self.status_bar)
self.apply_styles()
self.add_new_tab(QUrl(self.home_page))
self.setup_shortcuts()
def _initialize_timers(self):
self.cache_timer = QTimer(self)
self.cache_timer.timeout.connect(self.update_cache_size_periodic)
self.cache_timer.start(30000)
self.performance_timer = QTimer(self)
self.performance_timer.timeout.connect(self.optimize_performance)
self.performance_timer.start(60000)
self.tab_suspension_timer = QTimer(self)
self.tab_suspension_timer.timeout.connect(self.suspend_inactive_tabs)
self.tab_suspension_timer.start(120000)
self.memory_optimization_timer = QTimer(self)
self.memory_optimization_timer.timeout.connect(self.optimize_memory_usage)
self.memory_optimization_timer.start(60000)
def optimize_memory_usage(self):
current_browser = self.tabs.currentWidget()
for i in range(self.tabs.count()):
browser = self.tabs.widget(i)
if browser and browser != current_browser:
browser.page().setLifecycleState(QWebEnginePage.LifecycleState.Discarded)
browser.page().setBackgroundColor(QColor(DARK_MODE_BACKGROUND if self.theme == "Dark" else LIGHT_MODE_BACKGROUND))
QWebEngineProfile.defaultProfile().clearHttpCache()
def create_tool_bar(self):
self.tool_bar = QToolBar("Navigation", self)
self.addToolBar(Qt.TopToolBarArea, self.tool_bar)
self.tool_bar.setIconSize(QSize(28, 28))
self.tool_bar.setFont(UI_FONT)
self.tool_bar.setStyleSheet(self.get_toolbar_style())
self.tool_bar.setMovable(True)
actions = [
("back.png", "go-previous", "Back", "Go to previous page", self.browser_back),
("forward.png", "go-next", "Forward", "Go to next page", self.browser_forward),
(None, "view-refresh", "Reload", "Reload page", self.browser_reload),
(None, "process-stop", "Stop", "Stop loading", self.browser_stop),
("home.png", "go-home", "Home", "Go to homepage", self.go_home),
(None, "zoom-in", "Zoom In", "Increase zoom", self.zoom_in),
(None, "zoom-out", "Zoom Out", "Decrease zoom", self.zoom_out),
(None, "view-fullscreen", "Fullscreen", "Toggle fullscreen", self.toggle_fullscreen),
]
for icon_file, theme_icon, text, tip, connect in actions:
icon = QIcon(f"icons/{icon_file}") if icon_file and os.path.exists(f"icons/{icon_file}") else QIcon.fromTheme(theme_icon)
action = QAction(icon, text, self)
action.setStatusTip(tip)
action.triggered.connect(connect)
self.tool_bar.addAction(action)
self.address_bar = QLineEdit()
self.address_bar.setStyleSheet(self.get_input_style())
self.address_bar.setMinimumWidth(320)
self.address_bar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.address_bar.returnPressed.connect(self.load_page)
self.address_bar.setClearButtonEnabled(True)
self.tool_bar.addWidget(self.address_bar)
go_action = QAction(QIcon("icons/search.png") if os.path.exists("icons/search.png") else QIcon.fromTheme("go-jump"), "Go", self)
go_action.setStatusTip("Go to address or search")
go_action.triggered.connect(self.load_page)
self.tool_bar.addAction(go_action)
self.tool_bar.addSeparator()
additional_actions = [
("new_tab.png", "document-new", "New Tab", "Open new tab", self.add_new_tab),
(None, "emblem-favorite", "Bookmark", "Bookmark page", self.settings_persistence.add_bookmark),
(None, "bookmarks", "Bookmarks", "View bookmarks", self.settings_persistence.view_bookmarks),
(None, "document-open-recent", "History", "View history", self.settings_persistence.view_history),
("settings.png", "preferences-system", "Settings", "Open settings", self.open_settings),
("exten.png", "applications-other", "Extensions", "Manage extensions", self.open_extensions),
]
for icon_file, theme_icon, text, tip, connect in additional_actions:
icon = QIcon(f"icons/{icon_file}") if icon_file and os.path.exists(f"icons/{icon_file}") else QIcon.fromTheme(theme_icon)
action = QAction(icon, text, self)
action.setStatusTip(tip)
action.triggered.connect(connect)
self.tool_bar.addAction(action)
reader_action = QAction(QIcon.fromTheme("document-preview"), "Reader Mode", self)
reader_action.setStatusTip("Toggle reader mode")
reader_action.triggered.connect(self.toggle_reader_mode)
self.tool_bar.addAction(reader_action)
profile_action = QAction(QIcon.fromTheme("system-users"), "Switch Profile", self)
profile_action.setStatusTip("Switch user profile")
profile_action.triggered.connect(self.switch_profile)
self.tool_bar.addAction(profile_action)
def get_toolbar_style(self):
theme = self.theme
return (
f"QToolBar {{ background-color: {DARK_MODE_ACCENT if theme == 'Dark' else LIGHT_MODE_ACCENT}; "
f"color: {DARK_MODE_TEXT if theme == 'Dark' else LIGHT_MODE_TEXT}; "
f"border-radius: {BORDER_RADIUS}; padding: 10px; spacing: 10px; }}"
f"QToolButton {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {PRIMARY_COLOR}, stop:1 {self.adjust_color(PRIMARY_COLOR, -20)}); "
f"color: {TEXT_COLOR}; border: none; border-radius: {BUTTON_BORDER_RADIUS}; padding: 12px; "
f"font-size: 14px; }}"
f"QToolButton:hover {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {BUTTON_HOVER_COLOR}, stop:1 {self.adjust_color(BUTTON_HOVER_COLOR, -20)}); }}"
f"QToolButton:pressed {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {BUTTON_PRESSED_COLOR}, stop:1 {self.adjust_color(BUTTON_PRESSED_COLOR, -20)}); }}"
)
def apply_styles(self):
theme = self.theme
main_background, main_text_color, input_background, input_border = (
(DARK_MODE_BACKGROUND, DARK_MODE_TEXT, DARK_MODE_ACCENT, "#4B5563") if theme == "Dark"
else (LIGHT_MODE_BACKGROUND, LIGHT_MODE_TEXT, LIGHT_MODE_ACCENT, "#D1D5DB")
)
app_stylesheet = (
f"QMainWindow {{ background-color: {main_background}; color: {main_text_color}; font-size: 14px; }}"
f"QToolBar {{ background-color: {input_background}; }}"
f"QStatusBar {{ background-color: {input_background}; }}"
)
self.setStyleSheet(app_stylesheet)
self.tabs.setStyleSheet(self.get_tab_style())
self.statusBar().setStyleSheet(self.get_statusbar_style())
self.tool_bar.setStyleSheet(self.get_toolbar_style())
self.address_bar.setStyleSheet(self.get_input_style())
if hasattr(self, 'settings_dialog') and self.settings_dialog:
self.settings_dialog.apply_theme()
def open_extensions(self):
dialog = ExtensionsDialog(self)
dialog.exec_()
def create_tabs(self):
self.tabs = QTabWidget()
self.tabs.setTabsClosable(True)
self.tabs.setMovable(True)
self.tabs.tabCloseRequested.connect(self.close_tab)
self.tabs.currentChanged.connect(self.update_address_bar)
self.tabs.setContextMenuPolicy(Qt.CustomContextMenu)
self.tabs.customContextMenuRequested.connect(self.tab_context_menu)
self.tabs.setStyleSheet(self.get_tab_style())
self.tabs.setFont(UI_FONT)
self.tabs.setDocumentMode(True)
self.layout.addWidget(self.tabs)
def setup_system_tray(self):
icon_path = "icons/app_icon.png"
tray_icon = QIcon(icon_path) if os.path.exists(icon_path) else QIcon.fromTheme("web-browser")
if not tray_icon.isNull():
self.tray_icon = QSystemTrayIcon(tray_icon, self)
tray_menu = QMenu()
tray_menu.addAction("Restore", self.showNormal)
tray_menu.addAction("New Tab", lambda: self.add_new_tab())
tray_menu.addAction("Quit", self.close)
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.activated.connect(self.tray_activated)
self.tray_icon.show()
else:
print("Warning: No valid icon found for the system tray.")
def tray_activated(self, reason):
if reason == QSystemTrayIcon.DoubleClick:
self.showNormal()
def get_tab_style(self):
theme = self.theme
tab_text_color, tab_background_color, tab_selected_background = (
(DARK_MODE_TEXT, DARK_MODE_ACCENT, DARK_MODE_BACKGROUND) if theme == "Dark"
else (LIGHT_MODE_TEXT, LIGHT_MODE_ACCENT, LIGHT_MODE_BACKGROUND)
)
return (
"QTabBar::close-button { image: url('icons/close_tab.png'); width: 14px; height: 14px; subcontrol-position: right; }"
f"QTabWidget::pane {{ border: none; border-radius: {BORDER_RADIUS}; background-color: {tab_selected_background}; padding: 8px; }}"
f"QTabBar::tab {{ background-color: {tab_background_color}; color: {tab_text_color}; "
f"border: 1px solid {'#4B5563' if theme == 'Dark' else '#D1D5DB'}; border-bottom: none; "
f"padding: 10px 20px; border-top-left-radius: {BORDER_RADIUS}; border-top-right-radius: {BORDER_RADIUS}; font-size: 14px; }}"
f"QTabBar::tab:selected {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {tab_selected_background}, stop:1 {self.adjust_color(tab_selected_background, -10)}); "
f"border-bottom: 3px solid {PRIMARY_COLOR}; font-weight: bold; }}"
f"QTabBar::tab:hover:!selected {{ background: {'#374151' if theme == 'Dark' else '#E5E7EB'}; }}"
)
def get_statusbar_style(self):
theme = self.theme
return (
f"QStatusBar {{ background-color: {DARK_MODE_ACCENT if theme == 'Dark' else LIGHT_MODE_ACCENT}; "
f"color: {DARK_MODE_TEXT if theme == 'Dark' else LIGHT_MODE_TEXT}; border-radius: {BORDER_RADIUS}; padding: 6px; font-size: 14px; }}"
)
def get_button_style(self, background_color, hover_color, pressed_color):
text_color = DARK_MODE_TEXT if self.theme == "Dark" else LIGHT_MODE_TEXT
return (
f"QPushButton {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {background_color}, stop:1 {self.adjust_color(background_color, -20)}); "
f"color: {TEXT_COLOR}; border: none; border-radius: {BUTTON_BORDER_RADIUS}; padding: 12px 24px; "
f"font-weight: 500; font-size: 14px; }}"
f"QPushButton:hover {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {hover_color}, stop:1 {self.adjust_color(hover_color, -20)}); }}"
f"QPushButton:pressed {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {pressed_color}, stop:1 {self.adjust_color(pressed_color, -20)}); }}"
)
def get_input_style(self):
theme = self.theme
return (
f"QLineEdit, QComboBox, QTextEdit {{ background-color: {DARK_MODE_ACCENT if theme == "Dark" else LIGHT_MODE_ACCENT}; "
f"color: {DARK_MODE_TEXT if theme == "Dark" else LIGHT_MODE_TEXT}; border: 1px solid {'#4B5563' if theme == "Dark" else '#D1D5DB'}; "
f"border-radius: {BORDER_RADIUS}; padding: 10px; font-size: 14px; }}"
f"QLineEdit:focus, QComboBox:focus {{ border: 2px solid {PRIMARY_COLOR}; }}"
)
def get_checkbox_style(self):
theme = self.theme
return f"QCheckBox {{ color: {DARK_MODE_TEXT if self.theme == 'Dark' else LIGHT_MODE_TEXT}; padding: 8px; font-weight: 500; font-size: 14px; }}"
def get_label_style(self):
theme = self.theme
return f"QLabel {{ color: {DARK_MODE_TEXT if theme == 'Dark' else LIGHT_MODE_TEXT}; font-weight: 600; font-size: 14px; }}"
def get_list_style(self):
theme = self.theme
list_background, list_text_color, list_selected_background = (
(DARK_MODE_ACCENT, DARK_MODE_TEXT, "#374151") if theme == "Dark"
else (LIGHT_MODE_ACCENT, LIGHT_MODE_TEXT, "#E5E7EB")
)
return (
f"QListWidget {{ background-color: {list_background}; color: {list_text_color}; "
f"border: 1px solid {'#4B5563' if theme == 'Dark' else '#D1D5DB'}; border-radius: {BORDER_RADIUS}; padding: 10px; font-size: 14px; }}"
"QListWidget::item { padding: 10px; }"
f"QListWidget::item:selected {{ background-color: {list_selected_background}; }}"
)
def adjust_color(self, hex_color, amount):
r, g, b = tuple(int(hex_color[i:i+2], 16) for i in (1, 3, 5))
r, g, b = [min(max(c + amount, 0), 255) for c in (r, g, b)]
return f"#{r:02x}{g:02x}{b:02x}"
def add_new_tab(self, url=None):
browser = QWebEngineView(self) if self.settings_persistence.privacy_settings["private_browsing"] else QWebEngineView()
if self.settings_persistence.privacy_settings["private_browsing"]:
if not self.private_profile:
self.private_profile = QWebEngineProfile("PrivateProfile", self)
self.private_profile.setCachePath("")
self.private_profile.setPersistentStoragePath("")
page = PrivacyPage(self.private_profile, browser)
page.setPrivacyEngine(self.privacy_engine)
browser.setPage(page)
else:
page = PrivacyPage(QWebEngineProfile.defaultProfile(), browser)
page.setPrivacyEngine(self.privacy_engine)
browser.setPage(page)
self.apply_webengine_settings(browser)
if not url:
if self.new_tab_behavior == "Home Page":
url = QUrl(self.home_page)
elif self.new_tab_behavior == "Blank Page":
url = QUrl("about:blank")
elif self.new_tab_behavior == "Last Page" and self.history:
url = QUrl(self.history[-1])
else:
url = QUrl(self.home_page)
browser.setUrl(url)
i = self.tabs.addTab(browser, "New Tab")
self.tabs.setCurrentIndex(i)
browser.urlChanged.connect(lambda u, b=browser: (self.update_tab_title(b, u), self.update_history(u), self.update_address_bar(i)))
browser.loadStarted.connect(lambda: self.statusBar().showMessage("Loading..."))
browser.loadProgress.connect(lambda p: self.statusBar().showMessage(f"Loading... {p}%"))
browser.loadFinished.connect(lambda ok, b=browser: (self.load_finished(ok, b), self.extension_manager.inject_extensions(b)))
browser.titleChanged.connect(lambda title, b=browser: self.update_tab_title(b, title))
browser.iconChanged.connect(lambda icon, b=browser: self.update_tab_icon(b, icon))
browser.setContextMenuPolicy(Qt.CustomContextMenu)
browser.customContextMenuRequested.connect(lambda pos: self.show_web_context_menu(pos, browser))
browser.settings().setAttribute(QWebEngineSettings.ErrorPageEnabled, False)
browser.settings().setAttribute(QWebEngineSettings.FullScreenSupportEnabled, False)
def update_tab_icon(self, browser, icon):
index = self.tabs.indexOf(browser)
if index >= 0:
self.tabs.setTabIcon(index, icon)
def close_tab(self, index):
browser = self.tabs.widget(index)
if browser:
browser.deleteLater()
if self.tabs.count() > 1:
self.tabs.removeTab(index)
else:
self.close()
def update_tab_title(self, browser, title):
index = self.tabs.indexOf(browser)
if index >= 0:
title_str = title.toString() if isinstance(title, QUrl) else title
self.tabs.setTabText(index, title_str[:30] + "..." if len(title_str) > 30 else title_str)
self.tabs.setTabToolTip(index, title_str)
def update_address_bar(self, index):
if index >= 0:
browser = self.tabs.widget(index)
if browser:
self.address_bar.setText(browser.url().toString())
self.statusBar().showMessage(f"Zoom: {int(browser.zoomFactor() * 100)}%", 2000)
def load_page(self):
url = self.address_bar.text().strip()
browser = self.tabs.currentWidget()
if not url or not browser:
return
if re.match(r'^(https?://)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/.*)?$', url):
browser.setUrl(QUrl(url if url.startswith(('http://', 'https://')) else f"https://{url}"))
elif re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', url):