1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168 |
- ########################################################################
- # Searx-qt - Lightweight desktop application for SearX.
- # Copyright (C) 2020 CYBERDEViL
- #
- # This file is part of Searx-qt.
- #
- # Searx-qt is free software: you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation, either version 3 of the License, or
- # (at your option) any later version.
- #
- # Searx-qt is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # GNU General Public License for more details.
- #
- # You should have received a copy of the GNU General Public License
- # along with this program. If not, see <https://www.gnu.org/licenses/>.
- #
- ########################################################################
- from PyQt5.QtWidgets import (
- QWidget,
- QVBoxLayout,
- QLabel,
- QTableView,
- QHeaderView,
- QAbstractItemView,
- QHBoxLayout,
- QFormLayout,
- QCheckBox,
- QMenu,
- QComboBox,
- QSizePolicy,
- QScrollArea,
- QSplitter,
- QFrame,
- QWidgetAction
- )
- from PyQt5.QtCore import pyqtSignal, Qt
- from PyQt5.QtWidgets import QMessageBox
- from PyQt5.QtGui import QGuiApplication
- from searxqt.widgets.buttons import Button
- from searxqt.widgets.dialogs import UrlDialog
- from searxqt.models.instances import (
- InstanceTableModel,
- InstancesModelTypes
- )
- from searxqt.translations import _, timeToString
- class AddUserInstanceDialog(UrlDialog):
- def __init__(self, url='', parent=None):
- UrlDialog.__init__(self, url=url, acceptTxt=_("Add"), parent=parent)
- layout = self.layout()
- label = QLabel("Update data on add:")
- self._updateCheckBox = QCheckBox("", self)
- layout.insertRow(2, label, self._updateCheckBox)
- def updateOnAdd(self):
- return bool(self._updateCheckBox.isChecked())
- class InstancesView(QWidget):
- def __init__(self, filterModel, instanceSelecter, parent=None):
- """
- @type model: searxqt.models.instances.InstanceModelFilter
- @type instanceSelecter: searxqt.models.instances.InstanceSelecterModel
- @type parent: QObject
- """
- QWidget.__init__(self, parent=parent)
- layout = QVBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(0)
- self._filterModel = filterModel
- self._instanceSelecter = instanceSelecter
- self._tableModel = InstanceTableModel(filterModel, self)
- # Diffrent types can have diffrent attibutes.
- self._currentInstancesType = filterModel.parentModel().Type
- headLabel = QLabel("<h2>{0}</h2>".format(_("Instances")), self)
- layout.addWidget(headLabel)
- # Splitter
- self._splitter = QSplitter(self)
- self._splitter.setOrientation(Qt.Vertical)
- layout.addWidget(self._splitter)
- # Filter scroll area
- self._scrollArea = QScrollArea(self._splitter)
- self._scrollContentWidget = QWidget(self._scrollArea)
- scrollLayout = QVBoxLayout(self._scrollContentWidget)
- self.filterWidget = FilterWidget(
- filterModel,
- self._scrollContentWidget
- )
- self._scrollArea.setWidget(self._scrollContentWidget)
- self._scrollArea.setFrameShape(QFrame.NoFrame)
- self._scrollArea.setWidgetResizable(True)
- self._scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- self._scrollArea.setAlignment(
- Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop
- )
- scrollLayout.addWidget(self.filterWidget, 0, Qt.AlignTop)
- # Bottom widgets
- bottomWidget = QWidget(self._splitter)
- bottomLayout = QVBoxLayout(bottomWidget)
- self.statsWidget = InstancesStatsWidget(filterModel, bottomWidget)
- bottomLayout.addWidget(self.statsWidget)
- self._typeDependantButton = Button("", bottomWidget)
- bottomLayout.addWidget(self._typeDependantButton)
- self._tableView = InstanceTableView(
- filterModel,
- self._tableModel,
- self
- )
- bottomLayout.addWidget(self._tableView)
- # Connections
- self._tableView.selectionModel().selectionChanged.connect(
- self.__selectionChanged)
- self._tableModel.layoutChanged.connect(self.__tableModelLayoutChanged)
- self._instanceSelecter.instanceChanged.connect(self.__instanceChanged)
- filterModel.parentModel().typeChanged.connect(
- self.__instancesModelTypeChanged
- )
- """ InstancesType dependant methods below
- """
- def __instancesModelTypeChanged(self, type_):
- """ PersistentInstancesModel emitted changed.
- """
- previousType = self._currentInstancesType
- # Disconnect signals
- if previousType == InstancesModelTypes.Stats2:
- self._typeDependantButton.clicked.disconnect(self.__updateClicked)
- elif previousType == InstancesModelTypes.User:
- self._typeDependantButton.clicked.disconnect(self.__addClicked)
- if type_ == InstancesModelTypes.Stats2:
- self._typeDependantButton.setText(_("Update"))
- self._typeDependantButton.clicked.connect(self.__updateClicked)
- elif type_ == InstancesModelTypes.User:
- self._typeDependantButton.setText(_("Add Instance"))
- self._typeDependantButton.clicked.connect(self.__addClicked)
- self._currentInstancesType = type_
- # InstancesModelTypes.Stats2
- def __updateClicked(self, checked):
- self._filterModel.parentModel().handler().updateInstances()
- # InstancesModelTypes.User
- def __addClicked(self, checked):
- dialog = AddUserInstanceDialog()
- if dialog.exec():
- handler = self._filterModel.parentModel().handler()
- handler.addInstance(dialog.url)
- if dialog.updateOnAdd():
- handler.updateInstance(dialog.url)
- """ -----------------------------------------------------------
- """
- def selectUrl(self, url):
- self._tableView.selectionModel().selectionChanged.disconnect(
- self.__selectionChanged)
- # Backup horizontal scroll value
- horScrollVal = self._tableView.horizontalScrollBar().value()
- if url in self._filterModel:
- rowIndex = self._tableModel.getByUrl(url)
- modelIndex = self._tableModel.index(rowIndex, 0)
- self._tableView.setCurrentIndex(modelIndex)
- self._tableView.scrollTo(
- modelIndex,
- QAbstractItemView.PositionAtCenter
- )
- else:
- # No URL set so clear the selection.
- self._tableView.clearSelection()
- # Restore horizontal scroll value
- self._tableView.horizontalScrollBar().setValue(horScrollVal)
- self._tableView.selectionModel().selectionChanged.connect(
- self.__selectionChanged)
- def __instanceChanged(self, url):
- """ Select and scroll to table item with passed url.
- @param url: Instance url to select and scroll to.
- @type url: str
- """
- if url in self._filterModel:
- rowIndex = self._tableModel.getByUrl(url)
- modelIndex = self._tableModel.index(rowIndex, 0)
- self._tableView.setCurrentIndex(modelIndex)
- self._tableView.scrollTo(
- modelIndex,
- QAbstractItemView.PositionAtCenter
- )
- def __tableModelLayoutChanged(self):
- """ Re-select the current URL when the layout changed.
- """
- self.selectUrl(self._instanceSelecter.currentUrl)
- def __selectionChanged(self):
- """ Let the InstanceSelecter know that the current instance has
- changed. (Selected by the user.)
- """
- self._instanceSelecter.instanceChanged.disconnect(
- self.__instanceChanged)
- selectionModel = self._tableView.selectionModel()
- if selectionModel.hasSelection():
- rows = selectionModel.selectedRows()
- selectedIndex = rows[0].row()
- self._instanceSelecter.currentUrl = (
- self._tableModel.getByIndex(selectedIndex)
- )
- else:
- self._instanceSelecter.currentUrl = ""
- self._instanceSelecter.instanceChanged.connect(self.__instanceChanged)
- def __filterWidgetChanged(self):
- self._filterModel.updateKwargs(self.filterWidget.data())
- def saveSettings(self):
- header = self._tableView.horizontalHeader()
- data = {
- 'hiddenColumnIndexes': self._tableView.getHiddenColumnIndexes(),
- 'headerState': header.saveState()
- }
- return data
- def loadSettings(self, data):
- self._tableView.setHiddenColumnIndexes(
- data.get('hiddenColumnIndexes', [])
- )
- if 'headerState' in data:
- header = self._tableView.horizontalHeader()
- header.restoreState(data['headerState'])
- class InstanceTableView(QTableView):
- def __init__(self, filterModel, tableModel=None, parent=None):
- """
- @type filterModel: searxqt.models.instances.InstanceModelFilter
- @type tableModel: searxqt.models.instances.InstanceTableModel
- """
- QTableView.__init__(self, parent=parent)
- self._filterModel = filterModel
- if tableModel:
- self.setModel(tableModel)
- self.setAlternatingRowColors(True)
- self.setSelectionBehavior(QAbstractItemView.SelectRows)
- self.setEditTriggers(QAbstractItemView.NoEditTriggers)
- self.setSortingEnabled(True)
- self.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
- # Horizontal header
- header = self.horizontalHeader()
- header.setSectionResizeMode(QHeaderView.ResizeToContents)
- header.setSectionsMovable(True)
- def _hideColumn(self, index, state):
- state = state == 0
- self.setColumnHidden(index, state)
- def getHiddenColumnIndexes(self):
- columnIndex = 0
- indexes = []
- for columnData in self.model().getColumns():
- # Set current value
- if self.isColumnHidden(columnIndex):
- indexes.append(columnIndex)
- columnIndex += 1
- return indexes
- def setHiddenColumnIndexes(self, indexes):
- for index in indexes:
- self._hideColumn(index, True)
- """ Re-implementations
- """
- def contextMenuEvent(self, event):
- def __removeFromWhitelist(self, url):
- filter_ = self._filterModel.filter()
- filter_['url'].remove(url)
- self._filterModel.updateKwargs(
- {'url': filter_['url']},
- commit=False
- )
- selectionModel = self.selectionModel()
- if selectionModel.hasSelection():
- menu = QMenu(self)
- # Add to blacklist
- addToBlacklistAction = menu.addAction(_("Add to blacklist"))
- # Add to whitelist
- addToWhitelistAction = menu.addAction(_("Add to whitelist"))
- # Copy URL
- copyUrlAction = menu.addAction(_("Copy URL"))
- menu.addSeparator()
- # Select all
- selectAllAction = menu.addAction(_("Select All"))
- menu.addSeparator()
- # Column options
- columnsMenu = QMenu(_("Columns"), self)
- menu.addMenu(columnsMenu)
- # User instances specific
- userInstances = False
- handler = self._filterModel.parentModel().handler()
- if (
- self._filterModel.parentModel().Type
- == InstancesModelTypes.User
- ):
- userInstances = True
- menu.addSeparator()
- delUserInstanceAction = menu.addAction(_("Remove selected"))
- updateUserInstanceAction = menu.addAction(_("Update selected"))
- if handler.hasActiveJobs():
- delUserInstanceAction.setEnabled(False)
- columnIndex = 0
- for columnData in self.model().getColumns():
- action = QWidgetAction(columnsMenu)
- widget = QCheckBox(columnData.name, columnsMenu)
- widget.setTristate(False)
- action.setDefaultWidget(widget)
- # Set current value
- if not self.isColumnHidden(columnIndex):
- widget.setChecked(True)
- columnsMenu.addAction(action)
- widget.stateChanged.connect(
- lambda state, index=columnIndex:
- self._hideColumn(index, state)
- )
- columnIndex += 1
- action = menu.exec_(self.mapToGlobal(event.pos()))
- if action == addToBlacklistAction:
- # Blacklist
- filter_ = self._filterModel.filter()
- indexes = self.selectionModel().selectedRows()
- urls = []
- forAll = None
- for index in indexes:
- url = self.model().getByIndex(index.row())
- if url in filter_['url']:
- # Url is whitelisted, what to do?
- if forAll == QMessageBox.YesRole:
- __removeFromWhitelist(self, url)
- elif forAll == QMessageBox.NoRole:
- continue
- else:
- questionBox = QMessageBox(self)
- questionBox.addButton(
- _("Yes"), QMessageBox.YesRole
- )
- questionBox.addButton(
- _("No"), QMessageBox.NoRole
- )
- questionBox.addButton(
- _("Cancel"), QMessageBox.RejectRole
- )
- questionBox.setWindowTitle("Url whitelisted")
- questionBox.setText(_(
- "{0} found in the <b>whitelist</b>. Would you"
- " like to <b>remove</b> it from the"
- " <b>whitelist</b> and add it to the"
- " <b>blacklist</b>?").format(url)
- )
- checkBox = QCheckBox(
- _("Remember for all"), questionBox
- )
- questionBox.setCheckBox(checkBox)
- questionBox.exec()
- answer = questionBox.result()
- if answer == 0: # Yes
- # Remove url from whitelist and add it to
- # the blacklist
- __removeFromWhitelist(self, url)
- if checkBox.isChecked():
- forAll = QMessageBox.YesRole
- elif answer == 1 and checkBox.isChecked():
- forAll = QMessageBox.NoRole
- continue
- else:
- continue
- urls.append(url)
- self._filterModel.updateKwargs(
- {
- 'skipUrl': filter_['skipUrl'] + urls
- }
- )
- elif action == addToWhitelistAction:
- # Whitelist
- filter_ = self._filterModel.filter()
- indexes = self.selectionModel().selectedRows()
- toAdd = []
- for index in indexes:
- url = self.model().getByIndex(index.row())
- if url not in filter_['url']:
- toAdd.append(url)
- self._filterModel.updateKwargs(
- {
- 'url': filter_['url'] + toAdd
- }
- )
- elif action == copyUrlAction:
- index = selectionModel.selectedRows()[0]
- url = self.model().getByIndex(index.row())
- clipboard = QGuiApplication.clipboard()
- clipboard.setText(url)
- elif action == selectAllAction:
- self.selectAll()
- # User instances actions
- if userInstances:
- if action == delUserInstanceAction:
- indexes = self.selectionModel().selectedRows()
- # Confirmation
- instancesStr = ""
- for index in indexes:
- url = self.model().getByIndex(index.row())
- instancesStr = "{0}\n{1}".format(instancesStr, url)
- confirmDialog = QMessageBox()
- confirmDialog.setWindowTitle(
- _("Delete instances")
- )
- confirmDialog.setText(
- _("Are you sure you want to delete the following"
- " instances?\n") + instancesStr
- )
- confirmDialog.setStandardButtons(
- QMessageBox.Yes | QMessageBox.No
- )
- confirmDialog.button(QMessageBox.Yes).setText(_("Yes"))
- confirmDialog.button(QMessageBox.No).setText(_("No"))
- if confirmDialog.exec() != QMessageBox.Yes:
- return
- toRemove = []
- for index in indexes:
- toRemove.append(self.model().getByIndex(index.row()))
- handler.removeMultiInstances(toRemove)
- elif action == updateUserInstanceAction:
- indexes = self.selectionModel().selectedRows()
- handler = self._filterModel.parentModel().handler()
- for index in indexes:
- handler.updateInstance(
- self.model().getByIndex(index.row())
- )
- class UrlFilterItem(QWidget):
- deleted = pyqtSignal(str) # url
- def __init__(self, url, parent=None):
- QWidget.__init__(self, parent=parent)
- layout = QHBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- self._urlStr = url
- label = QLabel(url, self)
- delButton = Button("X", self)
- delButton.setSizePolicy(
- QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
- )
- layout.addWidget(label)
- layout.addWidget(delButton)
- delButton.clicked.connect(self.__delMe)
- def str(self): return self._urlStr
- def __delMe(self):
- self.deleted.emit(self.str())
- self.deleteLater()
- class UrlFilterWidget(QWidget):
- def __init__(self, model, key, parent=None):
- QWidget.__init__(self, parent=parent)
- self._model = model
- self._items = {}
- self._key = key
- QVBoxLayout(self)
- self.layout().setContentsMargins(0, 0, 0, 0)
- self.layout().setSpacing(0)
- self._model.changed.connect(self.__modelChanged)
- def __modelChanged(self):
- filter = self._model.filter()
- # Remove old
- for url in list(self._items.keys()):
- if url not in filter[self._key]:
- self._items[url].deleteLater()
- del self._items[url]
- # Add new
- for url in filter[self._key]:
- self.__add(url, updateModel=False)
- def __add(self, url, updateModel=True):
- if url not in self._items:
- item = UrlFilterItem(url, self)
- self._items.update({url: item})
- item.deleted.connect(self.delete)
- self.layout().addWidget(item)
- def delete(self, url):
- del self._items[url]
- self._model.updateKwargs(self.data())
- def data(self):
- return {self._key: list(self._items.keys())}
- class NetworkFilterWidget(QWidget):
- def __init__(self, model, parent=None):
- """
- @type model: InstancesModel
- """
- QWidget.__init__(self, parent=parent)
- self._model = model
- layout = QHBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(0)
- self._webBox = QCheckBox("Web", self)
- self._torBox = QCheckBox("Tor", self)
- self._i2pBox = QCheckBox("i2p", self)
- self._webBox.setSizePolicy(
- QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
- )
- self._torBox.setSizePolicy(
- QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
- )
- self._i2pBox.setSizePolicy(
- QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
- )
- layout.addWidget(self._webBox, 0, Qt.AlignLeft)
- layout.addWidget(self._torBox, 0, Qt.AlignLeft)
- layout.addWidget(self._i2pBox, 1, Qt.AlignLeft)
- self._model.changed.connect(self._modelChanged)
- self._webBox.stateChanged.connect(self.__changed)
- self._torBox.stateChanged.connect(self.__changed)
- self._i2pBox.stateChanged.connect(self.__changed)
- def __changed(self, state):
- self._model.changed.disconnect(self._modelChanged)
- self._model.updateKwargs(self.data())
- self._model.changed.connect(self._modelChanged)
- def _modelChanged(self):
- self._webBox.stateChanged.disconnect(self.__changed)
- self._torBox.stateChanged.disconnect(self.__changed)
- self._i2pBox.stateChanged.disconnect(self.__changed)
- self._webBox.setChecked(False)
- self._torBox.setChecked(False)
- self._i2pBox.setChecked(False)
- filter = self._model.filter()
- # Nothing is checked
- if not filter['ext'] and not filter['skipExt']:
- self._webBox.setChecked(True)
- self._torBox.setChecked(True)
- self._i2pBox.setChecked(True)
- # Only web checked
- elif 'onion' in filter['skipExt'] and 'i2p' in filter['skipExt']:
- self._webBox.setChecked(True)
- # Web + Tor
- elif 'i2p' in filter['skipExt'] and not filter['ext']:
- self._webBox.setChecked(True)
- self._torBox.setChecked(True)
- # Web + i2p
- elif 'onion' in filter['skipExt'] and not filter['ext']:
- self._webBox.setChecked(True)
- self._torBox.setChecked(True)
- # Tor + i2p
- elif 'onion' in filter['ext'] and 'i2p' in filter['ext']:
- self._i2pBox.setChecked(True)
- self._torBox.setChecked(True)
- # Tor
- elif 'onion' in filter['ext']:
- self._torBox.setChecked(True)
- # i2p
- elif 'i2p' in filter['ext']:
- self._i2pBox.setChecked(True)
- self._webBox.stateChanged.connect(self.__changed)
- self._torBox.stateChanged.connect(self.__changed)
- self._i2pBox.stateChanged.connect(self.__changed)
- def data(self):
- result = {
- 'ext': [], # required
- 'skipExt': [] # skip
- }
- """
- [ ] web [ ] tor [ ] i2p
- [x] web [x] tor [x] i2p
- result = {
- 'ext': [],
- 'skipExt': []
- }
- [x] web
- [ ] tor
- [ ] i2p
- result = {
- 'ext': [],
- 'skipExt': ['onion', 'i2p']
- }
- [x] web
- [x] tor
- [ ] i2p
- result = {
- 'ext': [],
- 'skipExt': ['i2p']
- }
- [x] web
- [ ] tor
- [x] i2p
- result = {
- 'ext': [],
- 'skipExt': ['onion']
- }
- [ ] web
- [x] tor
- [x] i2p
- result = {
- 'ext': ['onion', 'i2p'],
- 'skipExt': []
- }
- [ ] web
- [ ] tor
- [x] i2p
- result = {
- 'ext': ['i2p'],
- 'skipExt': []
- }
- [ ] web
- [x] tor
- [ ] i2p
- result = {
- 'ext': ['onion'],
- 'skipExt': []
- }
- """
- # Nothing or all checked
- if ((not self._webBox.isChecked()
- and not self._torBox.isChecked()
- and not self._i2pBox.isChecked())
- or (self._webBox.isChecked()
- and self._torBox.isChecked()
- and self._i2pBox.isChecked())):
- return result
- # Only web checked
- if (self._webBox.isChecked()
- and not self._torBox.isChecked()
- and not self._i2pBox.isChecked()):
- result['skipExt'].append('onion')
- result['skipExt'].append('i2p')
- return result
- # Web + Tor
- if (self._webBox.isChecked()
- and self._torBox.isChecked()
- and not self._i2pBox.isChecked()):
- result['skipExt'].append('i2p')
- return result
- # Web + i2p
- if (self._webBox.isChecked()
- and not self._torBox.isChecked()
- and self._i2pBox.isChecked()):
- result['skipExt'].append('onion')
- return result
- # Tor + i2p
- if (not self._webBox.isChecked()
- and self._torBox.isChecked()
- and self._i2pBox.isChecked()):
- result['ext'].append('onion')
- result['ext'].append('i2p')
- return result
- # Tor
- if (not self._webBox.isChecked()
- and self._torBox.isChecked()
- and not self._i2pBox.isChecked()):
- result['ext'].append('onion')
- return result
- # i2p
- if (not self._webBox.isChecked()
- and not self._torBox.isChecked()
- and self._i2pBox.isChecked()):
- result['ext'].append('i2p')
- return result
- return result
- class VersionItem(QWidget):
- deleted = pyqtSignal(str) # version string
- def __init__(self, versionStr, parent=None):
- QWidget.__init__(self, parent=parent)
- layout = QHBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(0)
- self._versionStr = versionStr
- label = QLabel(versionStr, self)
- delButton = Button("X", self)
- delButton.setSizePolicy(QSizePolicy(
- QSizePolicy.Maximum, QSizePolicy.Fixed))
- layout.addWidget(label)
- layout.addWidget(delButton)
- delButton.clicked.connect(self.__delMe)
- def str(self): return self._versionStr
- def __delMe(self):
- self.deleted.emit(self.str())
- self.deleteLater()
- class VersionFilter(QWidget):
- def __init__(self, model, parent=None):
- """
- @type model: InstanceModelFilter
- """
- QWidget.__init__(self, parent=parent)
- self._model = model
- self._items = {}
- layout = QVBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(0)
- # Add new
- horizontalLayout = QHBoxLayout()
- layout.addLayout(horizontalLayout)
- self.comboBox = QComboBox(self)
- self.addButton = Button(_("Add"), self)
- self.addButton.setSizePolicy(
- QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
- )
- horizontalLayout.addWidget(self.comboBox)
- horizontalLayout.addWidget(self.addButton)
- self.addButton.clicked.connect(self.__addClicked)
- self._model.changed.connect(self.__modelChanged)
- def __addClicked(self):
- """ Add button clicked -- will add the current selected version
- of the combobox to the version filter list.
- This wil trigger the following:
- 1) self.__add
- Adds the version string as a key to self._items
- 2) self._model.updateKwargs
- Update the model
- 3) self.__modelChanged
- Model has been changed so self.__modelChanged is called. This
- will re-generate the view.
- """
- self.__add(self.comboBox.currentText())
- self._model.updateKwargs(self.data()) # update the model.
- def __fromItemDelete(self, versionStr):
- """ Called when a VersionItem emits deleted (It's 'X' aka delete
- button has been pressed).
- This will trigger the following:
- 1) self.delete
- Deletes the version (key) from self._items and removes from
- the widget from the view.
- 2) self._model.updateKwargs
- Update the model.
- 3) Model has been changed so self.__modelChanged is called. This
- will re-generate the view.
- """
- self.delete(versionStr)
- self._model.updateKwargs(self.data())
- def _compileVersions(self):
- """ Fill the combobox with available version strings
- """
- allVersions = []
- self.comboBox.clear()
- for url, instance in self._model.parentModel().items():
- if instance.version and instance.version not in allVersions:
- allVersions.append(instance.version)
- if instance.version not in self._items.keys():
- self.comboBox.addItem(instance.version)
- def __modelChanged(self):
- self.clear() # clear the versions list
- filter = self._model.filter()
- for versionStr in filter['version']:
- # Add the version to the list
- self.add(versionStr)
- self._compileVersions() # re-generate the combobox items
- def data(self):
- result = {
- 'version': [], # required
- 'skipVersion': [] # skip (TODO unused)
- }
- for versionStr in self._items.keys():
- result['version'].append(versionStr)
- return result
- def clear(self):
- """ Clears added version items (on the view side only)
- """
- keys = list(self._items.keys())
- for versionStr in keys:
- self.delete(versionStr)
- def __add(self, versionStr):
- self._items.update({versionStr: None})
- def add(self, versionStr):
- item = VersionItem(versionStr, self)
- self._items.update({versionStr: item})
- item.deleted.connect(self.__fromItemDelete)
- self.layout().addWidget(item)
- def delete(self, versionStr):
- if self._items[versionStr]:
- # delete the widget if exists.
- self._items[versionStr].deleteLater()
- del self._items[versionStr]
- class CheckboxFilter(QCheckBox):
- def __init__(self, model, key, parent=None):
- """
- @type model: InstancesModel
- @param key: key to use (from model.filter())
- @type key: str
- """
- QCheckBox.__init__(self, parent=parent)
- self._model = model
- self._key = key
- self._model.changed.connect(self.__modelChanged)
- self.stateChanged.connect(self.__stateChanged)
- def __modelChanged(self):
- """ Model changed, update the checkbox.
- """
- filter_ = self._model.filter()
- state = filter_.get(self._key, True)
- self.stateChanged.disconnect(self.__stateChanged)
- self.setChecked(state)
- self.stateChanged.connect(self.__stateChanged)
- def __stateChanged(self):
- """ Checkbox state changed, update the model.
- """
- state = self.isChecked()
- self._model.updateKwargs({self._key: state})
- class FilterWidget(QWidget):
- def __init__(self, model, parent=None):
- """
- @type model: searxqt.models.instances.InstanceModelFilter
- """
- QWidget.__init__(self, parent=parent)
- self._model = model
- layout = QFormLayout(self)
- layout.setLabelAlignment(
- Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop
- )
- layout.addRow(QLabel(_("<h3>Filter</h3>"), self))
- self._networkFilter = NetworkFilterWidget(model, self)
- layout.addRow(QLabel(_("Network") + ":"), self._networkFilter)
- self._asnPrivacyFilter = None
- self._ipv6Filter = None
- self._versionFilter = VersionFilter(model, self)
- layout.addRow(QLabel(_("Version") + ":"), self._versionFilter)
- self._urlFilterOut = UrlFilterWidget(model, 'skipUrl', self)
- layout.addRow(QLabel(_("Blacklist") + ":"), self._urlFilterOut)
- self._urlFilter = UrlFilterWidget(model, 'url', self)
- layout.addRow(QLabel(_("Whitelist") + ":"), self._urlFilter)
- model.parentModel().typeChanged.connect(self.__modelTypeChanged)
- def __modelTypeChanged(self, type_):
- layout = self.layout()
- if type_ == InstancesModelTypes.Stats2:
- if not self._asnPrivacyFilter:
- self._asnPrivacyFilter = CheckboxFilter(
- self._model,
- 'asnPrivacy',
- self
- )
- label = QLabel(_("Require ASN privacy") + ":")
- label.setWordWrap(True)
- label.setToolTip(_(
- "Filter out instances that run their server at a known\n"
- "malicious network like Google, CloudFlare, Akamai etc..\n"
- "\n"
- "This does not give any guarantee, it only filters known\n"
- "privacy violators!"
- ))
- layout.insertRow(
- 2,
- label,
- self._asnPrivacyFilter
- )
- if not self._ipv6Filter:
- self._ipv6Filter = CheckboxFilter(self._model, 'ipv6', self)
- label = QLabel(_("Require IPv6") + ":")
- label.setWordWrap(True)
- label.setToolTip(_(
- "Only instances with at least one ipv6-address remain"
- " if checked."
- ))
- layout.insertRow(3, label, self._ipv6Filter)
- else:
- if self._asnPrivacyFilter:
- self._asnPrivacyFilter.deleteLater()
- layout.removeRow(2)
- self._asnPrivacyFilter = None
- if self._ipv6Filter:
- self._ipv6Filter.deleteLater()
- layout.removeRow(2)
- self._ipv6Filter = None
- class InstancesStatsWidget(QWidget):
- def __init__(self, filterModel, parent=None):
- """
- @param filterModel:
- @type filterModel: searxqt.models.instances.InstanceModelFilter
- """
- QWidget.__init__(self, parent=parent)
- self._filterModel = filterModel
- self._currentInstancesType = filterModel.parentModel().Type
- self._countLabel = None
- self._filterCountLabel = None
- self._lastUpdateLabel = None
- layout = QFormLayout(self)
- layout.setLabelAlignment(
- Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop
- )
- self._toggleButton = Button("", self)
- layout.addRow(QLabel(_("<h3>Stats</h3>"), self), self._toggleButton)
- self.__show()
- self._toggleButton.clicked.connect(self.__toggle)
- self._filterModel.parentModel().typeChanged.connect(
- self.__instancesModelTypeChanged
- )
- def collapsed(self):
- return bool(self._countLabel is None)
- def __toggle(self):
- if self.collapsed():
- self.__show()
- else:
- self.__hide()
- def __show(self):
- self._toggleButton.setText(_("Hide"))
- layout = self.layout()
- self._countLabel = QLabel("0", self)
- layout.addRow(QLabel(_("Total count") + ":"), self._countLabel)
- self._filterCountLabel = QLabel("0", self)
- layout.addRow(
- QLabel(_("After filter count") + ":"),
- self._filterCountLabel
- )
- self._lastUpdateLabel = QLabel("0", self)
- self._lastUpdateLabel.setWordWrap(True)
- layout.addRow(QLabel(_("Last update") + ":"), self._lastUpdateLabel)
- self.__modelChanged() # Update count and after filter count
- self.__instancesModelTypeChanged(self._filterModel.parentModel().Type)
- self._filterModel.changed.connect(self.__modelChanged)
- def __hide(self):
- self._filterModel.changed.disconnect(self.__modelChanged)
- self.__instancesModelTypeChanged(InstancesModelTypes.NotDefined)
- self._toggleButton.setText(_("Show"))
- layout = self.layout()
- while layout.rowCount() > 1:
- layout.removeRow(1)
- self._countLabel = None
- self._filterCountLabel = None
- self._lastUpdateLabel = None
- """ InstancesType dependant methods below
- """
- def __instancesModelTypeChanged(self, type_):
- """ PersistentInstancesModel emitted changed.
- """
- if self.collapsed():
- return
- previousType = self._currentInstancesType
- self._currentInstancesType = type_
- # Disconnect signals
- if previousType == InstancesModelTypes.Stats2:
- self._filterModel.changed.disconnect(self.__updateLastUpdated)
- elif previousType == InstancesModelTypes.User:
- pass
- if type_ == InstancesModelTypes.Stats2:
- self._filterModel.changed.connect(self.__updateLastUpdated)
- self.__updateLastUpdated()
- else:
- self._lastUpdateLabel.setText("-")
- # InstancesModelTypes.Stats2
- def __updateLastUpdated(self):
- self._lastUpdateLabel.setText(
- timeToString(
- self._filterModel.parentModel().handler().lastUpdated()
- )
- )
- """ -------------------------------------------
- """
- def __modelChanged(self):
- self._countLabel.setText(str(len(self._filterModel.parentModel())))
- self._filterCountLabel.setText(str(len(self._filterModel)))
|