コード例 #1
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self._sessionsMetaDataList = []  # QList<SessionMetaData>

        self._firstBackupSession = DataPaths.currentProfilePath() + '/session.dat.old'
        self._secondBackupSession = DataPaths.currentProfilePath() + '/session.dat.old1'
        self._lastActiveSessionPath = ''

        sessionFileWatcher = QFileSystemWatcher([DataPaths.path(DataPaths.Sessions)], self)
        sessionFileWatcher.directoryChanged.connect(self._sessionsDirectoryChanged)
        sessionFileWatcher.directoryChanged.connect(self.sessionsMetaDataChanged)

        self.loadSettings()
コード例 #2
0
    def saveSettings(self):
        sessionDir = QDir(DataPaths.path(DataPaths.Sessions))

        settings = Settings()
        settings.beginGroup('Web-Browser-Settings')
        settings.setValue('lastActiveSessionPath', sessionDir.relativeFilePath(self._lastActiveSessionPath))
        settings.endGroup()
コード例 #3
0
    def loadSettings(self):
        sessionDir = QDir(DataPaths.path(DataPaths.Sessions))

        settings = Settings()
        settings.beginGroup('Web-Browser-Settings')
        self._lastActiveSessionPath = settings.value('lastActiveSessionPath', self.defaultSessionPath())
        settings.endGroup()

        if QDir.isRelativePath(self._lastActiveSessionPath):
            self._lastActiveSessionPath = sessionDir.absoluteFilePath(self._lastActiveSessionPath)

        # Fallback to default session
        if not RestoreManager.validateFile(self._lastActiveSessionPath):
            self._lastActiveSessionPath = self.defaultSessionPath()
コード例 #4
0
    def __init__(self, parent, preferences):
        '''
        @param: parent QWidget
        @param: preferences Preferences
        '''
        super().__init__()
        self._ui = uic.loadUi('mc/preferences/ThemeManager.ui', self)
        self._preferences = preferences  # Preferences

        self._activeTheme = ''
        self._themeHash = {}  # QHash<QString, Theme>

        self._ui.listWidget.setLayoutDirection(Qt.LeftToRight)
        self._ui.license.hide()

        settings = Settings()
        settings.beginGroup('Themes')
        self._activeTheme = settings.value('activeTheme',
                                           const.DEFAULT_THEME_NAME)
        settings.endGroup()

        themePaths = DataPaths.allPaths(DataPaths.Themes)

        for path in themePaths:
            dir_ = QDir(path)
            list_ = dir_.entryList(QDir.AllDirs | QDir.NoDotAndDotDot)
            for name in list_:
                # Theme
                themeInfo = self._parseTheme(
                    dir_.absoluteFilePath(name) + '/', name)
                if not themeInfo.isValid:
                    continue

                item = QListWidgetItem(self._ui.listWidget)
                item.setText(themeInfo.name)
                item.setIcon(themeInfo.icon)
                item.setData(Qt.UserRole, name)

                if self._activeTheme == name:
                    self._ui.listWidget.setCurrentItem(item)

                self._ui.listWidget.addItem(item)

        self._ui.listWidget.currentItemChanged.connect(self._currentChanged)
        self._ui.license.clicked.connect(self._showLicense)

        self._currentChanged()
コード例 #5
0
ファイル: AppTools.py プロジェクト: zy-sunshine/falkon-pyqt5
    def iconFromFileName(self, fileName):
        '''
        @param: fileName QString
        @return: QIcon
        '''
        tempInfo = QFileInfo(fileName)
        suffix = tempInfo.suffix()
        if suffix in self._s_iconCache:
            return self._s_iconCache[suffix]

        iconProvider = QFileIconProvider()
        tempFile = DataPaths.path(DataPaths.Temp) + '/XXXXXX.' + suffix
        tempFile.open()
        tempInfo.setFile(tempFile.fileName())

        icon = QIcon(iconProvider.icon(tempInfo))
        self._s_iconCache[suffix] = icon
コード例 #6
0
    def _optimizeDb(self):
        gVar.app.setOverrideCursor(Qt.WaitCursor)
        profilePath = DataPaths.currentProfilePath()
        sizeBefore = gVar.appTools.fileSizeToString(
            QFileInfo(profilePath + 'browserdata.db').size())

        IconProvider.instance().clearOldIconsInDatabase()

        sizeAfter = gVar.appTools.fileSizeToString(
            QFileInfo(profilePath + 'browserdata.db').size())

        gVar.app.restoreOverrideCursor()

        QMessageBox.information(
            self,
            _('Database Optimized'),
            _('Database successfully optimized.<br/><br/><b>Database Size Before: </b>%s<br/><b>Database Size After: </b>%s'
              ) %  # noqa E501
            (sizeBefore, sizeAfter))
