search.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. ########################################################################
  2. # Searx-Qt - Lightweight desktop application for Searx.
  3. # Copyright (C) 2020-2022 CYBERDEViL
  4. #
  5. # This file is part of Searx-Qt.
  6. #
  7. # Searx-Qt is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Searx-Qt is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. #
  20. ########################################################################
  21. from PyQt5.QtWidgets import (
  22. QWidget,
  23. QVBoxLayout,
  24. QHBoxLayout,
  25. QLineEdit,
  26. QTextBrowser,
  27. QCheckBox,
  28. QLabel,
  29. QComboBox,
  30. QFrame,
  31. QMenu,
  32. QWidgetAction,
  33. QShortcut,
  34. QSpacerItem,
  35. QSizePolicy,
  36. QDialog,
  37. QListWidget,
  38. QTableView,
  39. QSplitter,
  40. QAbstractItemView,
  41. QHeaderView,
  42. QFormLayout,
  43. QMessageBox
  44. )
  45. from PyQt5.QtCore import pyqtSignal, Qt, QVariant, QByteArray, QEvent
  46. from PyQt5.QtGui import (
  47. QDesktopServices,
  48. QStandardItem,
  49. QStandardItemModel,
  50. QTextDocument
  51. )
  52. from searxqt.core.customAnchorCmd import AnchorCMD
  53. from searxqt.core.htmlGen import ResultsHtml, FailedResponsesHtml
  54. from searxqt.core.guard import ConsequenceType
  55. from searxqt.core.requests import ErrorType
  56. from searxqt.models.search import (
  57. SearchStatus,
  58. UserCategoriesModel,
  59. CategoriesModel
  60. )
  61. from searxqt.models.instances import EnginesTableModel
  62. from searxqt.widgets.buttons import Button, CheckboxOptionsButton
  63. from searxqt.thread import Thread
  64. from searxqt.translations import _
  65. from searxqt.themes import Themes
  66. from searxqt.core import log
  67. class SearchNavigation(QWidget):
  68. requestPage = pyqtSignal(int) # pageno
  69. def __init__(self, parent=None):
  70. QWidget.__init__(self, parent=parent)
  71. layout = QHBoxLayout(self)
  72. self.prevPageButton = Button("◄", self)
  73. self.pageNoLabel = QLabel("1", self)
  74. self.nextPageButton = Button("►", self)
  75. layout.addWidget(self.prevPageButton, 0, Qt.AlignLeft)
  76. layout.addWidget(self.pageNoLabel, 0, Qt.AlignCenter)
  77. layout.addWidget(self.nextPageButton, 0, Qt.AlignRight)
  78. self.prevPageButton.setEnabled(False)
  79. self.nextPageButton.clicked.connect(self._nextPage)
  80. self.prevPageButton.clicked.connect(self._prevPage)
  81. self.reset()
  82. def _updateLabel(self):
  83. self.pageNoLabel.setText(str(self._pageno))
  84. def _nextPage(self):
  85. self._pageno += 1
  86. if self._pageno > 1 and not self.prevPageButton.isEnabled():
  87. self.prevPageButton.setEnabled(True)
  88. self._updateLabel()
  89. self.requestPage.emit(self._pageno)
  90. def _prevPage(self):
  91. self._pageno -= 1
  92. if self._pageno == 1:
  93. self.prevPageButton.setEnabled(False)
  94. self.setNextEnabled(True)
  95. self._updateLabel()
  96. self.requestPage.emit(self._pageno)
  97. def reset(self):
  98. self._pageno = 1
  99. self.prevPageButton.setEnabled(False)
  100. self._updateLabel()
  101. def setNextEnabled(self, state):
  102. self.nextPageButton.setEnabled(state)
  103. class SearchEngines(CheckboxOptionsButton):
  104. def __init__(self, searchModel, instancesModel, parent=None):
  105. """
  106. @param searchModel: needed for getting and setting current
  107. enabled/disabled engines.
  108. @type searchModel: SearchModel
  109. @param instancesModel: needed for listing current available
  110. engines and update it's current filter
  111. to filter out instances without atleast
  112. one of the required engine(s).
  113. @type instancesModel: InstanceModelFilter
  114. """
  115. self._instancesModel = instancesModel
  116. self._searchModel = searchModel
  117. CheckboxOptionsButton.__init__(
  118. self,
  119. labelName=_("Engines"),
  120. parent=parent
  121. )
  122. instancesModel.parentModel().changed.connect(self.reGenerate)
  123. def updateFilter(self):
  124. """ Filter out instances that don't support atleast one of the
  125. enabled engines.
  126. """
  127. self._instancesModel.updateKwargs(
  128. {'engines': self.getCheckedOptionNames()}
  129. )
  130. """ Below are re-implementations.
  131. """
  132. def getCheckedOptionNames(self):
  133. """ Should return a list with checked option names. This will
  134. be used to generate the label.
  135. @return: should return a list with strings.
  136. @rtype: list
  137. """
  138. return self._searchModel.engines
  139. def getOptions(self):
  140. """ Should return a list with options tuple(key, name, state)
  141. This will be used to generate the options.
  142. """
  143. list_ = []
  144. tmp = []
  145. for url, instance in self._instancesModel.items():
  146. for engine in instance.engines:
  147. if engine.name not in tmp:
  148. state = bool(engine.name in self._searchModel.engines)
  149. list_.append((engine.name, engine.name, state))
  150. tmp.append(engine.name)
  151. return sorted(list_)
  152. def optionToggled(self, key, state):
  153. if state:
  154. self._searchModel.engines.append(key)
  155. else:
  156. self._searchModel.engines.remove(key)
  157. self.updateFilter()
  158. class CategoryEditor(QDialog):
  159. def __init__(self, enginesModel, categoriesModel,
  160. userCategoriesModel, parent=None):
  161. QDialog.__init__(self, parent=parent)
  162. self._categoriesModel = categoriesModel
  163. self._userCategoriesModel = userCategoriesModel
  164. self.setWindowTitle(_("Category manager"))
  165. layout = QHBoxLayout(self)
  166. # Splitter to horizontal split the categories widget and the engines
  167. # widget so their width becomes adjustable.
  168. self.splitter = QSplitter(self)
  169. self.splitter.setOrientation(Qt.Horizontal)
  170. layout.addWidget(self.splitter)
  171. # Categories
  172. catWidget = QWidget(self.splitter)
  173. catLayout = QVBoxLayout(catWidget)
  174. label = QLabel(f"<h2>{_('Categories')}</h2>", self)
  175. # Categories toolbuttons
  176. catToolLayout = QHBoxLayout()
  177. catAddButton = Button("+", self)
  178. self._catDelButton = Button("-", self)
  179. catToolLayout.addWidget(catAddButton, 0, Qt.AlignLeft)
  180. catToolLayout.addWidget(self._catDelButton, 1, Qt.AlignLeft)
  181. self._categoryListWidget = QListWidget(self)
  182. catLayout.addWidget(label)
  183. catLayout.addLayout(catToolLayout)
  184. catLayout.addWidget(self._categoryListWidget)
  185. # Engines
  186. engWidget = QWidget(self.splitter)
  187. engLayout = QVBoxLayout(engWidget)
  188. label = QLabel(f"<h2>{_('Engines')}</h2>", self)
  189. # Engines filter
  190. filterLayout = QHBoxLayout()
  191. self._enginesCategoryFilterBox = QComboBox(self)
  192. self._enginesCategoryFilterBox.addItem(_("All"))
  193. for key, cat in categoriesModel.items():
  194. self._enginesCategoryFilterBox.addItem(cat.name)
  195. filterLayout.addWidget(
  196. QLabel(_("Category") + ":", self), 1, Qt.AlignRight
  197. )
  198. filterLayout.addWidget(
  199. self._enginesCategoryFilterBox, 0, Qt.AlignRight
  200. )
  201. # Engines table
  202. self._enginesTableView = QTableView(self)
  203. self._enginesTableView.setAlternatingRowColors(True)
  204. self._enginesTableView.setSelectionBehavior(
  205. QAbstractItemView.SelectRows
  206. )
  207. self._enginesTableView.setEditTriggers(
  208. QAbstractItemView.NoEditTriggers
  209. )
  210. self._enginesTableView.setSortingEnabled(True)
  211. self._enginesTableView.setHorizontalScrollMode(
  212. QAbstractItemView.ScrollPerPixel
  213. )
  214. header = self._enginesTableView.horizontalHeader()
  215. header.setSectionResizeMode(QHeaderView.ResizeToContents)
  216. header.setSectionsMovable(True)
  217. self._enginesTableModel = EnginesTableModel(enginesModel, self)
  218. self._enginesTableView.setModel(self._enginesTableModel)
  219. engLayout.addWidget(label)
  220. engLayout.addLayout(filterLayout)
  221. engLayout.addWidget(self._enginesTableView)
  222. # Connections
  223. catAddButton.clicked.connect(self.__addCategoryClicked)
  224. self._catDelButton.clicked.connect(self.__delCategoryClicked)
  225. self._categoryListWidget.currentRowChanged.connect(
  226. self.__currentUserCategoryChanged
  227. )
  228. self._enginesCategoryFilterBox.currentIndexChanged.connect(
  229. self.__enginesCategoryFilterChanged
  230. )
  231. self._enginesTableView.setEnabled(False)
  232. self._catDelButton.setEnabled(False)
  233. self.__addUserCategories()
  234. self.__selectFirst()
  235. def __currentUserCategoryChanged(self, index):
  236. if index < 0:
  237. self._enginesTableView.setEnabled(False)
  238. self._catDelButton.setEnabled(False)
  239. else:
  240. self._enginesTableView.setEnabled(True)
  241. self._catDelButton.setEnabled(True)
  242. if self._userCategoriesModel:
  243. key = list(self._userCategoriesModel.keys())[index]
  244. self._enginesTableModel.setUserModel(
  245. self._userCategoriesModel[key]
  246. )
  247. def __addUserCategories(self):
  248. for catKey, cat in self._userCategoriesModel.items():
  249. self._categoryListWidget.addItem(cat.name)
  250. def __selectFirst(self):
  251. if self._categoryListWidget.count():
  252. self._categoryListWidget.setCurrentRow(0)
  253. def __selectLast(self):
  254. self._categoryListWidget.setCurrentRow(
  255. self._categoryListWidget.count() - 1
  256. )
  257. def __reloadUserCategories(self):
  258. self._categoryListWidget.currentRowChanged.disconnect(
  259. self.__currentUserCategoryChanged
  260. )
  261. self._enginesTableModel.setUserModel(None)
  262. self._categoryListWidget.clear()
  263. self.__addUserCategories()
  264. self._categoryListWidget.currentRowChanged.connect(
  265. self.__currentUserCategoryChanged
  266. )
  267. def __addCategoryClicked(self, state):
  268. dialog = AddUserCategoryDialog(
  269. self._userCategoriesModel.keys()
  270. )
  271. if dialog.exec():
  272. self._userCategoriesModel.addCategory(
  273. dialog.name.lower(),
  274. dialog.name
  275. )
  276. self.__reloadUserCategories()
  277. self.__selectLast()
  278. def __delCategoryClicked(self, state):
  279. index = self._categoryListWidget.currentRow()
  280. key = list(self._userCategoriesModel.keys())[index]
  281. confirmDialog = QMessageBox()
  282. confirmDialog.setWindowTitle(
  283. _("Delete category")
  284. )
  285. categoryName = self._userCategoriesModel[key].name
  286. confirmDialog.setText(_("Are you sure you want to delete the " \
  287. f"category `{categoryName}`?"))
  288. confirmDialog.setStandardButtons(
  289. QMessageBox.Yes | QMessageBox.No
  290. )
  291. confirmDialog.button(QMessageBox.Yes).setText(_("Yes"))
  292. confirmDialog.button(QMessageBox.No).setText(_("No"))
  293. if confirmDialog.exec() != QMessageBox.Yes:
  294. return
  295. self._userCategoriesModel.removeCategory(key)
  296. self.__reloadUserCategories()
  297. self.__selectLast()
  298. self.__currentUserCategoryChanged(
  299. self._categoryListWidget.count() - 1
  300. )
  301. def __enginesCategoryFilterChanged(self, index):
  302. if not index: # All
  303. self._enginesTableModel.setCatFilter()
  304. else:
  305. key = list(self._categoriesModel.keys())[index-1]
  306. self._enginesTableModel.setCatFilter(key)
  307. class AddUserCategoryDialog(QDialog):
  308. def __init__(self, existingNames=[], text="", parent=None):
  309. QDialog.__init__(self, parent=parent)
  310. self._existingNames = existingNames
  311. layout = QFormLayout(self)
  312. label = QLabel(_("Name") + ":")
  313. self._nameEdit = QLineEdit(self)
  314. if text:
  315. self._nameEdit.setText(text)
  316. self._nameEdit.setPlaceholderText(text)
  317. else:
  318. self._nameEdit.setPlaceholderText(_("My category"))
  319. self._cancelButton = Button(_("Cancel"), self)
  320. self._addButton = Button(_("Add"), self)
  321. self._addButton.setEnabled(False)
  322. # Add stuff to layout
  323. layout.addRow(label, self._nameEdit)
  324. layout.addRow(self._cancelButton, self._addButton)
  325. # Connections
  326. self._nameEdit.textChanged.connect(self.__inputChanged)
  327. self._addButton.clicked.connect(self.accept)
  328. self._cancelButton.clicked.connect(self.reject)
  329. def __inputChanged(self, text):
  330. if self.isValid():
  331. self._addButton.setEnabled(True)
  332. else:
  333. self._addButton.setEnabled(False)
  334. def isValid(self):
  335. name = self._nameEdit.text().lower()
  336. if not name:
  337. return False
  338. for existingName in self._existingNames:
  339. if name == existingName.lower():
  340. return False
  341. return True
  342. @property
  343. def name(self):
  344. return self._nameEdit.text()
  345. class SearchCategories(CheckboxOptionsButton):
  346. def __init__(self, categoriesModel, instanceCategoriesModel, enginesModel,
  347. userCategoriesModel, parent=None):
  348. """
  349. @param categoriesModel: Predefined categories (only avaiable when at
  350. least one instance has the category).
  351. @type categoriesModel: searxqt.models.search.CategoriesModel
  352. @param instanceCategoriesModel: Some instances define custom search
  353. categories.
  354. @type instanceCategoriesModel: searxqt.models.search.CategoriesModel
  355. @param enginesModel:
  356. @type enginesModel: searxqt.models.instances.EnginesModel
  357. @param userCategoriesModel:
  358. @type userCategoriesModel: searxqt.models.search.UserCategoriesModel
  359. @param parent:
  360. @type parent: QObject or None
  361. """
  362. self._categoriesModel = categoriesModel
  363. self._instanceCategoriesModel = instanceCategoriesModel
  364. self._enginesModel = enginesModel
  365. self._userCategoriesModel = userCategoriesModel
  366. CheckboxOptionsButton.__init__(
  367. self,
  368. labelName=_("Categories"),
  369. parent=parent
  370. )
  371. self._categoriesModel.dataChanged.connect(self.__categoryDataChanged)
  372. def __categoryDataChanged(self):
  373. # This happends after CategoriesModel.setData
  374. self.reGenerate()
  375. def __openUserCategoryEditor(self):
  376. window = CategoryEditor(
  377. self._enginesModel,
  378. self._categoriesModel,
  379. self._userCategoriesModel, self)
  380. window.exec()
  381. def __userCategoryToggled(self, key, state):
  382. if state:
  383. self._userCategoriesModel[key].check()
  384. else:
  385. self._userCategoriesModel[key].uncheck()
  386. self.reGenerate()
  387. def __instanceCategoryToggled(self, key, state):
  388. if state:
  389. self._instanceCategoriesModel[key].check()
  390. else:
  391. self._instanceCategoriesModel[key].uncheck()
  392. self.reGenerate()
  393. """ Below are re-implementations.
  394. """
  395. def addCustomWidgetsTop(self, menu):
  396. # User specified categories
  397. menu.addSection(_("Custom"))
  398. action = QWidgetAction(menu)
  399. manageCustomButton = Button(_("Manage"), menu)
  400. action.setDefaultWidget(manageCustomButton)
  401. menu.addAction(action)
  402. for catKey, cat in self._userCategoriesModel.items():
  403. action = QWidgetAction(menu)
  404. widget = QCheckBox(cat.name, menu)
  405. widget.setTristate(False)
  406. widget.setChecked(
  407. cat.isChecked()
  408. )
  409. action.setDefaultWidget(widget)
  410. widget.stateChanged.connect(
  411. lambda state, key=catKey:
  412. self.__userCategoryToggled(key, state)
  413. )
  414. menu.addAction(action)
  415. # Custom instance specified categories
  416. menu.addSection(_("Instances"))
  417. for catKey, cat in self._instanceCategoriesModel.items():
  418. action = QWidgetAction(menu)
  419. widget = QCheckBox(cat.name, menu)
  420. widget.setTristate(False)
  421. widget.setChecked(cat.isChecked())
  422. action.setDefaultWidget(widget)
  423. widget.stateChanged.connect(
  424. lambda state, key=catKey:
  425. self.__instanceCategoryToggled(key, state)
  426. )
  427. menu.addAction(action)
  428. # Predefined Searx categories
  429. menu.addSection(_("Default"))
  430. manageCustomButton.clicked.connect(self.__openUserCategoryEditor)
  431. def hasEnabledCheckedKeys(self):
  432. """ Same as CheckboxOptionsButton.hasEnabledCheckedKeys(self) but with
  433. User Categories. Categories don't get enabled/disabled so we can skip
  434. that check.
  435. @rtype: bool
  436. """
  437. if self._userCategoriesModel.checkedCategories():
  438. return True
  439. elif self._instanceCategoriesModel.checkedCategories():
  440. return True
  441. return CheckboxOptionsButton.hasEnabledCheckedKeys(self)
  442. def uncheckAllEnabledKeys(self):
  443. """ Unchecks all checked keys that are enabled.
  444. """
  445. for catKey in self._userCategoriesModel.checkedCategories():
  446. self._userCategoriesModel[catKey].uncheck()
  447. for catKey in self._instanceCategoriesModel.checkedCategories():
  448. self._instanceCategoriesModel[catKey].uncheck()
  449. CheckboxOptionsButton.uncheckAllEnabledKeys(self)
  450. def getCheckedOptionNames(self):
  451. """ Should return a list with checked option names. This will
  452. be used to generate the label.
  453. @return: should return a list with strings.
  454. @rtype: list
  455. """
  456. return(
  457. [
  458. self._categoriesModel[catKey].name
  459. for catKey in self._categoriesModel.checkedCategories()
  460. ] +
  461. [
  462. self._instanceCategoriesModel[catKey].name
  463. for catKey in self._instanceCategoriesModel.checkedCategories()
  464. ] +
  465. [
  466. self._userCategoriesModel[catKey].name
  467. for catKey in self._userCategoriesModel.checkedCategories()
  468. ]
  469. )
  470. def getOptions(self):
  471. """ Should return a list with options tuple(key, name, state)
  472. This will be used to generate the options.
  473. """
  474. list_ = []
  475. for catKey in self._categoriesModel:
  476. list_.append(
  477. (
  478. catKey,
  479. self._categoriesModel[catKey].name,
  480. self._categoriesModel[catKey].isChecked()
  481. )
  482. )
  483. return list_
  484. def optionToggled(self, key, state):
  485. if state:
  486. self._categoriesModel[key].check()
  487. else:
  488. self._categoriesModel[key].uncheck()
  489. class SearchPeriod(QComboBox):
  490. def __init__(self, model, parent=None):
  491. QComboBox.__init__(self, parent=parent)
  492. self._model = model
  493. self.setMinimumContentsLength(2)
  494. for period in model.Periods:
  495. self.addItem(model.Periods[period], QVariant(period))
  496. self.currentIndexChanged.connect(self.__indexChanged)
  497. def __indexChanged(self, index):
  498. self._model.timeRange = self.currentData()
  499. class SearchLanguage(QComboBox):
  500. def __init__(self, model, parent=None):
  501. QComboBox.__init__(self, parent=parent)
  502. self._model = model
  503. self._favorites = []
  504. self.setMinimumContentsLength(2)
  505. self.__itemModel = QStandardItemModel(self)
  506. self.setModel(self.__itemModel)
  507. self.currentIndexChanged.connect(self.__indexChanged)
  508. self.__itemModel.itemChanged.connect(self.__favCheckChanged)
  509. def __indexChanged(self, index):
  510. self._model.lang = self.currentData()
  511. def __favCheckChanged(self, item):
  512. lang = item.data(Qt.UserRole)
  513. index = item.row()
  514. newIndex = 0
  515. if item.checkState():
  516. # Language added to favorites.
  517. self._favorites.append(lang)
  518. else:
  519. # Remove language from favorites.
  520. langList = list(self._model.Languages.keys())
  521. newIndex = langList.index(lang)
  522. self._favorites.remove(lang)
  523. # Index offset
  524. for favLang in self._favorites:
  525. if langList.index(favLang) < newIndex:
  526. newIndex -= 1
  527. newIndex += len(self._favorites)
  528. self.__itemModel.takeRow(index)
  529. self.__itemModel.insertRow(newIndex, item)
  530. def populate(self):
  531. self.__itemModel.clear()
  532. for lang in self._model.Languages:
  533. newItem = QStandardItem(self._model.Languages[lang])
  534. newItem.setCheckable(True)
  535. newItem.setFlags(
  536. Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
  537. )
  538. newItem.setData(QVariant(lang), Qt.UserRole)
  539. if lang in self._favorites:
  540. newItem.setData(Qt.Checked, Qt.CheckStateRole)
  541. self.__itemModel.insertRow(0, newItem)
  542. continue
  543. newItem.setData(Qt.Unchecked, Qt.CheckStateRole)
  544. self.__itemModel.appendRow(newItem)
  545. def loadSettings(self, data):
  546. for lang in data.get('favs', []):
  547. self._favorites.append(lang)
  548. self.populate()
  549. # Find and set the index that matches lang
  550. self.setCurrentIndex(
  551. self.findData(QVariant(data.get('lang', '')), Qt.UserRole)
  552. )
  553. def saveSettings(self):
  554. return {
  555. 'lang': str(self.currentData()),
  556. 'favs': self._favorites
  557. }
  558. class SearchOptionsContainer(QFrame):
  559. """ Custom QFrame to be able to show or hide certain widgets.
  560. """
  561. def __init__(self, searchModel, instancesModel, enginesModel, parent=None):
  562. """
  563. @param searchModel:
  564. @type searchModel: searxqt.models.search.SearchModel
  565. @param instancesModel:
  566. @type instancesModel: searxqt.models.instances.InstanceModelFilter
  567. @param enginesModel:
  568. @type enginesModel: searxqt.models.instances.EnginesModel
  569. @param parent:
  570. @type parent: QObject or None
  571. """
  572. QFrame.__init__(self, parent=parent)
  573. self._enginesModel = enginesModel
  574. self._searchModel = searchModel
  575. self._categoriesModel = CategoriesModel()
  576. self._instanceCategoriesModel = CategoriesModel()
  577. self._userCategoriesModel = UserCategoriesModel()
  578. # Backup user checked engines.
  579. self.__userCheckedBackup = []
  580. # Keep track of disabled engines (these engines are disabled
  581. # because they are part of one or more checked categories).
  582. #
  583. # @key: engine name (str)
  584. # @value : list with category keys (str)
  585. self.__disabledByCat = {}
  586. layout = QHBoxLayout(self)
  587. self._widgets = {
  588. 'categories': SearchCategories(
  589. self._categoriesModel,
  590. self._instanceCategoriesModel,
  591. enginesModel,
  592. self._userCategoriesModel,
  593. self
  594. ),
  595. 'engines': SearchEngines(searchModel, instancesModel, self),
  596. 'period': SearchPeriod(searchModel, self),
  597. 'lang': SearchLanguage(searchModel, self)
  598. }
  599. for widget in self._widgets.values():
  600. layout.addWidget(widget, 0, Qt.AlignTop)
  601. # Keep widgets left aligned.
  602. spacer = QSpacerItem(
  603. 40, 20, QSizePolicy.MinimumExpanding, QSizePolicy.Minimum
  604. )
  605. layout.addItem(spacer)
  606. # Connections
  607. self._categoriesModel.stateChanged.connect(
  608. self.__categoriesStateChanged
  609. )
  610. self._instanceCategoriesModel.stateChanged.connect(
  611. self.__categoriesStateChanged
  612. )
  613. self._userCategoriesModel.stateChanged.connect(
  614. self.__userCategoriesStateChanged
  615. )
  616. self._userCategoriesModel.changed.connect(self.__userCategoriesChanged)
  617. self._userCategoriesModel.removed.connect(self.__userCategoryRemoved)
  618. self._enginesModel.changed.connect(self.__enginesModelChanged)
  619. def __enginesModelChanged(self):
  620. """Settings loaded or data updated
  621. """
  622. # Remove deleted engines from __disabledByCat
  623. for engine in list(self.__disabledByCat.keys()):
  624. if engine not in self._enginesModel:
  625. del self.__disabledByCat[engine]
  626. self._widgets['engines'].setKeyEnabled(engine)
  627. # Add new categories
  628. for catKey in self._enginesModel.categories():
  629. if catKey not in self._categoriesModel:
  630. name = ""
  631. if catKey in self._searchModel.categories.types:
  632. # Default pre-defined categories are translatable
  633. name = self._searchModel.categories.types[catKey][0]
  634. self._categoriesModel.addCategory(catKey, name)
  635. else:
  636. name = catKey.capitalize()
  637. log.debug(f"Found non default category `{name}`", self)
  638. self._instanceCategoriesModel.addCategory(catKey, name)
  639. # Remove old categories
  640. for catKey in self._categoriesModel.copy():
  641. if catKey not in self._enginesModel.categories():
  642. self._categoriesModel.removeCategory(catKey)
  643. # Release potentialy checked engines
  644. self.__processCategoriesStateChange(
  645. [engine.name for engine in
  646. self._enginesModel.getByCategory(catKey)],
  647. catKey,
  648. False
  649. )
  650. # Remove old instance specific categories
  651. for catKey in self._instanceCategoriesModel.copy():
  652. if (catKey not in self._enginesModel.categories() and
  653. catKey not in self._categoriesModel):
  654. self._instanceCategoriesModel.removeCategory(catKey)
  655. # Release potentialy checked engines
  656. self.__processCategoriesStateChange(
  657. [engine.name for engine in
  658. self._enginesModel.getByCategory(catKey)],
  659. catKey,
  660. False
  661. )
  662. self._widgets['categories'].reGenerate()
  663. self.__finalizeCategoriesStateChange()
  664. def __userCategoryRemoved(self, catKey):
  665. for engineKey, catList in self.__disabledByCat.copy().items():
  666. if catKey in catList:
  667. self.__uncheckEngineByCat(catKey, engineKey)
  668. self._widgets['categories'].reGenerate()
  669. self.__finalizeCategoriesStateChange()
  670. def __userCategoriesChanged(self, catKey):
  671. """ When the user edited a existing user-category this should
  672. check freshly added engines to this category and uncheck engines
  673. that have been removed from this category.
  674. """
  675. if self._userCategoriesModel[catKey].isChecked():
  676. engines = self._userCategoriesModel[catKey].engines
  677. # Uncheck removed engines
  678. for engineKey, categories in self.__disabledByCat.copy().items():
  679. if catKey in categories:
  680. if engineKey not in engines:
  681. self.__uncheckEngineByCat(catKey, engineKey)
  682. # Check newly added engines
  683. for engineKey in engines:
  684. if engineKey not in self.__disabledByCat:
  685. self.__checkEngineByCat(catKey, engineKey)
  686. self.__finalizeCategoriesStateChange()
  687. def __checkEngineByCat(self, catKey, engineKey):
  688. """ This method handles checking of a engine by a category.
  689. @param catKey: Category key
  690. @type catKey: str
  691. @param engineKey: Engine key
  692. @type engineKey: str
  693. """
  694. if engineKey not in self._searchModel.engines:
  695. # User did not check this engine so we are going to.
  696. self._searchModel.engines.append(
  697. engineKey
  698. )
  699. elif(engineKey not in self.__userCheckedBackup and
  700. not self._widgets['engines'].keyDisabled(engineKey)):
  701. # User did check this engine, so we backup that.
  702. self.__userCheckedBackup.append(engineKey)
  703. if not self._widgets['engines'].keyDisabled(engineKey):
  704. # Disable the engine from being toggled by the user.
  705. self._widgets['engines'].setKeyDisabled(engineKey)
  706. if engineKey not in self.__disabledByCat:
  707. self.__disabledByCat.update({engineKey: []})
  708. # Backup that this category is blocking this engine from
  709. # being toggled by the user.
  710. self.__disabledByCat[engineKey].append(catKey)
  711. def __uncheckEngineByCat(self, catKey, engineKey):
  712. """ This method handles the unchecking of a engine by a category.
  713. @param catKey: Category key
  714. @type catKey: str
  715. @param engineKey: Engine key
  716. @type engineKey: str
  717. """
  718. if engineKey in self.__disabledByCat:
  719. if catKey in self.__disabledByCat[engineKey]:
  720. # This category no longer blocks this engine from
  721. # being edited by the user.
  722. self.__disabledByCat[engineKey].remove(catKey)
  723. if not self.__disabledByCat[engineKey]:
  724. # No category left that blocks this engine from
  725. # user-toggleing.
  726. self._widgets['engines'].setKeyEnabled(engineKey)
  727. self.__disabledByCat.pop(engineKey)
  728. if engineKey not in self.__userCheckedBackup:
  729. # User didn't check this engine, so we can
  730. # uncheck it.
  731. self._searchModel.engines.remove(
  732. engineKey
  733. )
  734. else:
  735. # User did check this engine before checking
  736. # this category so we won't uncheck it.
  737. self.__userCheckedBackup.remove(engineKey)
  738. def __userCategoriesStateChanged(self, catKey, state):
  739. """ The user checked or unchecked a user-category.
  740. @param catKey: Category key
  741. @type catKey: str
  742. @param state:Category enabled or disabled (checked or unchecked)
  743. @type state: bool
  744. """
  745. self.__processCategoriesStateChange(
  746. self._userCategoriesModel[catKey].engines,
  747. catKey,
  748. state
  749. )
  750. self._widgets['categories'].reGenerate()
  751. self.__finalizeCategoriesStateChange()
  752. def __categoriesStateChanged(self, catKey, state):
  753. """ The user checked or unchecked a default-category.
  754. @param catKey: Category key
  755. @type catKey: str
  756. @param state: Category enabled or disabled (checked or unchecked)
  757. @type state: bool
  758. """
  759. self.__processCategoriesStateChange(
  760. [engine.name for engine in
  761. self._enginesModel.getByCategory(catKey)],
  762. catKey,
  763. state
  764. )
  765. self._widgets['categories'].reGenerate()
  766. self.__finalizeCategoriesStateChange()
  767. def __processCategoriesStateChange(self, engines, catKey, state):
  768. """ The user checked or unchecked a category, depending on the
  769. `state` variable.
  770. When a category gets checked all the engines in that category
  771. will be checked and disabled so that the user can't toggle the
  772. engine.
  773. On uncheck of a category all engines in that category should be
  774. re-enabled. And those engines should be unchecked if they weren't
  775. checked by the user before checking this category.
  776. @param engines: A list with engineKeys (str) that are part of the
  777. category (catKey).
  778. @type engines: list
  779. @param catKey: Category key
  780. @type catKey: str
  781. @param state: Category enabled or disabled (checked or unchecked)
  782. @type state: bool
  783. """
  784. if state:
  785. # Category checked.
  786. for engine in engines:
  787. self.__checkEngineByCat(catKey, engine)
  788. else:
  789. # Category unchecked.
  790. for engine in engines:
  791. self.__uncheckEngineByCat(catKey, engine)
  792. def __finalizeCategoriesStateChange(self):
  793. # Re-generate the engines label
  794. self._widgets['engines'].reGenerate()
  795. # Update the instances filter.
  796. self._widgets['engines'].updateFilter()
  797. def saveSettings(self):
  798. data = {}
  799. # Store widgets visible state.
  800. for key, widget in self._widgets.items():
  801. data.update({
  802. f"{key}Visible": not widget.isHidden()
  803. })
  804. # Store category states and CheckboxOptionsButton states (label
  805. # expanded or collapsed)
  806. data.update({
  807. 'userCatModel': self._userCategoriesModel.data(),
  808. 'defaultCatModel': self._categoriesModel.data(),
  809. 'categoriesButton': self._widgets['categories'].saveSettings(),
  810. 'enginesButton': self._widgets['engines'].saveSettings(),
  811. 'language': self._widgets['lang'].saveSettings()
  812. })
  813. return data
  814. def loadSettings(self, data):
  815. # Set widgets visible or hidden depending on their state.
  816. for key, widget in self._widgets.items():
  817. if data.get(f"{key}Visible", True):
  818. widget.show()
  819. else:
  820. widget.hide()
  821. # Load category states
  822. self._userCategoriesModel.setData(data.get('userCatModel', {}))
  823. self._categoriesModel.setData(data.get('defaultCatModel', {}))
  824. # Load CheckboxOptionsButton states (categories and engines label
  825. # states, expanded or collapsed.)
  826. self._widgets['categories'].loadSettings(
  827. data.get('categoriesButton', {})
  828. )
  829. self._widgets['engines'].loadSettings(data.get('enginesButton', {}))
  830. # Load search language.
  831. self._widgets['lang'].loadSettings(data.get('language', {}))
  832. def __checkBoxStateChanged(self, key, state):
  833. if state:
  834. self._widgets[key].show()
  835. else:
  836. self._widgets[key].hide()
  837. """ QFrame re-implementations
  838. """
  839. def contextMenuEvent(self, event):
  840. menu = QMenu(self)
  841. menu.addSection(_("Show / Hide"))
  842. for key, widget in self._widgets.items():
  843. action = QWidgetAction(menu)
  844. checkbox = QCheckBox(key, menu)
  845. checkbox.setTristate(False)
  846. checkbox.setChecked(not widget.isHidden())
  847. action.setDefaultWidget(checkbox)
  848. checkbox.stateChanged.connect(
  849. lambda state, key=key:
  850. self.__checkBoxStateChanged(key, state)
  851. )
  852. menu.addAction(action)
  853. menu.exec_(self.mapToGlobal(event.pos()))
  854. """ Find text in the search results
  855. Shortcuts:
  856. - 'Return' find text.
  857. - 'Shift+Return' find previous text.
  858. """
  859. class ResultSearcher(QWidget):
  860. closeRequest = pyqtSignal()
  861. def __init__(self, resultsContainer, parent):
  862. QWidget.__init__(self, parent)
  863. self.__resultsContainer = resultsContainer
  864. layout = QHBoxLayout(self)
  865. self.__inputEdit = QLineEdit(self)
  866. self.__inputEdit.setPlaceholderText(_("Find .."))
  867. self.__inputEdit.installEventFilter(self)
  868. self.__caseCheckbox = QCheckBox(_("Case sensitive"), self)
  869. self.__wholeCheckbox = QCheckBox(_("Whole words"), self)
  870. nextButton = Button("►", self)
  871. prevButton = Button("◄", self)
  872. closeButton = Button("X", self)
  873. layout.addWidget(self.__inputEdit)
  874. layout.addWidget(prevButton)
  875. layout.addWidget(nextButton)
  876. layout.addWidget(self.__caseCheckbox)
  877. layout.addWidget(self.__wholeCheckbox)
  878. layout.addWidget(closeButton)
  879. closeButton.clicked.connect(self.closeRequest)
  880. nextButton.clicked.connect(self.__search)
  881. prevButton.clicked.connect(self.__searchPrev)
  882. def eventFilter(self, source, event):
  883. if event.type() == QEvent.KeyPress and source is self.__inputEdit:
  884. if event.key() == Qt.Key_Return and event.modifiers() == Qt.ShiftModifier:
  885. self.__search(reverse=True)
  886. elif event.key() == Qt.Key_Return:
  887. self.__search()
  888. elif event.key() == Qt.Key_Escape:
  889. self.closeRequest.emit()
  890. return QLineEdit.eventFilter(self, source, event)
  891. def focusInput(self):
  892. self.__inputEdit.setFocus()
  893. def __searchPrev(self):
  894. self.__search(reverse=True)
  895. def __search(self, reverse=False):
  896. text = self.__inputEdit.text()
  897. flags = QTextDocument.FindFlag(0)
  898. if reverse:
  899. flags |= QTextDocument.FindBackward
  900. if self.__caseCheckbox.isChecked():
  901. flags |= QTextDocument.FindCaseSensitively
  902. if self.__wholeCheckbox.isChecked():
  903. flags |= QTextDocument.FindWholeWords
  904. self.__resultsContainer.find(text, options=flags)
  905. class SearchContainer(QWidget):
  906. def __init__(self, searchModel, instancesModel,
  907. instanceSelecter, enginesModel, guard, parent=None):
  908. """
  909. @type searchModel: models.search.SearchModel
  910. @type instancesModel: models.instances.InstancesModelFilter
  911. @type instanceSelecter: models.instances.InstanceSelecterModel
  912. @type enginesModel: models.instances.EnginesModel
  913. @type guard: core.guard.Guard
  914. """
  915. QWidget.__init__(self, parent=parent)
  916. layout = QVBoxLayout(self)
  917. self._model = searchModel
  918. self._instancesModel = instancesModel
  919. self._instanceSelecter = instanceSelecter
  920. self._guard = guard
  921. self._searchThread = None
  922. # Maximum other instances to try on fail.
  923. self._maxSearchFailCount = 10
  924. # Set `_useFallback` to True to try another instance when the
  925. # search failed somehow or set to False to try same instance or
  926. # for pagination which also should use the same instance.
  927. self._useFallback = True
  928. # `_fallbackActive` should be False when a fresh list of fallback
  929. # instances should be picked on failed search and should be True
  930. # when search(es) fail and `_fallbackInstancesQueue` is beeing
  931. # used.
  932. self._fallbackActive = False
  933. # Used to store errors when fallback is active so they can be listed
  934. # to the user when even the fallback fails.
  935. self._fallbackErrors = []
  936. # Every first request that has `_useFallback` set to True will
  937. # use this list as a resource for next instance(s) to try until
  938. # it is out of instance url's. Also on the first request this
  939. # list will be cleared and filled again with `_maxSearchFailCount`
  940. # of random instances.
  941. self._fallbackInstancesQueue = []
  942. # Set to True to break out of the fallback loop.
  943. # This is used for the Stop action.
  944. self._breakFallback = False
  945. searchLayout = QHBoxLayout()
  946. layout.addLayout(searchLayout)
  947. # -- Start search bar
  948. self.queryEdit = QLineEdit(self)
  949. self.queryEdit.setPlaceholderText(_("Search for .."))
  950. searchLayout.addWidget(self.queryEdit)
  951. self.searchButton = Button(_("Searx"), self)
  952. self.searchButton.setToolTip(_("Preform search."))
  953. searchLayout.addWidget(self.searchButton)
  954. self.reloadButton = Button("♻", self)
  955. self.reloadButton.setToolTip(_("Reload"))
  956. searchLayout.addWidget(self.reloadButton)
  957. self.randomButton = Button("⤳", self)
  958. self.randomButton.setToolTip(_(
  959. "Search with random instance.\n"
  960. "(Obsolete when 'Random Every is checked')"
  961. ))
  962. searchLayout.addWidget(self.randomButton)
  963. rightLayout = QVBoxLayout()
  964. rightLayout.setSpacing(0)
  965. searchLayout.addLayout(rightLayout)
  966. self._fallbackCheck = QCheckBox(_("Fallback"), self)
  967. self._fallbackCheck.setToolTip(_("Try random other instance on fail."))
  968. rightLayout.addWidget(self._fallbackCheck)
  969. self._randomCheckEvery = QCheckBox(_("Random every"), self)
  970. self._randomCheckEvery.setToolTip(_("Pick a random instance for "
  971. "every request."))
  972. rightLayout.addWidget(self._randomCheckEvery)
  973. # -- End search bar
  974. # -- Start splitter
  975. self.splitter = QSplitter(self)
  976. self.splitter.setOrientation(Qt.Vertical)
  977. layout.addWidget(self.splitter)
  978. # ---- Start search options toolbar
  979. self._optionsContainer = SearchOptionsContainer(
  980. searchModel, instancesModel, enginesModel, self.splitter
  981. )
  982. # ---- End search options toolbar
  983. # --- Start search results container
  984. searchBottomWidget = QWidget(self.splitter)
  985. self.searchBottomWidgetLayout = QVBoxLayout(searchBottomWidget)
  986. self.resultsContainer = QTextBrowser(self)
  987. self.resultsContainer.setOpenLinks(False)
  988. self.resultsContainer.setOpenExternalLinks(False)
  989. self.resultsContainer.setLineWrapMode(1)
  990. self.searchBottomWidgetLayout.addWidget(self.resultsContainer)
  991. self.navBar = SearchNavigation(self)
  992. self.navBar.setEnabled(False)
  993. self.searchBottomWidgetLayout.addWidget(self.navBar)
  994. # --- End search results container
  995. # -- End splitter
  996. # Find text
  997. self.__findShortcut = QShortcut('Ctrl+F', self);
  998. self.__findShortcut.activated.connect(self.__openFind);
  999. self.__resultsSearcher = None
  1000. self.queryEdit.textChanged.connect(self.__queryChanged)
  1001. self._model.statusChanged.connect(self.__searchStatusChanged)
  1002. self._model.optionsChanged.connect(self.__searchOptionsChanged)
  1003. self._fallbackCheck.stateChanged.connect(self.__useFallbackChanged)
  1004. self._randomCheckEvery.stateChanged.connect(
  1005. self.__randomEveryRequestChanged)
  1006. self._instanceSelecter.instanceChanged.connect(
  1007. self.__instanceChanged)
  1008. self.queryEdit.returnPressed.connect(self.__searchButtonClicked)
  1009. self.searchButton.clicked.connect(self.__searchButtonClicked)
  1010. self.reloadButton.clicked.connect(self.__reloadButtonClicked)
  1011. self.randomButton.clicked.connect(self.__randomSearchButtonClicked)
  1012. self.navBar.requestPage.connect(self.__navBarRequest)
  1013. self.resultsContainer.anchorClicked.connect(self.__handleAnchorClicked)
  1014. self.__queryChanged("")
  1015. def isBusy(self):
  1016. return bool(self._searchThread is not None)
  1017. def cancelAll(self):
  1018. self._breakFallback = True
  1019. self._searchThread.wait()
  1020. def reset(self):
  1021. self._model.reset()
  1022. self.resultsContainer.setHtml("")
  1023. self.resultsContainer.clearHistory()
  1024. def __openFind(self):
  1025. if self.__resultsSearcher is None:
  1026. self.__resultsSearcher = ResultSearcher(self.resultsContainer, self)
  1027. self.searchBottomWidgetLayout.insertWidget(1, self.__resultsSearcher)
  1028. self.__resultsSearcher.closeRequest.connect(self.__closeFind)
  1029. self.__resultsSearcher.focusInput()
  1030. def __closeFind(self):
  1031. self.searchBottomWidgetLayout.removeWidget(self.__resultsSearcher)
  1032. self.__resultsSearcher.deleteLater()
  1033. self.__resultsSearcher = None
  1034. def __handleAnchorClicked(self, url):
  1035. scheme = url.scheme()
  1036. # Internal from sugestions/corrections
  1037. if scheme == 'search':
  1038. self.queryEdit.setText(url.path())
  1039. self._newSearch(self._instanceSelecter.currentUrl)
  1040. return
  1041. # Custom command
  1042. if (AnchorCMD.handle(scheme, url.toString())):
  1043. return # Handled by custom command
  1044. # Let QDesktopServices handle known schemes
  1045. if scheme in ['http', 'https', 'magnet', 'ftp']:
  1046. QDesktopServices.openUrl(url)
  1047. # Unknown schemes are not doing anything .. :-)
  1048. def __searchButtonClicked(self, checked=0):
  1049. # Set to use fallback
  1050. self._useFallback = self._model.useFallback
  1051. if (self._model.randomEvery or
  1052. (self._useFallback and
  1053. not self._instanceSelecter.currentUrl)):
  1054. self._instanceSelecter.randomInstance()
  1055. self._resetPagination()
  1056. self._newSearch(self._instanceSelecter.currentUrl)
  1057. def __stopButtonClicked(self):
  1058. self._breakFallback = True
  1059. self.searchButton.setEnabled(False)
  1060. def __reloadButtonClicked(self):
  1061. self._useFallback = False
  1062. self._newSearch(self._instanceSelecter.currentUrl)
  1063. def __randomSearchButtonClicked(self):
  1064. self._useFallback = self._model.useFallback
  1065. self._instanceSelecter.randomInstance()
  1066. self._newSearch(self._instanceSelecter.currentUrl)
  1067. def __navBarRequest(self, pageNo):
  1068. self._useFallback = False
  1069. self._model.pageno = pageNo
  1070. self._newSearch(self._instanceSelecter.currentUrl)
  1071. def _resetPagination(self):
  1072. self.navBar.reset()
  1073. self._model.pageno = 1
  1074. def __instanceChanged(self):
  1075. self._resetPagination()
  1076. def __searchOptionsChanged(self):
  1077. """ From the model (on load settings)
  1078. """
  1079. self._randomCheckEvery.stateChanged.disconnect(
  1080. self.__randomEveryRequestChanged)
  1081. self._fallbackCheck.stateChanged.disconnect(
  1082. self.__useFallbackChanged)
  1083. self._randomCheckEvery.setChecked(self._model.randomEvery)
  1084. self._fallbackCheck.setChecked(self._model.useFallback)
  1085. self.__handleRandomButtonState()
  1086. self._randomCheckEvery.stateChanged.connect(
  1087. self.__randomEveryRequestChanged)
  1088. self._fallbackCheck.stateChanged.connect(self.__useFallbackChanged)
  1089. def __handleRandomButtonState(self):
  1090. """ Hides or shows the 'Random search button'.
  1091. We don't need the button when the model it's randomEvery is True.
  1092. """
  1093. if self._model.randomEvery:
  1094. self.randomButton.hide()
  1095. else:
  1096. self.randomButton.show()
  1097. def __randomEveryRequestChanged(self, state):
  1098. """ From the checkbox
  1099. """
  1100. self._model.optionsChanged.disconnect(self.__searchOptionsChanged)
  1101. self._model.randomEvery = bool(state)
  1102. self.__handleRandomButtonState()
  1103. self._model.optionsChanged.connect(self.__searchOptionsChanged)
  1104. def __useFallbackChanged(self, state):
  1105. """ From the checkbox
  1106. """
  1107. self._model.optionsChanged.disconnect(self.__searchOptionsChanged)
  1108. self._model.useFallback = bool(state)
  1109. self._model.optionsChanged.connect(self.__searchOptionsChanged)
  1110. def __queryChanged(self, q):
  1111. if self._model.status() == SearchStatus.Busy:
  1112. return
  1113. if q:
  1114. self.searchButton.setEnabled(True)
  1115. self.reloadButton.setEnabled(True)
  1116. self.randomButton.setEnabled(True)
  1117. else:
  1118. self.searchButton.setEnabled(False)
  1119. self.reloadButton.setEnabled(False)
  1120. self.randomButton.setEnabled(False)
  1121. def _setOptionsState(self, state=True):
  1122. if self._useFallback:
  1123. if state:
  1124. # Search stopped
  1125. self.searchButton.setText(_("Search"))
  1126. self.searchButton.clicked.disconnect(
  1127. self.__stopButtonClicked
  1128. )
  1129. self.searchButton.clicked.connect(self.__searchButtonClicked)
  1130. self.searchButton.setEnabled(True)
  1131. else:
  1132. # Searching
  1133. self.searchButton.setText(_("Stop"))
  1134. self.searchButton.clicked.disconnect(
  1135. self.__searchButtonClicked
  1136. )
  1137. self.searchButton.clicked.connect(self.__stopButtonClicked)
  1138. else:
  1139. self.searchButton.setEnabled(state)
  1140. self.reloadButton.setEnabled(state)
  1141. self.randomButton.setEnabled(state)
  1142. self._randomCheckEvery.setEnabled(state)
  1143. self._fallbackCheck.setEnabled(state)
  1144. self.queryEdit.setEnabled(state)
  1145. self._optionsContainer.setEnabled(state)
  1146. def __searchStatusChanged(self, status):
  1147. if status == SearchStatus.Busy:
  1148. self._setOptionsState(False)
  1149. elif status == SearchStatus.Done:
  1150. self._setOptionsState()
  1151. @property
  1152. def query(self): return self.queryEdit.text()
  1153. def _newSearch(self, url, query=''):
  1154. self.resultsContainer.clear()
  1155. self._search(url, query)
  1156. def _search(self, url, query=''):
  1157. if self._searchThread:
  1158. return
  1159. if not query:
  1160. query = self.query
  1161. if not query:
  1162. self.resultsContainer.setHtml(_("Please enter a search query."))
  1163. return
  1164. if not url:
  1165. self.resultsContainer.setHtml(_("Please select a instance first."))
  1166. return
  1167. self.navBar.setEnabled(False)
  1168. self._model.url = url
  1169. self._model.query = query
  1170. self._searchThread = Thread(
  1171. self._model.search,
  1172. args=[self._model],
  1173. parent=self
  1174. )
  1175. self._searchThread.finished.connect(self._searchFinished)
  1176. self._searchThread.start()
  1177. def _searchFailed(self, result):
  1178. currentUrl = self._instanceSelecter.currentUrl # backup
  1179. # Don't go further on proxy errors.
  1180. # - Guard should not handle proxy errors.
  1181. # - Fallback should be disabled for proxy errors.
  1182. if result.errorType() == ErrorType.ProxyError:
  1183. self._breakFallback = False
  1184. self.resultsContainer.setHtml(
  1185. FailedResponsesHtml.create([result], Themes.htmlCssFail)
  1186. )
  1187. return
  1188. if self._guard.isEnabled():
  1189. # See if the Guard has any consequence for this instance.
  1190. consequence = self._guard.getConsequence(currentUrl)
  1191. if consequence:
  1192. # Apply the consequence.
  1193. if consequence.type == ConsequenceType.Blacklist:
  1194. # Blacklist the instance.
  1195. self._instancesModel.putInstanceOnBlacklist(
  1196. currentUrl,
  1197. reason=result.error()
  1198. )
  1199. else:
  1200. # Put the instance on a timeout.
  1201. self._instancesModel.putInstanceOnTimeout(
  1202. currentUrl,
  1203. duration=consequence.duration,
  1204. reason=result.error()
  1205. )
  1206. self._instancesModel.apply() # Apply the changed filter.
  1207. if self._useFallback: # Re-try another instance
  1208. if self._breakFallback: # Stop button pressed
  1209. self._breakFallback = False
  1210. self._fallbackActive = False
  1211. self._fallbackErrors.append(result)
  1212. self.resultsContainer.setHtml(
  1213. FailedResponsesHtml.create(
  1214. self._fallbackErrors,
  1215. f"{_('Max fail count reached!')} " \
  1216. f"({self._maxSearchFailCount})",
  1217. Themes.htmlCssFail)
  1218. )
  1219. self._fallbackErrors.clear()
  1220. return
  1221. if not self._fallbackActive:
  1222. # Get new list with instances to try same request.
  1223. self._fallbackActive = True
  1224. self._fallbackErrors.clear()
  1225. self._fallbackInstancesQueue.clear()
  1226. self._fallbackInstancesQueue = (
  1227. self._instanceSelecter.getRandomInstances(
  1228. amount=self._maxSearchFailCount))
  1229. if not self._fallbackInstancesQueue:
  1230. self.resultsContainer.setHtml(
  1231. FailedResponsesHtml.create(
  1232. self._fallbackErrors,
  1233. f"{_('Max fail count reached!')} " \
  1234. f"({self._maxSearchFailCount})",
  1235. Themes.htmlCssFail)
  1236. )
  1237. self._fallbackActive = False
  1238. self._fallbackErrors.clear()
  1239. return
  1240. # Append current error to error list
  1241. self._fallbackErrors.append(result)
  1242. # Set next instance url to try.
  1243. self._instanceSelecter.currentUrl = (
  1244. self._fallbackInstancesQueue.pop(0))
  1245. self._search(self._instanceSelecter.currentUrl)
  1246. return
  1247. if self._model.pageno > 1:
  1248. self.navBar.setEnabled(True)
  1249. self.navBar.setNextEnabled(False)
  1250. self.resultsContainer.setHtml(
  1251. FailedResponsesHtml.create([result], _("Search request failed."), Themes.htmlCssFail)
  1252. )
  1253. def _searchFinished(self):
  1254. result = self._searchThread.result()
  1255. self._clearSearchThread()
  1256. # Guard
  1257. if self._guard.isEnabled():
  1258. currentUrl = self._instanceSelecter.currentUrl
  1259. # Report the search result to Guard.
  1260. self._guard.reportSearchResult(currentUrl, result)
  1261. if not bool(result): # Failed
  1262. self._searchFailed(result)
  1263. return
  1264. self._fallbackActive = False
  1265. self.resultsContainer.setHtml(
  1266. ResultsHtml.create(result.json(), Themes.htmlCssResults)
  1267. )
  1268. self.navBar.setEnabled(True)
  1269. self.navBar.setNextEnabled(True)
  1270. def _clearSearchThread(self):
  1271. self._searchThread.finished.disconnect(self._searchFinished)
  1272. # Wait before deleting because the `finished` signal is emited
  1273. # from the thread itself, so this method could be called before the
  1274. # thread is actually finished and result in a crash.
  1275. self._searchThread.wait()
  1276. self._searchThread.deleteLater()
  1277. self._searchThread = None
  1278. def saveSettings(self):
  1279. return {
  1280. 'searchOptions': self._optionsContainer.saveSettings(),
  1281. 'splitterState': self.splitter.saveState()
  1282. }
  1283. def loadSettings(self, data):
  1284. self.queryEdit.setText("")
  1285. self._optionsContainer.loadSettings(
  1286. data.get('searchOptions', {})
  1287. )
  1288. self.splitter.restoreState(
  1289. data.get('splitterState', QByteArray())
  1290. )