python WEBブラウザ

import sys
import os
import json
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QWidget, QTabWidget, QAction, QMenuBar, QMenu, QListWidget, QInputDialog, QMessageBox, QFileDialog, QToolBar)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEngineDownloadItem
from PyQt5.QtCore import QUrl, QTimer, Qt

class Browser(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Advanced Browser')
        self.setGeometry(100, 100, 1200, 800)
        
        self.bookmarks = []
        self.history = []
        self.home_page = 'http://www.google.com'
        self.auto_browse_url = ''
        self.auto_browse_interval = 60
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.auto_browse)

        self.load_settings()

        self.tab_widget = QTabWidget()
        self.tab_widget.setDocumentMode(True)
        self.tab_widget.tabBarDoubleClicked.connect(self.add_new_tab)
        self.tab_widget.currentChanged.connect(self.update_url_bar)
        self.tab_widget.setTabsClosable(True)
        self.tab_widget.tabCloseRequested.connect(self.close_current_tab)

        self.setCentralWidget(self.tab_widget)
        self.status = QLineEdit()
        self.status.setReadOnly(True)
        self.statusBar().addPermanentWidget(self.status)

        navtb = QToolBar("Navigation")
        self.addToolBar(navtb)

        self.url_bar = QLineEdit()
        self.url_bar.returnPressed.connect(self.navigate_to_url)

        self.back_button = QPushButton('<')
        self.back_button.clicked.connect(lambda: self.tab_widget.currentWidget().back())

        self.forward_button = QPushButton('>')
        self.forward_button.clicked.connect(lambda: self.tab_widget.currentWidget().forward())

        self.reload_button = QPushButton('R')
        self.reload_button.clicked.connect(lambda: self.tab_widget.currentWidget().reload())

        self.add_tab_button = QPushButton('+')
        self.add_tab_button.clicked.connect(self.add_new_tab)

        self.auto_browse_button = QPushButton('Auto Browse')
        self.auto_browse_button.clicked.connect(self.toggle_auto_browse)

        navtb.addWidget(self.back_button)
        navtb.addWidget(self.forward_button)
        navtb.addWidget(self.reload_button)
        navtb.addWidget(self.url_bar)
        navtb.addWidget(self.add_tab_button)
        navtb.addWidget(self.auto_browse_button)

        self.menu_bar = QMenuBar()
        self.setMenuBar(self.menu_bar)

        self.file_menu = QMenu("&File", self)
        self.menu_bar.addMenu(self.file_menu)

        self.bookmark_menu = QMenu("&Bookmarks", self)
        self.menu_bar.addMenu(self.bookmark_menu)
        self.bookmark_menu.addAction("Add Bookmark", self.add_bookmark)
        self.bookmark_menu.addAction("Show Bookmarks", self.show_bookmarks)

        self.history_menu = QMenu("&History", self)
        self.menu_bar.addMenu(self.history_menu)
        self.history_menu.addAction("Show History", self.show_history)
        
        self.settings_menu = QMenu("&Settings", self)
        self.menu_bar.addMenu(self.settings_menu)
        self.settings_menu.addAction("Set Home Page", self.set_home_page)
        self.settings_menu.addAction("Set Auto Browse", self.set_auto_browse)

        self.add_new_tab(QUrl(self.home_page), "Home")

    def add_new_tab(self, qurl=None, label="New Tab"):
        if qurl is None:
            qurl = QUrl(self.home_page)

        browser = QWebEngineView()
        browser.setUrl(qurl)
        i = self.tab_widget.addTab(browser, label)
        self.tab_widget.setCurrentIndex(i)

        browser.urlChanged.connect(lambda qurl, browser=browser: self.update_url(qurl, browser))
        browser.loadFinished.connect(lambda _, i=i, browser=browser: self.tab_widget.setTabText(i, browser.page().title()))
        browser.page().profile().downloadRequested.connect(self.download_requested)

    def update_url(self, qurl, browser=None):
        if browser != self.tab_widget.currentWidget():
            return
        self.url_bar.setText(qurl.toString())
        self.status.setText(qurl.toString())
        self.history.append(qurl.toString())

    def navigate_to_url(self):
        qurl = QUrl(self.url_bar.text())
        self.tab_widget.currentWidget().setUrl(qurl)

    def update_url_bar(self, i):
        qurl = self.tab_widget.currentWidget().url()
        self.url_bar.setText(qurl.toString())
        self.status.setText(qurl.toString())

    def close_current_tab(self, i):
        if self.tab_widget.count() < 2:
            return
        self.tab_widget.removeTab(i)

    def add_bookmark(self):
        url = self.url_bar.text()
        if url and url not in self.bookmarks:
            self.bookmarks.append(url)
            QMessageBox.information(self, "Bookmark Added", "Bookmark has been added.")
            self.save_settings()

    def show_bookmarks(self):
        dlg = QInputDialog(self)
        dlg.setLabelText("Bookmarks:")
        dlg.setComboBoxItems(self.bookmarks)
        dlg.exec_()

    def show_history(self):
        dlg = QInputDialog(self)
        dlg.setLabelText("History:")
        dlg.setComboBoxItems(self.history)
        dlg.exec_()

    def set_home_page(self):
        url, ok = QInputDialog.getText(self, "Set Home Page", "Enter URL:")
        if ok and url:
            self.home_page = url
            self.save_settings()

    def set_auto_browse(self):
        url, ok1 = QInputDialog.getText(self, "Set Auto Browse URL", "Enter URL:")
        if ok1 and url:
            interval, ok2 = QInputDialog.getInt(self, "Set Auto Browse Interval", "Enter Interval (seconds):", min=1)
            if ok2:
                self.auto_browse_url = url
                self.auto_browse_interval = interval
                self.save_settings()

    def toggle_auto_browse(self):
        if self.timer.isActive():
            self.timer.stop()
            self.auto_browse_button.setText("Auto Browse")
        else:
            self.timer.start(self.auto_browse_interval * 1000)
            self.auto_browse_button.setText("Stop Auto Browse")

    def auto_browse(self):
        if self.auto_browse_url:
            self.tab_widget.currentWidget().setUrl(QUrl(self.auto_browse_url))

    def download_requested(self, download):
        path, _ = QFileDialog.getSaveFileName(self, "Save File", download.path())
        if path:
            download.setPath(path)
            download.accept()

    def load_settings(self):
        if os.path.exists('browser_settings.json'):
            with open('browser_settings.json', 'r') as f:
                settings = json.load(f)
                self.bookmarks = settings.get('bookmarks', [])
                self.history = settings.get('history', [])
                self.home_page = settings.get('home_page', 'http://www.google.com')
                self.auto_browse_url = settings.get('auto_browse_url', '')
                self.auto_browse_interval = settings.get('auto_browse_interval', 60)

    def save_settings(self):
        settings = {
            'bookmarks': self.bookmarks,
            'history': self.history,
            'home_page': self.home_page,
            'auto_browse_url': self.auto_browse_url,
            'auto_browse_interval': self.auto_browse_interval
        }
        with open('browser_settings.json', 'w') as f:
            json.dump(settings, f)

app = QApplication(sys.argv)
app.setApplicationName("Advanced Browser")
window = Browser()
window.show()
sys.exit(app.exec_())

投稿者: chosuke

趣味はゲームやアニメや漫画などです

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です