コード例 #7
0
    def _saveSession(self):
        '''
        @note: not used yet
        '''
        sessionName, ok = QInputDialog.getText(gVar.app.getWindow(), _('Save Session'),
            _('Please enter a name to save session:'), QLineEdit.Normal,
            _('Saved Session (%s)') % QDateTime.currentDateTime().toString('yyyy MM dd HH-mm-ss'))

        if not ok:
            return

        filePath = '%s/%s.dat' % (DataPaths.path(DataPaths.Sessions), sessionName)
        if QFile.exists(filePath):
            QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                _('The session file "%s" exists. Please enter another name.') % sessionName)
            self._saveSession()
            return

        self.writeCurrentSession(filePath)
コード例 #8
0
ファイル: SpeedDial.py プロジェクト: zy-sunshine/falkon-pyqt5
    def loadSettings(self):
        self._loaded = True

        settings = Settings()
        settings.beginGroup('SpeedDial')
        allPages = settings.value('pages', '')
        self.setBackgroundImage(settings.value('background', ''))
        self._backgroundImageSize = settings.value('backsize', 'auto')
        self._maxPagesInRow = settings.value('pagesrow', 4)
        self._sizeOfSpeedDials = settings.value('sdsize', 231)
        self._sdcentered = settings.value('sdcenter', False)
        settings.endGroup()

        self.changed(allPages)

        self._thumbnailsDir = DataPaths.currentProfilePath() + '/thumbnails/'

        # If needed, create thumbnails directory
        if not pathexists(self._thumbnailsDir):
            makedirs(self._thumbnailsDir)
コード例 #9
0
    def showNotification(self, icon, heading, text):
        '''
        @param: icon QPixmap
        @param: heading QString
        @param: text QString
        '''
        if not self._enabled:
            return

        if self._notifType == self.PopupWidget:
            if not self._desktopNotif:
                self._desktopNotif = DesktopNotification()

                def func():
                    self._desktopNotif = None
                self._desktopNotif.closedSignal.connect(func)
            self._desktopNotif.setPixmap(icon)
            self._desktopNotif.setHeading(heading)
            self._desktopNotif.setText(text)
            self._desktopNotif.setTimeout(self._timeout)
            self._desktopNotif.move(self._position)
            self._desktopNotif.show()
        elif self._notifType == self.DesktopNative:
            if const.OS_UNIX and not const.DISABLE_DBUS:
                tmp = QFile(DataPaths.path(DataPaths.Temp) + '/app_notif.png')
                tmp.open(QFile.WriteOnly)
                icon.save(tmp.fileName())

                from PyQt5.Qt import QDBusInterface, QDBusConnection
                dbus = QDBusInterface('org.freedesktop.Notifications', '/org/freedesktop/Notifications',
                        'org.freedesktop.Notifications', QDBusConnection.sessionBus())
                args = []
                args.append('app')
                args.append(self._uint)
                args.append(tmp.fileName())
                args.append(heading)
                args.append(text)
                args.append([])
                args.append({})
                args.append(self._timeout)
                dbus.callWithCallback('Notify', args, self._updateLastId, self._error)
コード例 #10
0
ファイル: Bookmarks.py プロジェクト: zy-sunshine/falkon-pyqt5
    def _saveBookmarks(self):
        bookmarksMap = {}
        self._WRITE_FOLDER('bookmark_bar', self._folderToolbar, bookmarksMap)
        self._WRITE_FOLDER('bookmark_menu', self._folderMenu, bookmarksMap)
        self._WRITE_FOLDER('other', self._folderUnsorted, bookmarksMap)

        map_ = {}
        map_['version'] = self._s_bookmarksVersion
        map_['roots'] = bookmarksMap

        data = jdumps(map_)

        if not data:
            print(
                'Warning: Bookmarks::saveBookmarks() Error serializing bookmarks!'
            )
            return

        fpath = DataPaths.currentProfilePath() + '/bookmarks.json'
        with open(fpath, 'wt') as fp:
            fp.write(data)
コード例 #11
0
    def _renameSession(self, sessionFilePath='', flags=0):
        if not sessionFilePath:
            action = self.sender()
            if not isinstance(action, QAction):
                return

            sessionFilePath = action.data()

        suggestedName = QFileInfo(sessionFilePath).completeBaseName() + \
            (flags & self.CloneSession) and _('_cloned') or _('_renamed')

        newName, ok = QInputDialog.getText(gVar.app.activeWindow(),
            (flags & self.CloneSession) and _('Clone Session') or _('Rename Session'),
            _('Please enter a new name:'), QLineEdit.Normal, suggestedName)

        if not ok:
            return

        newSessionPath = '%s/%s.dat' % (DataPaths.path(DataPaths.Sessions), newName)
        if QFile.exists(newSessionPath):
            QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                    _('The session file "%s" exists. Please enter another name.') % newName)
            self._renameSession(sessionFilePath, flags)
            return

        if flags & self.CloneSession:
            if not QFile.copy(sessionFilePath, newSessionPath):
                QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                    _('An error occurred when cloning session file.'))
                return
        else:
            if not QFile.rename(sessionFilePath, newSessionPath):
                QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                    _('An error occurred when renaming session file.'))
                return
            if self._isActive(sessionFilePath):
                self._lastActiveSessionPath = newSessionPath
                self._sessionsMetaDataList.clear()
