0% found this document useful (0 votes)
11 views4 pages

Message

This document outlines the implementation of a web browser using PyQt6, featuring a custom web engine page, a settings dialog for user preferences, and a main browser window with tabbed browsing functionality. It includes constants for file paths, a list of search engines, and methods for loading settings, navigating URLs, and managing tabs. The application is structured to handle downloads, security settings, and user interface elements effectively.

Uploaded by

minecraft007h1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

Message

This document outlines the implementation of a web browser using PyQt6, featuring a custom web engine page, a settings dialog for user preferences, and a main browser window with tabbed browsing functionality. It includes constants for file paths, a list of search engines, and methods for loading settings, navigating URLs, and managing tabs. The application is structured to handle downloads, security settings, and user interface elements effectively.

Uploaded by

minecraft007h1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

import sys

import os
import json
from PyQt6.QtCore import QUrl, QSize, Qt, pyqtSignal, QDateTime
from PyQt6.QtGui import QIcon, QAction
from PyQt6.QtWidgets import (QApplication, QMainWindow, QTabWidget, QVBoxLayout,
QWidget, QLineEdit, QPushButton, QHBoxLayout,
QDialog, QListWidget, QMessageBox, QMenu,
QFileIconProvider, QListWidgetItem, QComboBox,
QCheckBox, QGroupBox, QLabel)
from PyQt6.QtWebEngineCore import (QWebEngineProfile, QWebEnginePage,
QWebEngineDownloadRequest)
from PyQt6.QtWebEngineWidgets import QWebEngineView

# Constantes de arquivos
HISTORY_FILE = "history.json"
DOWNLOADS_FILE = "downloads.json"
SETTINGS_FILE = "settings.json"
BROWSER_DATA_DIR = "browser_data"

# Lista de mecanismos de busca


SEARCH_ENGINES = [
("Google", "google.png", "https://www.google.com",
"https://www.google.com/search?q="),
("Bing", "bing.png", "https://bing.com", "https://www.bing.com/search?q="),
("youCare", "youcare.png", "https://youcare.world/",
"https://youcare.world/all?q="),
("DuckDuckGo", "duckduckgo.png", "https://duckduckgo.com",
"https://duckduckgo.com/?t=h_&q="),
("Brave Search", "brave.png", "https://search.brave.com",
"https://search.brave.com/search?q="),
("Ecosia", "ecosia.png", "https://ecosia.org", "https://www.ecosia.org/search?
method=index&q=")
]

class CustomWebEnginePage(QWebEnginePage):
newTabRequested = pyqtSignal(QUrl)
downloadRequested = pyqtSignal(QWebEngineDownloadRequest)

def __init__(self, profile, parent=None):


super().__init__(profile, parent)
self.profile().downloadRequested.connect(self.on_download_requested)
self.last_new_tab_time = QDateTime.currentDateTime().toMSecsSinceEpoch()
self.new_tab_cooldown = 500 # 500 ms cooldown

def on_download_requested(self, download):


self.downloadRequested.emit(download)

def javaScriptConsoleMessage(self, level, message, line, source):


print(f"JS: {message}")

def createWindow(self, window_type):


current_time = QDateTime.currentDateTime().toMSecsSinceEpoch()
if current_time - self.last_new_tab_time > self.new_tab_cooldown:
self.last_new_tab_time = current_time
if window_type == QWebEnginePage.WebWindowType.WebBrowserTab:
new_page = CustomWebEnginePage(self.profile(), self)
new_page.urlChanged.connect(lambda url:
self.newTabRequested.emit(url))
return new_page
return self # Retorna a página atual se o cooldown não foi atingido

class SettingsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Definições")
self.setWindowIcon(QIcon("resources/settings.png"))
self.resize(500, 400)

layout = QVBoxLayout()

# Segurança
security_group = QGroupBox("Segurança 🔒")
security_layout = QVBoxLayout()

self.force_https = QCheckBox("Forçar ligação HTTPS")


security_layout.addWidget(self.force_https)

security_group.setLayout(security_layout)
layout.addWidget(security_group)

# Mecanismo de Busca
search_group = QGroupBox("Mecanismo de Busca 🔍")
search_layout = QVBoxLayout()

self.search_engine = QComboBox()

for name, icon, homepage, search_url in SEARCH_ENGINES:


icon_path = f"resources/searchengines/{icon}"
icon_item = QIcon(icon_path) if os.path.exists(icon_path) else None
self.search_engine.addItem(icon_item, name)

search_layout.addWidget(self.search_engine)

search_group.setLayout(search_layout)
layout.addWidget(search_group)

# Botão Salvar
self.save_button = QPushButton("Salvar Configurações")
layout.addWidget(self.save_button)

self.setLayout(layout)

class Browser(QMainWindow):
def __init__(self):
super().__init__()

self.setWindowTitle("NexusBrowser")
self.resize(1200, 800)

# Estilos e Layouts
self.setStyleSheet("""
QMainWindow { background-color: #2e2e2e; }
/* Adicione outros estilos conforme necessário */
""")

# Inicialização das variáveis


self.history = []
self.downloads = []

# Carregar configurações e inicializar UI


storage_path = os.path.abspath(BROWSER_DATA_DIR)

if not os.path.exists(storage_path):
os.makedirs(storage_path)

# Configuração do perfil do navegador


self.profile = QWebEngineProfile("NexusBrowser")

# Criação da interface gráfica do usuário (UI)


self.init_ui()

# Carregar configurações se disponíveis


self.load_settings()

def load_settings(self):
try:
with open(SETTINGS_FILE) as f:
settings = json.load(f)
# Carregue configurações... (implementar a lógica para carregar as
configurações aqui)
pass
except (FileNotFoundError, json.JSONDecodeError):
pass # Usar configurações padrão

def init_ui(self):
# Criação das abas do navegador
self.browser_tabs = QTabWidget()
self.browser_tabs.setTabsClosable(True)
self.browser_tabs.setMovable(True)

# Conectar sinais às funções correspondentes


self.browser_tabs.tabCloseRequested.connect(self.close_tab)
self.browser_tabs.currentChanged.connect(self.update_url_bar)

# Barra de URL e botões de navegação


self.url_bar = QLineEdit()
self.url_bar.setPlaceholderText("Insira URL ou pesquise...")
self.url_bar.returnPressed.connect(self.navigate_to_url)

toolbar_layout = QHBoxLayout()
toolbar_layout.addWidget(self.url_bar)

main_layout = QVBoxLayout()
main_layout.addLayout(toolbar_layout)
main_layout.addWidget(self.browser_tabs)

container = QWidget()
container.setLayout(main_layout)

# Defina o layout principal no contêiner


self.setCentralWidget(container)

def update_url_bar(self):
current_index = self.browser_tabs.currentIndex()
if current_index >= 0:
current_tab_widget = self.browser_tabs.widget(current_index)
url_text = current_tab_widget.url().toString()
self.url_bar.setText(url_text)

def navigate_to_url(self):
url_text = self.url_bar.text()
if not url_text.startswith(('http://', 'https://')):
url_text = 'http://' + url_text

current_tab_index = self.browser_tabs.currentIndex()

if current_tab_index >= 0:
current_tab_widget = self.browser_tabs.widget(current_tab_index)
current_tab_widget.setUrl(QUrl(url_text))

def close_tab(self, index):


if self.browser_tabs.count() > 1:
self.browser_tabs.removeTab(index)

if __name__ == "__main__":
app = QApplication(sys.argv)
browser = Browser()
browser.show()
sys.exit(app.exec())

You might also like