Certainly! Let's address both of your requests:
-
Fixing Incognito Mode:
The incognito mode wasn't functioning as expected because the custom QWebEngineProfile wasn't properly isolated or connected. To ensure incognito mode works correctly, we need to make sure that the profile is truly off-the-record and doesn't share any data with the default profile. Additionally, it's essential to handle the creation of QWebEnginePage correctly.
-
Adding levbrowser://flags/ with Quic and Kyber Flags:
We'll add a custom URL scheme (levbrowser://flags/) that, when navigated to, displays a dialog allowing the user to toggle the Quic and Kyber flags. Since QWebEngineView doesn't inherently recognize custom URL schemes, we'll intercept URL changes and handle them accordingly.
Here's the updated and corrected code with detailed explanations:
import sys
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QTabWidget, QVBoxLayout, QWidget,
QLineEdit, QToolBar, QAction, QInputDialog, QMessageBox, QPushButton, QHBoxLayout
)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage
from PyQt5.QtCore import QUrl, QObject, pyqtSignal
from PyQt5.QtGui import QIcon
class BrowserTab(QWidget):
def __init__(self, start_url="https://www.google.com", incognito=False, user_agent=None, flags=None):
super().__init__()
self.layout = QVBoxLayout(self)
# Навигационная панель внутри вкладки
nav_bar = QHBoxLayout()
self.back_btn = QPushButton("Назад")
self.forward_btn = QPushButton("Вперед")
self.reload_btn = QPushButton("Обновить")
self.zoom_in_btn = QPushButton("Увеличить")
self.zoom_out_btn = QPushButton("Уменьшить")
nav_bar.addWidget(self.back_btn)
nav_bar.addWidget(self.forward_btn)
nav_bar.addWidget(self.reload_btn)
nav_bar.addWidget(self.zoom_in_btn)
nav_bar.addWidget(self.zoom_out_btn)
self.layout.addLayout(nav_bar)
# Поле ввода URL
self.url_bar = QLineEdit()
self.url_bar.returnPressed.connect(self.navigate_to_url)
self.layout.addWidget(self.url_bar)
# Веб-просмотр
self.browser = QWebEngineView()
self.layout.addWidget(self.browser)
# Настройка профиля для инкогнито и user-agent
if incognito:
self.profile = QWebEngineProfile(self)
self.profile.setOffTheRecord(True)
self.page = QWebEnginePage(self.profile, self.browser)
self.browser.setPage(self.page)
else:
self.profile = QWebEngineProfile.defaultProfile()
self.page = self.browser.page()
if user_agent:
self.profile.setHttpUserAgent(user_agent)
# Обработка специальных URL схем
self.page.urlChanged.connect(self.handle_special_urls)
# Установка начального URL
self.browser.setUrl(QUrl(start_url))
# Подключение сигналов к кнопкам
self.back_btn.clicked.connect(self.browser.back)
self.forward_btn.clicked.connect(self.browser.forward)
self.reload_btn.clicked.connect(self.browser.reload)
self.zoom_in_btn.clicked.connect(self.zoom_in)
self.zoom_out_btn.clicked.connect(self.zoom_out)
self.browser.urlChanged.connect(self.update_url_bar)
self.browser.titleChanged.connect(self.update_parent_title)
# Flags
self.flags = flags if flags is not None else {"Quic": False, "Kyber": False}
if self.flags["Quic"]:
self.profile.setHttpUserAgent(self.profile.httpUserAgent() + " QuicEnabled")
if self.flags["Kyber"]:
self.profile.setHttpUserAgent(self.profile.httpUserAgent() + " KyberEnabled")
def navigate_to_url(self):
url = self.url_bar.text()
if not url.startswith(("http://", "https://", "levbrowser://")):
url = "http://" + url
self.browser.setUrl(QUrl(url))
def update_url_bar(self, q):
self.url_bar.setText(q.toString())
def update_parent_title(self, title):
"""Обновляет заголовок вкладки в основном окне."""
parent = self.parent()
while parent and not isinstance(parent, AdvancedBrowser):
parent = parent.parent()
if parent:
index = parent.tab_widget.indexOf(self)
if index != -1:
parent.tab_widget.setTabText(index, title)
def zoom_in(self):
current = self.browser.zoomFactor()
self.browser.setZoomFactor(current + 0.1)
def zoom_out(self):
current = self.browser.zoomFactor()
self.browser.setZoomFactor(current - 0.1)
def handle_special_urls(self, url):
if url.scheme() == "levbrowser" and url.host() == "flags":
# Prevent the webview from navigating to the special URL
self.browser.setUrl(QUrl("about:blank"))
self.show_flags_dialog()
def show_flags_dialog(self):
dialog = FlagsDialog(self.flags, self)
if dialog.exec_():
# Update flags based on user input
self.flags["Quic"], self.flags["Kyber"] = dialog.get_flags()
# Recreate the profile with new flags
self.profile = QWebEngineProfile(self)
self.profile.setOffTheRecord(self.profile.isOffTheRecord())
if self.flags["Quic"]:
self.profile.setHttpUserAgent(self.profile.httpUserAgent() + " QuicEnabled")
if self.flags["Kyber"]:
self.profile.setHttpUserAgent(self.profile.httpUserAgent() + " KyberEnabled")
self.page = QWebEnginePage(self.profile, self.browser)
self.browser.setPage(self.page)
# Reload the current page to apply new flags
self.browser.reload()
class FlagsDialog(QMessageBox):
def __init__(self, current_flags, parent=None):
super().__init__(parent)
self.setWindowTitle("Настройки Флагов")
self.setIcon(QMessageBox.Question)
self.setText("Выберите флаги:")
self.quic_btn = QPushButton("Quic", self)
self.quic_btn.setCheckable(True)
self.quic_btn.setChecked(current_flags.get("Quic", False))
self.kyber_btn = QPushButton("Kyber", self)
self.kyber_btn.setCheckable(True)
self.kyber_btn.setChecked(current_flags.get("Kyber", False))
self.layout().addWidget(self.quic_btn, 1, 1)
self.layout().addWidget(self.kyber_btn, 2, 1)
self.addButton(QMessageBox.Ok)
self.addButton(QMessageBox.Cancel)
def get_flags(self):
return self.quic_btn.isChecked(), self.kyber_btn.isChecked()
class AdvancedBrowser(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("LevBrowser")
self.resize(1024, 768)
# Создание вкладок
self.tab_widget = QTabWidget()
self.tab_widget.setTabsClosable(True)
self.tab_widget.tabCloseRequested.connect(self.close_current_tab)
self.setCentralWidget(self.tab_widget)
# Создание панели инструментов
nav_bar = QToolBar("Навигация")
self.addToolBar(nav_bar)
# Действия панели инструментов
new_tab_action = QAction("Новая вкладка", self)
new_tab_action.setIcon(QIcon.fromTheme("tab-new"))
new_tab_action.triggered.connect(self.add_new_tab)
nav_bar.addAction(new_tab_action)
change_ua_action = QAction("Сменить User-Agent", self)
change_ua_action.setIcon(QIcon.fromTheme("preferences-system"))
change_ua_action.triggered.connect(self.change_user_agent)
nav_bar.addAction(change_ua_action)
incognito_action = QAction("Инкогнито", self)
incognito_action.setIcon(QIcon.fromTheme("face-monster"))
incognito_action.triggered.connect(self.enable_incognito_mode)
nav_bar.addAction(incognito_action)
# Добавление первой вкладки
self.add_new_tab()
def add_new_tab(self, incognito=False, user_agent=None, start_url="https://www.google.com", flags=None):
new_tab = BrowserTab(start_url, incognito, user_agent, flags)
index = self.tab_widget.addTab(new_tab, "Новая вкладка")
self.tab_widget.setCurrentIndex(index)
def close_current_tab(self, index):
if self.tab_widget.count() < 2:
# Если открыта только одна вкладка, подтвердите закрытие приложения
reply = QMessageBox.question(
self, 'Закрыть браузер',
"Это последняя вкладка. Хотите закрыть браузер?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No
)
if reply == QMessageBox.Yes:
self.close()
else:
self.tab_widget.removeTab(index)
def current_tab(self):
return self.tab_widget.currentWidget()
def change_user_agent(self):
user_agent, ok = QInputDialog.getText(self, "Сменить User-Agent", "Введите новый User-Agent:")
if ok and user_agent:
self.add_new_tab(user_agent=user_agent)
def enable_incognito_mode(self):
self.add_new_tab(incognito=True)
def main():
app = QApplication(sys.argv)
app.setApplicationName("LevBrowser")
browser = AdvancedBrowser()
browser.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Detailed Explanation of Changes:
-
Fixing Incognito Mode:
-
Proper Parenting of QWebEngineProfile:
self.profile = QWebEngineProfile(self)
By setting the parent to self, we ensure that the profile is correctly managed within the BrowserTab.
-
Handling Flags Appropriately:
The original implementation didn't account for the persistence or interaction between flags and the profile. We've introduced a flags dictionary to manage feature toggles like Quic and Kyber.
-
Recreating the Profile When Flags Change:
When flags are updated, we recreate the QWebEngineProfile to apply the new settings and reload the current page to reflect changes.
-
Adding levbrowser://flags/:
-
Intercepting Special URLs:
self.page.urlChanged.connect(self.handle_special_urls)
We connect the urlChanged signal to a custom handler handle_special_urls.
-
Handling the Custom URL Scheme:
def handle_special_urls(self, url):
if url.scheme() == "levbrowser" and url.host() == "flags":
self.browser.setUrl(QUrl("about:blank"))
self.show_flags_dialog()
If the URL matches levbrowser://flags/, we prevent navigation and display a dialog for flag settings.
-
Creating FlagsDialog:
We created a custom FlagsDialog class that inherits from QMessageBox to allow users to toggle the Quic and Kyber flags.
-
Enhancements and Best Practices:
-
User Experience:
Added icons to toolbar actions for better UX (assuming a theme that provides these icons).
-
Code Organization:
Encapsulated flag management within the BrowserTab class for better modularity.
-
Safety Checks:
Ensured that the application handles the last tab appropriately by prompting the user before closing.
Usage of levbrowser://flags/:
To navigate to the flags dialog, users can enter levbrowser://flags/ in the URL bar. This will trigger the handle_special_urls method, displaying the FlagsDialog where they can toggle the Quic and Kyber flags.
Final Notes:
-
Icons: Ensure that your system or environment has the appropriate icon themes. If not, you may need to provide custom icons or remove the setIcon lines.
-
Flag Implementation: The example demonstrates how to handle flags within the application. Depending on what Quic and Kyber are intended to do in your context, you might need to implement actual functionality that responds to these flags.
-
Error Handling: For a production-grade browser, more robust error handling and security considerations would be necessary.
I hope this resolves the issues with incognito mode and adds the desired levbrowser://flags/ functionality effectively!