コード例 #12
0
ファイル: Bookmarks.py プロジェクト: zy-sunshine/falkon-pyqt5
    def _loadBookmarks(self):
        bookmarksFile = DataPaths.currentProfilePath() + '/bookmarks.json'
        backupFile = bookmarksFile + '.old'
        error = False

        try:
            res = jloads(gVar.appTools.readAllFileContents(bookmarksFile))
            if type(res) != dict:
                error = True
        except ValueError:
            error = True

        if error:
            if pathexists(bookmarksFile):
                print(
                    'Warning: Bookmarks::init() Error parsing bookmarks! Using default bookmarks!'
                )
                print(
                    'Warning: Bookmarks::init() Your bookmarks have been backed up in %s'
                    % backupFile)

                # Backup the user bookmarks
                if pathexists(backupFile):
                    remove(backupFile)
                copy(bookmarksFile, backupFile)

            # Load default bookmarks
            content = gVar.appTools.readAllFileContents(':data/bookmarks.json')
            data = jloads(content)
            assert (type(data) == dict)

            self._loadBookmarksFromMap(data['roots'])

            # Don't forget to save the bookmarks
            self._autoSaver.changeOccurred()
        else:
            self._loadBookmarksFromMap(res['roots'])
コード例 #13
0
    def _fillSessionsMetaDataListIfNeeded(self):
        '''
        @brief: load all session meta info from sessions directory include default session file
        '''
        if self._sessionsMetaDataList:
            return

        dir_ = QDir(DataPaths.path(DataPaths.Sessions))

        sessionFiles = []
        sessionFiles.append(QFileInfo(self.defaultSessionPath()))
        sessionFiles.extend(dir_.entryInfoList(['*.*'], QDir.Files, QDir.Time))

        fileNames = []

        defaultFileInfo = QFileInfo(self.defaultSessionPath())
        for fileInfo in sessionFiles:
            if not RestoreManager.validateFile(fileInfo.absoluteFilePath()):
                continue

            metaData = self.SessionMetaData()
            metaData.name = baseName = fileInfo.completeBaseName()

            if fileInfo == defaultFileInfo:
                metaData.name = _('Default session')
                metaData.isDefault = True
            elif baseName in fileNames:
                metaData.name = fileInfo.fileName()

            if self._isActive(fileInfo):
                metaData.isActive = True

            fileNames.append(metaData.name)
            metaData.filePath = fileInfo.canonicalFilePath()

            self._sessionsMetaDataList.append(metaData)
コード例 #14
0
    def _newSession(self):
        sessionName, ok = QInputDialog.getText(gVar.app.getWindow(), _('New Session'),
            _('Please enter a name to create new session:'), QLineEdit.Normal,
            _('New Session (%s)') % QDateTime.currentDateTime().toString('yyyy MM dd HH-mm-ss'))

        if not ok:
            return

        filePath = '%s/%s.dat' % (DataPaths.path(DataPaths.Sessions), sessionName)
        if QFile.exists(filePath):
            QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                _('The session file "%1" exists. Please enter another name.') % sessionName)
            self._newSession()
            return

        self.writeCurrentSession(self._lastActiveSessionPath)

        window = gVar.app.createWindow(const.BW_NewWindow)
        for win in gVar.app.windows():
            if win != window:
                win.close()

        self._lastActiveSessionPath = filePath
        self.autoSaveLastSession()
