main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. import sys
  22. from copy import deepcopy
  23. from PyQt5.QtWidgets import (
  24. QApplication,
  25. QAction,
  26. QSplitter,
  27. QMenuBar,
  28. QMenu,
  29. QMainWindow,
  30. QHBoxLayout,
  31. QVBoxLayout,
  32. QWidget,
  33. QStatusBar,
  34. QLabel,
  35. QMessageBox
  36. )
  37. from PyQt5.QtCore import (
  38. Qt,
  39. QSettings,
  40. QByteArray,
  41. QSize
  42. )
  43. from searxqt.models.instances import (
  44. Stats2InstancesModel,
  45. UserInstancesModel,
  46. Stats2EnginesModel,
  47. UserEnginesModel,
  48. Stats2Model,
  49. InstanceModelFilter,
  50. InstanceSelecterModel,
  51. PersistentInstancesModel,
  52. PersistentEnginesModel,
  53. InstancesModelTypes
  54. )
  55. from searxqt.models.settings import SettingsModel
  56. from searxqt.models.search import (
  57. SearchModel,
  58. UserInstancesHandler,
  59. SearchStatus
  60. )
  61. from searxqt.models.profiles import Profiles, ProfileItem
  62. from searxqt.views.instances import InstancesView
  63. from searxqt.views.settings import SettingsWindow
  64. from searxqt.views.search import SearchContainer
  65. from searxqt.views import about
  66. from searxqt.views.profiles import ProfileChooserDialog
  67. from searxqt.core.requests import RequestsHandler
  68. from searxqt.core.guard import Guard
  69. from searxqt.translations import _
  70. from searxqt.version import __version__
  71. from searxqt import PROFILES_PATH, SETTINGS_PATH
  72. from searxqt.core import log
  73. class MainWindow(QMainWindow):
  74. def __init__(self, *args, **kwargs):
  75. QMainWindow.__init__(self, *args, **kwargs)
  76. self.setWindowTitle("Searx-Qt")
  77. self._settingsModel = SettingsModel(self)
  78. self._handler = None
  79. self._settingsWindow = None
  80. # Request handler
  81. self._requestHandler = RequestsHandler(self._settingsModel.requests)
  82. # Persistent models
  83. self._persistantInstancesModel = PersistentInstancesModel()
  84. self._persistantEnginesModel = PersistentEnginesModel()
  85. # Profiles
  86. self._profiles = Profiles()
  87. self.instanceFilter = InstanceModelFilter(
  88. self._persistantInstancesModel, self
  89. )
  90. self.instanceSelecter = InstanceSelecterModel(self.instanceFilter)
  91. self._searchModel = SearchModel(self._requestHandler, self)
  92. # Guard
  93. self._guard = Guard()
  94. # -- Menu bar
  95. menubar = QMenuBar(self)
  96. # Menu file
  97. menuFile = QMenu(menubar)
  98. menuFile.setTitle(_("File"))
  99. saveAction = QAction(_("Save"), menuFile)
  100. menuFile.addAction(saveAction)
  101. saveAction.setShortcut('Ctrl+S')
  102. saveAction.triggered.connect(self.saveSettings)
  103. actionExit = QAction(_("Exit"), menuFile)
  104. menuFile.addAction(actionExit)
  105. actionExit.setShortcut('Ctrl+Q')
  106. actionExit.triggered.connect(self.close)
  107. menubar.addAction(menuFile.menuAction())
  108. # Menu settings
  109. settingsAction = QAction(_("Settings"), menubar)
  110. menubar.addAction(settingsAction)
  111. settingsAction.triggered.connect(self._openSettingsWindow)
  112. # Menu profiles
  113. profilesAction = QAction(_("Profiles"), menubar)
  114. menubar.addAction(profilesAction)
  115. profilesAction.triggered.connect(self._openProfileChooser)
  116. # Menu about dialog
  117. aboutAction = QAction(_("About"), menubar)
  118. menubar.addAction(aboutAction)
  119. aboutAction.triggered.connect(self._openAboutDialog)
  120. self.setMenuBar(menubar)
  121. # -- End menu bar
  122. # -- Status bar
  123. self.statusBar = QStatusBar(self)
  124. statusWidget = QWidget(self)
  125. statusLayout = QHBoxLayout(statusWidget)
  126. self._handlerThreadStatusLabel = QLabel(self)
  127. statusLayout.addWidget(self._handlerThreadStatusLabel)
  128. self._statusInstanceLabel = QLabel(self)
  129. statusLayout.addWidget(self._statusInstanceLabel)
  130. self.statusBar.addPermanentWidget(statusWidget)
  131. self.setStatusBar(self.statusBar)
  132. # -- End status bar
  133. centralWidget = QWidget(self)
  134. layout = QVBoxLayout(centralWidget)
  135. self.setCentralWidget(centralWidget)
  136. self.splitter = QSplitter(centralWidget)
  137. self.splitter.setOrientation(Qt.Horizontal)
  138. layout.addWidget(self.splitter)
  139. self.searchContainer = SearchContainer(
  140. self._searchModel,
  141. self.instanceFilter,
  142. self.instanceSelecter,
  143. self._persistantEnginesModel,
  144. self._guard,
  145. self.splitter
  146. )
  147. self.instancesWidget = InstancesView(
  148. self.instanceFilter,
  149. self.instanceSelecter,
  150. self.splitter
  151. )
  152. self.instanceSelecter.instanceChanged.connect(self.__instanceChanged)
  153. self._searchModel.statusChanged.connect(self.__searchStatusChanged)
  154. self.__profileChooserInit()
  155. self.resize(800, 600)
  156. self.loadSharedSettings()
  157. self.loadProfile()
  158. def __instanceChanged(self, url):
  159. self._statusInstanceLabel.setText(
  160. "<b>{0}:</b> {1}".format(_("Instance"), url)
  161. )
  162. # Disable/enable instances view on search status change.
  163. def __searchStatusChanged(self, status):
  164. if status == SearchStatus.Busy:
  165. self.instancesWidget.setEnabled(False)
  166. else:
  167. self.instancesWidget.setEnabled(True)
  168. def closeEvent(self, event=None):
  169. # Disable everything.
  170. self.setEnabled(False)
  171. # Wait till all threads finished
  172. if self.searchContainer.isBusy():
  173. log.info("- Waiting for search thread to finish...", self)
  174. self.searchContainer.cancelAll()
  175. log.info("- Search thread finished.")
  176. if self._handler and self._handler.hasActiveJobs():
  177. log.info(
  178. "- Waiting for update instances thread to finish...",
  179. self
  180. )
  181. self._handler.cancelAll()
  182. log.info("- Instances update thread finished.", self)
  183. self.saveSettings()
  184. log.info("- Settings saved.", self)
  185. # Remove currently active profile id from the active list.
  186. self._profiles.setProfile(
  187. self._profiles.settings(),
  188. ProfileItem()
  189. )
  190. QApplication.closeAllWindows()
  191. log.info("Bye!", self)
  192. def _openAboutDialog(self):
  193. about.show(self)
  194. def __execProfileChooser(self):
  195. """ This only sets the profile, it does not load it.
  196. Returns True on success, False when something went wrong.
  197. """
  198. profiles = self._profiles
  199. profilesSettings = profiles.settings()
  200. profiles.loadProfiles(profilesSettings) # read profiles.conf
  201. dialog = ProfileChooserDialog(profiles)
  202. if dialog.exec():
  203. currentProfile = profiles.current()
  204. selectedProfile = dialog.selectedProfile()
  205. # Save current profile if one is set.
  206. if currentProfile.id:
  207. self.saveProfile()
  208. profiles.setProfile(
  209. profilesSettings,
  210. selectedProfile
  211. )
  212. else:
  213. self.__finalizeProfileChooser(dialog)
  214. return False
  215. self.__finalizeProfileChooser(dialog)
  216. return True
  217. def __profileChooserInit(self):
  218. profiles = self._profiles
  219. profilesSettings = profiles.settings()
  220. profiles.loadProfiles(profilesSettings) # read profiles.conf
  221. activeProfiles = profiles.getActiveProfiles(profilesSettings)
  222. defaultProfile = profiles.default()
  223. if defaultProfile is None or defaultProfile.id in activeProfiles:
  224. if not self.__execProfileChooser():
  225. sys.exit()
  226. else:
  227. # Load default profile.
  228. profiles.setProfile(
  229. profilesSettings,
  230. defaultProfile
  231. )
  232. def _openProfileChooser(self):
  233. if self._handler and self._handler.hasActiveJobs():
  234. QMessageBox.information(
  235. self,
  236. _("Instances update thread active"),
  237. _("Please wait until instances finished updating before\n"
  238. "switching profiles.")
  239. )
  240. return
  241. if self.__execProfileChooser():
  242. self.loadProfile()
  243. def __finalizeProfileChooser(self, dialog):
  244. """ Profiles may have been added or removed.
  245. - Store profiles.conf
  246. - Remove removed profile conf files
  247. """
  248. self._profiles.saveProfiles()
  249. self._profiles.removeProfileFiles(dialog.removedProfiles())
  250. def _openSettingsWindow(self):
  251. if not self._settingsWindow:
  252. self._settingsWindow = SettingsWindow(
  253. self._settingsModel,
  254. self._guard
  255. )
  256. self._settingsWindow.resize(self.__lastSettingsWindowSize)
  257. self._settingsWindow.show()
  258. self._settingsWindow.activateWindow() # Bring it to front
  259. self._settingsWindow.closed.connect(self._delSettingsWindow)
  260. def _delSettingsWindow(self):
  261. self._settingsWindow.closed.disconnect()
  262. self._settingsWindow.deleteLater()
  263. self._settingsWindow = None
  264. def __handlerThreadChanged(self):
  265. self._handlerThreadStatusLabel.setText(
  266. self._handler.currentJobStr()
  267. )
  268. def loadProfile(self):
  269. profile = self._profiles.current()
  270. self.setWindowTitle(f"Searx-Qt - {profile.name}")
  271. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  272. # Clean previous stuff
  273. if self._handler:
  274. self._handler.threadStarted.disconnect(
  275. self.__handlerThreadChanged
  276. )
  277. self._handler.threadFinished.disconnect(
  278. self.__handlerThreadChanged
  279. )
  280. self._handler.deleteLater()
  281. self._handler = None
  282. if self._settingsWindow:
  283. self._delSettingsWindow()
  284. self._searchModel.reset()
  285. # Set new models
  286. if profile.type == InstancesModelTypes.Stats2:
  287. self._handler = Stats2Model(self._requestHandler, self)
  288. instancesModel = Stats2InstancesModel(self._handler, parent=self)
  289. enginesModel = Stats2EnginesModel(self._handler, parent=self)
  290. self._settingsModel.loadSettings(
  291. profileSettings.value('settings', dict(), dict),
  292. stats2=True
  293. )
  294. elif profile.type == InstancesModelTypes.User:
  295. self._handler = UserInstancesHandler(self._requestHandler, self)
  296. instancesModel = UserInstancesModel(self._handler, parent=self)
  297. enginesModel = UserEnginesModel(self._handler, parent=self)
  298. self._settingsModel.loadSettings(
  299. profileSettings.value('settings', dict(), dict),
  300. stats2=False
  301. )
  302. else:
  303. print(f"ERROR unknown profile type '{profile.type}'")
  304. sys.exit(1)
  305. self._persistantInstancesModel.setModel(instancesModel)
  306. self._persistantEnginesModel.setModel(enginesModel)
  307. self._handler.setData(
  308. profileSettings.value('data', dict(), dict)
  309. )
  310. self._handler.threadStarted.connect(self.__handlerThreadChanged)
  311. self._handler.threadFinished.connect(self.__handlerThreadChanged)
  312. # Load settings
  313. self.instanceFilter.loadSettings(
  314. profileSettings.value('instanceFilter', dict(), dict)
  315. )
  316. self.instancesWidget.loadSettings(
  317. profileSettings.value('instancesView', dict(), dict)
  318. )
  319. self.instanceSelecter.loadSettings(
  320. profileSettings.value('instanceSelecter', dict(), dict)
  321. )
  322. self.searchContainer.loadSettings(
  323. profileSettings.value('searchContainer', dict(), dict)
  324. )
  325. self._searchModel.loadSettings(
  326. profileSettings.value('searchModel', dict(), dict)
  327. )
  328. # Guard
  329. self._guard.deserialize(profileSettings.value('Guard', dict(), dict))
  330. # Load main window splitter state (between search and instances)
  331. self.splitter.restoreState(
  332. profileSettings.value('splitterState', QByteArray(), QByteArray)
  333. )
  334. # Load defaults for new profiles.
  335. if profile.preset:
  336. from searxqt import defaults
  337. preset = defaults.Presets[profile.preset]
  338. # Settings
  339. if profile.type == InstancesModelTypes.Stats2:
  340. self._settingsModel.loadSettings(
  341. deepcopy(preset.get('settings', {})),
  342. stats2=True
  343. )
  344. elif profile.type == InstancesModelTypes.User:
  345. self._settingsModel.loadSettings(
  346. deepcopy(preset.get('settings', {})),
  347. stats2=False
  348. )
  349. # Guard
  350. self._guard.deserialize(
  351. deepcopy(preset.get('guard', {}))
  352. )
  353. # InstancesView
  354. self.instancesWidget.loadSettings(
  355. deepcopy(preset.get('instancesView', {}))
  356. )
  357. # InstancesFilter
  358. self.instanceFilter.loadSettings(
  359. deepcopy(preset.get('instancesFilter', {}))
  360. )
  361. # Instances
  362. self._handler.setData(
  363. deepcopy(preset.get('data', {}))
  364. )
  365. del preset
  366. del defaults
  367. def saveProfile(self):
  368. """ Save current profile
  369. """
  370. profile = self._profiles.current()
  371. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  372. profileSettings.setValue(
  373. 'settings', self._settingsModel.saveSettings()
  374. )
  375. profileSettings.setValue(
  376. 'instanceFilter', self.instanceFilter.saveSettings()
  377. )
  378. profileSettings.setValue(
  379. 'instancesView', self.instancesWidget.saveSettings()
  380. )
  381. profileSettings.setValue(
  382. 'instanceSelecter', self.instanceSelecter.saveSettings()
  383. )
  384. profileSettings.setValue(
  385. 'searchContainer', self.searchContainer.saveSettings()
  386. )
  387. profileSettings.setValue(
  388. 'searchModel', self._searchModel.saveSettings()
  389. )
  390. # Guard
  391. profileSettings.setValue('Guard', self._guard.serialize())
  392. # Store the main window splitter state (between search and instances)
  393. profileSettings.setValue('splitterState', self.splitter.saveState())
  394. # Store searx-qt version (for backward compatibility)
  395. profileSettings.setValue('version', __version__)
  396. if self._handler:
  397. profileSettings.setValue('data', self._handler.data())
  398. def loadSharedSettings(self):
  399. """ Load shared settings
  400. """
  401. settings = QSettings(SETTINGS_PATH, 'shared', self)
  402. self.resize(
  403. settings.value('windowSize', QSize(), QSize)
  404. )
  405. self.__lastSettingsWindowSize = settings.value(
  406. 'settingsWindowSize',
  407. QSize(400, 400),
  408. QSize
  409. )
  410. def saveSettings(self):
  411. # save current profile
  412. if self._profiles.current().id:
  413. self.saveProfile()
  414. # shared.conf
  415. settings = QSettings(SETTINGS_PATH, 'shared', self)
  416. settings.setValue('windowSize', self.size())
  417. if self._settingsWindow:
  418. settings.setValue(
  419. 'settingsWindowSize',
  420. self._settingsWindow.size()
  421. )