12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163 |
- ########################################################################
- # Searx-Qt - Lightweight desktop application for Searx.
- # Copyright (C) 2020-2022 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,
- QMessageBox,
- QMenu,
- QComboBox,
- QSizePolicy,
- QScrollArea,
- QSplitter,
- QFrame,
- QWidgetAction
- )
- from PyQt5.QtCore import pyqtSignal, Qt, pyqtProperty
- from PyQt5.QtGui import QGuiApplication, QPainter, QFontMetrics, QColor
- from searxqt.core.handler import NetworkTypes # for network type filtering.
- from searxqt.core.requests import ErrorType
- from searxqt.widgets.buttons import Button
- from searxqt.widgets.dialogs import UrlDialog, RequestsErrorMessage
- 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._typeDependantButton.setEnabled(False)
- handler = self._filterModel.parentModel().handler()
- if handler.updateInstances(): # True when thread has started.
- handler.updateFinished.connect(self.__updateFinished)
- def __updateFinished(self, errorType, errorMsg):
- handler = self._filterModel.parentModel().handler()
- handler.updateFinished.disconnect(self.__updateFinished)
- if errorType != ErrorType.Success:
- dialog = RequestsErrorMessage(errorType, errorMsg)
- dialog.exec()
- self._typeDependantButton.setEnabled(True)
- # 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 saveSettings(self):
- header = self._tableView.horizontalHeader()
- data = {
- 'hiddenColumnIndexes': self._tableView.getHiddenColumnIndexes(),
- 'headerState': header.saveState(),
- 'splitterState': self._splitter.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'])
- if 'splitterState' in data:
- self._splitter.restoreState(data['splitterState'])
- 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, 0)
- """ Re-implementations
- """
- def contextMenuEvent(self, event):
- def __removeFromWhitelist(self, url):
- # Remove instance url from whitelist without applying the filter.
- self._filterModel.delInstanceFromWhitelist(url)
- selectionModel = self.selectionModel()
- if selectionModel.hasSelection():
- menu = QMenu(self)
- # Add to blacklist
- addToBlacklistAction = menu.addAction(_("Add to blacklist"))
- # Add to temporary blacklist
- addToTmpBlacklistAction = menu.addAction(_("Temporary 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
- indexes = self.selectionModel().selectedRows()
- forAll = None
- for index in indexes:
- url = self.model().getByIndex(index.row())
- if url in self._filterModel.whitelist:
- # 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
- self._filterModel.putInstanceOnBlacklist(
- url, reason=_("Manual")
- )
- self._filterModel.apply()
- elif action == addToTmpBlacklistAction:
- index = selectionModel.selectedRows()[0]
- url = self.model().getByIndex(index.row())
- self._filterModel.putInstanceOnTimeout(url, reason=_("Manual"))
- self._filterModel.apply()
- elif action == addToWhitelistAction:
- # Whitelist
- indexes = self.selectionModel().selectedRows()
- for index in indexes:
- url = self.model().getByIndex(index.row())
- if url not in self._filterModel.whitelist:
- self._filterModel.putInstanceOnWhitelist(url)
- self._filterModel.apply()
- 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 UrlFilterLabel(QLabel):
- """ Fancy QLabel that eludes text and has a hover color property.
- """
- def __init__(self, text, parent):
- QLabel.__init__(self, text, parent=parent)
- self.__hover = False
- self.__hoverColor = QColor()
- self.setMinimumWidth(100)
- @pyqtProperty(QColor)
- def hoverColor(self):
- return self.__hoverColor
- @hoverColor.setter
- def hoverColor(self, color):
- self.__hoverColor = color
- def enterEvent(self, event):
- self.__hover = True
- self.update()
- def leaveEvent(self, event):
- self.__hover = False
- self.update()
- def paintEvent(self, event):
- painter = QPainter(self)
- if self.__hover and self.hoverColor.isValid():
- pen = painter.pen()
- pen.setColor(self.hoverColor)
- painter.setPen(pen)
- metrics = QFontMetrics(self.font())
- elided = metrics.elidedText(self.text(), Qt.ElideRight, self.width())
- painter.drawText(self.rect(), self.alignment(), elided)
- 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 = UrlFilterLabel(url, self)
- delButton = Button("X", self)
- delButton.setSizePolicy(
- QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
- )
- layout.addWidget(label, 0, Qt.AlignTop)
- layout.addWidget(delButton, 0, Qt.AlignTop)
- 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, parent=None):
- QWidget.__init__(self, parent=parent)
- self._model = model
- self._items = {}
- QVBoxLayout(self)
- self.layout().setContentsMargins(0, 0, 0, 0)
- self.layout().setSpacing(0)
- self._model.changed.connect(self.__modelChanged)
- # -- Override below in subclass.
- def filterItems(self):
- return []
- def delete(self, url):
- self._delete(url)
- def itemAdded(self, url):
- """ Callback from when a item has been added, usefull for subclasses
- to do something; for example set a tooltip.
- """
- pass
- # ---
- def __modelChanged(self):
- # Remove old
- for url in list(self._items.keys()):
- if url not in self.filterItems():
- self._items[url].deleteLater()
- del self._items[url]
- # Add new
- for url in self.filterItems():
- if url not in self._items:
- self._add(url)
- def _add(self, url):
- item = UrlFilterItem(url, self)
- self._items.update({url: item})
- item.deleted.connect(self.delete)
- self.layout().addWidget(item)
- self.itemAdded(url)
- def _delete(self, url):
- del self._items[url]
- class WhitelistFilterWidget(UrlFilterWidget):
- def filterItems(self):
- return self._model.whitelist
- def delete(self, url):
- UrlFilterWidget.delete(self, url)
- self._model.delInstanceFromWhitelist(url)
- self._model.apply()
- class BlacklistFilterWidget(UrlFilterWidget):
- def filterItems(self):
- return self._model.blacklist
- def itemAdded(self, url):
- filterItems = self.filterItems()
- dateStr = timeToString(filterItems[url][0] * 60)
- reasonStr = filterItems[url][1]
- tooltipStr = ("<b>{dateLabel}</b>: {dateStr}\n"
- "<b>{reasonLabel}</b>: {reasonStr}"
- ).format(
- dateLabel=_("Date"),
- dateStr=dateStr,
- reasonLabel=_("Reason"),
- reasonStr=reasonStr
- )
- self._items[url].setToolTip(tooltipStr)
- def delete(self, url):
- UrlFilterWidget.delete(self, url)
- self._model.delInstanceFromBlacklist(url)
- self._model.apply()
- class TimeoutFilterWidget(UrlFilterWidget):
- def filterItems(self):
- return self._model.timeoutList
- def itemAdded(self, url):
- # Add reason and duration tooltip
- durationStr = _("Until restart or manual removal.")
- filterItems = self.filterItems()
- timer = filterItems[url][0]
- if timer:
- durationStr = str(timer.interval() / 60000) + "min"
- tooltipStr = ("<b>{reasonLabel}</b>: \n{reason}\n<b>{durationLabel}"
- "</b>: {duration}".format(
- reasonLabel = _("Reason"),
- durationLabel = _("Duration"),
- reason = filterItems[url][1],
- duration = durationStr
- ))
- self._items[url].setToolTip(tooltipStr)
- def delete(self, url):
- UrlFilterWidget.delete(self, url)
- self._model.delInstanceFromTimeout(url)
- self._model.apply()
- 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()
- if NetworkTypes.Web in filter['networkTypes']:
- self._webBox.setChecked(True)
- if NetworkTypes.Tor in filter['networkTypes']:
- self._torBox.setChecked(True)
- if NetworkTypes.I2P in filter['networkTypes']:
- 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 = {
- 'networkTypes': [] # Network Types to pass
- }
- if self._webBox.isChecked():
- result['networkTypes'].append(NetworkTypes.Web)
- if self._torBox.isChecked():
- result['networkTypes'].append(NetworkTypes.Tor)
- if self._i2pBox.isChecked():
- result['networkTypes'].append(NetworkTypes.I2P)
- return result
- 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)
- self.minVersionCombo = QComboBox(self)
- self.gitVersionCheck = QCheckBox(_("Development"), self)
- self.gitVersionCheck.setToolTip(
- _("Include development versions of searx (Git versions) when "
- "checked.")
- )
- # Disable by default since there isn't a version selected by default.
- self.gitVersionCheck.setEnabled(False)
- self.unknownSuffixVersionCheck = QCheckBox(_("Unknown git"), self)
- self.unknownSuffixVersionCheck.setToolTip(
- _("Include git versions with a unknown commit hash when checked.")
- )
- # Disable by default since there isn't a version selected by default.
- self.unknownSuffixVersionCheck.setEnabled(False)
- # Add widgets to layout
- layout.addWidget(self.minVersionCombo)
- layout.addWidget(self.gitVersionCheck)
- layout.addWidget(self.unknownSuffixVersionCheck)
- # Signal connections
- self._model.changed.connect(self.__modelChanged)
- self.minVersionCombo.currentTextChanged.connect(
- self._minVersionComboChanged
- )
- self.gitVersionCheck.stateChanged.connect(self._optionCheckBoxChanged)
- self.unknownSuffixVersionCheck.stateChanged.connect(
- self._optionCheckBoxChanged
- )
- def _minVersionComboChanged(self, versionStr):
- """ From the ComboBox
- """
- self._model.changed.disconnect(self.__modelChanged)
- self._model.updateKwargs(self.data()) # update the model.
- self._minVersionChanged()
- self._model.changed.connect(self.__modelChanged)
- def _minVersionChanged(self):
- """ Minimum version has changed, it doesn't matter if it comes from the
- ComboBox or the Model.
- """
- # Enable/Disable the checkboxes based on wheter a minimum version is
- # selected or not.
- enabled = bool(self.minVersionCombo.currentIndex() != 0)
- self.gitVersionCheck.setEnabled(enabled)
- self.unknownSuffixVersionCheck.setEnabled(enabled)
- def _optionCheckBoxChanged(self, checkState):
- """ 'Development' or 'Unknown suffix' CheckBox has changed.
- """
- self._model.updateKwargs(self.data()) # update the model.
- def _compileVersions(self):
- """ Fill the combobox with available version strings
- """
- # Backup selected text so we can find the new index if it still exists.
- versionFilter = self._model.filter().get('version', {})
- selectedText = versionFilter.get('min', "")
- # Clear the combo
- self.minVersionCombo.clear()
- # Add the default None item
- self.minVersionCombo.addItem(_("Off"))
- # Unique
- uniqueVersions = []
- for url, instance in self._model.parentModel().items():
- if (
- instance.version.type and
- str(instance.version) not in uniqueVersions
- ):
- uniqueVersions.append(str(instance.version))
- # Sort
- uniqueVersions.sort()
- # Add versions to combobox
- selectedIndex = 0
- for versionStr in uniqueVersions:
- if versionStr == selectedText:
- # The selected item is still there, store it's index so we can
- # set it back later.
- selectedIndex = self.minVersionCombo.count()
- self.minVersionCombo.addItem(versionStr)
- # Restore the selected index
- self.minVersionCombo.setCurrentIndex(selectedIndex)
- # Enable/Disable the checkboxes based on wheter a minimum version is
- # selected or not.
- self._minVersionChanged()
- def __modelChanged(self):
- # Instances model has changed
- # Update versions combo
- self.minVersionCombo.currentTextChanged.disconnect(
- self._minVersionComboChanged
- )
- self._compileVersions() # re-generate the combobox items
- self.minVersionCombo.currentTextChanged.connect(
- self._minVersionComboChanged
- )
- versionFilter = self._model.filter().get('version', {})
- self.gitVersionCheck.setChecked(versionFilter.get('git', True))
- self.unknownSuffixVersionCheck.setChecked(
- versionFilter.get('unknown', True)
- )
- def data(self):
- result = {
- 'version': {
- 'min': self.minVersionCombo.currentText(),
- 'git': bool(self.gitVersionCheck.checkState()),
- 'unknown': bool(self.unknownSuffixVersionCheck.checkState())
- }
- }
- return result
- 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._analyticsFilter = None
- self._versionFilter = VersionFilter(model, self)
- layout.addRow(QLabel(_("Min version") + ":"), self._versionFilter)
- self._urlFilterOut = BlacklistFilterWidget(model, self)
- layout.addRow(QLabel(_("Blacklist") + ":"), self._urlFilterOut)
- self._urlFilter = WhitelistFilterWidget(model, self)
- layout.addRow(QLabel(_("Whitelist") + ":"), self._urlFilter)
- self._tmpBlacklist = TimeoutFilterWidget(model, self)
- layout.addRow(QLabel(_("Timeout") + ":"), self._tmpBlacklist)
- 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)
- if not self._analyticsFilter:
- self._analyticsFilter = CheckboxFilter(
- self._model,
- 'analytics',
- self
- )
- label = QLabel(_("Excl. analytics") + ":")
- label.setWordWrap(True)
- label.setToolTip(_(
- "Exclude instances running tracking software."
- ))
- layout.insertRow(4, label, self._analyticsFilter)
- 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
- if self._analyticsFilter:
- self._analyticsFilter.deleteLater()
- layout.removeRow(2)
- self._analyticsFilter = 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)))
|