コード例 #15
0
    def download(self, downloadItem):  # noqa C901
        '''
        @param: downloadItem QWebEngineDownloadItem
        '''
        downloadTimer = QTime()
        downloadTimer.start()

        self.closeDownloadTab(downloadItem)

        downloadPath = ''
        openFile = False

        fileName = basename(downloadItem.path())

        forceAsk = downloadItem.savePageFormat() != QWebEngineDownloadItem.UnknownSaveFormat \
            or downloadItem.type() == QWebEngineDownloadItem.UserRequested

        if self._useExternalManager:
            self.startExternalManager(downloadItem.url())
        elif forceAsk or not self._downloadPath:
            (Unknown, Open, Save, ExternalManager, SavePage) = range(5)
            result = Unknown

            if downloadItem.savePageFormat(
            ) != QWebEngineDownloadItem.UnknownSaveFormat:
                # Save Page Requested
                result = SavePage
            elif downloadItem.type() == QWebEngineDownloadItem.UserRequested:
                # Save x as... requested
                result = Save
            else:
                # Ask what to do
                optionsDialog = DownloadOptionsDialog(fileName, downloadItem,
                                                      gVar.app.activeWindow())
                optionsDialog.showExternalManagerOption(
                    self._useExternalManager)
                optionsDialog.setLastDownloadOption(self._lastDownloadOption)
                result = optionsDialog.exec_()

            if result == Open:
                openFile = True
                downloadPath = gVar.appTools.ensureUniqueFilename(
                    pathjoin(DataPaths.path(DataPaths.Temp), fileName))
                self._lastDownloadOption = self.OpenFile
            elif result == Save:
                downloadPath, selectedFitler = QFileDialog.getSaveFileName(
                    gVar.app.activeWindow(), _('Save file as...'),
                    pathjoin(self._lastDownloadPath, fileName))

                if downloadPath:
                    self._lastDownloadPath = QFileInfo(
                        downloadPath).absolutePath()
                    Settings().setValue('DownloadManager/lastDownloadPath',
                                        self._lastDownloadPath)
                    self._lastDownloadOption = self.SaveFile

            elif result == SavePage:
                mhtml = _('MIME HTML Archive (*.mhtml)')
                htmlSingle = _('HTML Page, single (*.html)')
                htmlComplete = _('HTML Page, complete (*.html)')
                filter_ = '%s;;%s;;%s' % (mhtml, htmlSingle, htmlComplete)

                selectedFilter = ''
                downloadPath, selectedFilter = QFileDialog.getSaveFileName(
                    gVar.app.activeWindow(), _('Save page as...'),
                    pathjoin(self._lastDownloadPath, fileName), filter_,
                    selectedFilter)

                if downloadPath:
                    self._lastDownloadPath = QFileInfo(
                        downloadPath).absolutePath()
                    Settings().setValue('DownloadManager/lastDownloadPath',
                                        self._lastDownloadPath)
                    self._lastDownloadOption = self.SaveFile

                    format_ = QWebEngineDownloadItem.UnknownSaveFormat

                    if selectedFilter == mhtml:
                        format_ = QWebEngineDownloadItem.MimeHtmlSaveFormat
                    elif selectedFilter == htmlSingle:
                        format_ = QWebEngineDownloadItem.SingleHtmlSaveFormat
                    elif selectedFilter == htmlComplete:
                        format_ = QWebEngineDownloadItem.CompleteHtmlSaveFormat

                    if format_ == QWebEngineDownloadItem.UnknownSaveFormat:
                        downloadItem.setSavePageFormat(format_)

            elif result == ExternalManager:
                self.startExternalManager(downloadItem.url())
                downloadItem.cancel()
            else:
                downloadItem.cancel()
        else:
            downloadPath = gVar.appTools.ensureUniqueFilename(
                pathjoin(self._downloadPath, fileName))

        if not downloadPath:
            downloadItem.cancel()
            return

        # Set download path ad accept
        downloadItem.setPath(downloadPath)
        downloadItem.accept()

        # Create download item
        listItem = QListWidgetItem(self._ui.list)
        downItem = DownloadItem(listItem, downloadItem,
                                QFileInfo(downloadPath).absolutePath(),
                                basename(downloadPath), openFile, self)
        downItem.setDownTimer(downloadTimer)
        downItem.startDownloading()
        downItem.deleteItem.connect(self._deleteItem)
        downItem.downloadFinished.connect(self._downloadFinished)
        self._ui.list.setItemWidget(listItem, downItem)
        listItem.setSizeHint(downItem.sizeHint())
        downItem.show()

        self._activeDownloadsCount += 1
        self.downloadsCountChanged.emit()
コード例 #16
0
 def defaultSessionPath(cls):
     '''
     @return: QString
     '''
     return DataPaths.currentProfilePath() + '/session.dat'
コード例 #17
0
    def clearLocalStorage(cls):
        profile = DataPaths.currentProfilePath()

        gVar.appTools.removeRecursively(profile + '/Local Storage')
コード例 #18
0
    def clearWebDatabases(cls):
        profile = DataPaths.currentProfilePath()

        gVar.appTools.removeRecursively(profile + '/IndexedDB')
        gVar.appTools.removeRecursively(profile + '/databases')
コード例 #19
0
    def clearCache(cls):
        profile = DataPaths.currentProfilePath()

        gVar.appTools.removeRecursively(profile + '/GPUCache')

        gVar.app.webProfile().clearHttpCache()