main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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.customAnchorCmd import AnchorCMD
  68. from searxqt.core.requests import RequestsHandler
  69. from searxqt.core.guard import Guard
  70. from searxqt.translations import _
  71. from searxqt.version import __version__
  72. from searxqt import PROFILES_PATH, SETTINGS_PATH
  73. from searxqt.core import log
  74. class MainWindow(QMainWindow):
  75. def __init__(self, *args, **kwargs):
  76. QMainWindow.__init__(self, *args, **kwargs)
  77. self.setWindowTitle("Searx-Qt")
  78. self._handler = None
  79. self._settingsWindow = None
  80. # Request handler
  81. self._requestHandler = RequestsHandler()
  82. self._settingsModel = SettingsModel(self._requestHandler.settings, self)
  83. # Persistent models
  84. self._persistantInstancesModel = PersistentInstancesModel()
  85. self._persistantEnginesModel = PersistentEnginesModel()
  86. # Profiles
  87. self._profiles = Profiles()
  88. self.instanceFilter = InstanceModelFilter(
  89. self._persistantInstancesModel, self
  90. )
  91. self.instanceSelecter = InstanceSelecterModel(self.instanceFilter)
  92. self._searchModel = SearchModel(self._requestHandler, self)
  93. # Guard
  94. self._guard = Guard()
  95. # -- Menu bar
  96. menubar = QMenuBar(self)
  97. # Menu file
  98. menuFile = QMenu(menubar)
  99. menuFile.setTitle(_("File"))
  100. saveAction = QAction(_("Save"), menuFile)
  101. menuFile.addAction(saveAction)
  102. saveAction.setShortcut('Ctrl+S')
  103. saveAction.triggered.connect(self.saveSettings)
  104. actionExit = QAction(_("Exit"), menuFile)
  105. menuFile.addAction(actionExit)
  106. actionExit.setShortcut('Ctrl+Q')
  107. actionExit.triggered.connect(self.close)
  108. menubar.addAction(menuFile.menuAction())
  109. # Menu settings
  110. settingsAction = QAction(_("Settings"), menubar)
  111. menubar.addAction(settingsAction)
  112. settingsAction.triggered.connect(self._openSettingsWindow)
  113. # Menu profiles
  114. profilesAction = QAction(_("Profiles"), menubar)
  115. menubar.addAction(profilesAction)
  116. profilesAction.triggered.connect(self._openProfileChooser)
  117. # Menu about dialog
  118. aboutAction = QAction(_("About"), menubar)
  119. menubar.addAction(aboutAction)
  120. aboutAction.triggered.connect(self._openAboutDialog)
  121. self.setMenuBar(menubar)
  122. # -- End menu bar
  123. # -- Status bar
  124. self.statusBar = QStatusBar(self)
  125. statusWidget = QWidget(self)
  126. statusLayout = QHBoxLayout(statusWidget)
  127. self._handlerThreadStatusLabel = QLabel(self)
  128. statusLayout.addWidget(self._handlerThreadStatusLabel)
  129. self._statusInstanceLabel = QLabel(self)
  130. statusLayout.addWidget(self._statusInstanceLabel)
  131. self.statusBar.addPermanentWidget(statusWidget)
  132. self.setStatusBar(self.statusBar)
  133. # -- End status bar
  134. centralWidget = QWidget(self)
  135. layout = QVBoxLayout(centralWidget)
  136. self.setCentralWidget(centralWidget)
  137. self.splitter = QSplitter(centralWidget)
  138. self.splitter.setOrientation(Qt.Horizontal)
  139. layout.addWidget(self.splitter)
  140. self.searchContainer = SearchContainer(
  141. self._searchModel,
  142. self.instanceFilter,
  143. self.instanceSelecter,
  144. self._persistantEnginesModel,
  145. self._guard,
  146. self.splitter
  147. )
  148. self.instancesWidget = InstancesView(
  149. self.instanceFilter,
  150. self.instanceSelecter,
  151. self.splitter
  152. )
  153. self.instanceSelecter.instanceChanged.connect(self.__instanceChanged)
  154. self._searchModel.statusChanged.connect(self.__searchStatusChanged)
  155. self.__profileChooserInit()
  156. self.resize(800, 600)
  157. self.loadSharedSettings()
  158. self.loadProfile()
  159. def __instanceChanged(self, url):
  160. self._statusInstanceLabel.setText(f"<b>{_('Instance')}:</b> {url}")
  161. # Disable/enable instances view on search status change.
  162. def __searchStatusChanged(self, status):
  163. if status == SearchStatus.Busy:
  164. self.instancesWidget.setEnabled(False)
  165. else:
  166. self.instancesWidget.setEnabled(True)
  167. def closeEvent(self, event=None):
  168. # Disable everything.
  169. self.setEnabled(False)
  170. # Wait till all threads finished
  171. if self.searchContainer.isBusy():
  172. log.info("- Waiting for search thread to finish...", self)
  173. self.searchContainer.cancelAll()
  174. log.info("- Search thread finished.")
  175. if self._handler and self._handler.hasActiveJobs():
  176. log.info(
  177. "- Waiting for update instances thread to finish...",
  178. self
  179. )
  180. self._handler.cancelAll()
  181. log.info("- Instances update thread finished.", self)
  182. self.saveSettings()
  183. log.info("- Settings saved.", self)
  184. # Remove currently active profile id from the active list.
  185. self._profiles.setProfile(
  186. self._profiles.settings(),
  187. ProfileItem()
  188. )
  189. QApplication.closeAllWindows()
  190. log.info("Bye!", self)
  191. def _openAboutDialog(self):
  192. about.show(self)
  193. def __execProfileChooser(self):
  194. """ This only sets the profile, it does not load it.
  195. Returns True on success, False when something went wrong.
  196. """
  197. profiles = self._profiles
  198. profilesSettings = profiles.settings()
  199. profiles.loadProfiles(profilesSettings) # read profiles.conf
  200. dialog = ProfileChooserDialog(profiles)
  201. if dialog.exec():
  202. currentProfile = profiles.current()
  203. selectedProfile = dialog.selectedProfile()
  204. # Save current profile if one is set.
  205. if currentProfile.id:
  206. self.saveProfile()
  207. profiles.setProfile(
  208. profilesSettings,
  209. selectedProfile
  210. )
  211. else:
  212. self.__finalizeProfileChooser(dialog)
  213. return False
  214. self.__finalizeProfileChooser(dialog)
  215. return True
  216. def __profileChooserInit(self):
  217. profiles = self._profiles
  218. profilesSettings = profiles.settings()
  219. profiles.loadProfiles(profilesSettings) # read profiles.conf
  220. activeProfiles = profiles.getActiveProfiles(profilesSettings)
  221. defaultProfile = profiles.default()
  222. if defaultProfile is None or defaultProfile.id in activeProfiles:
  223. if not self.__execProfileChooser():
  224. sys.exit()
  225. else:
  226. # Load default profile.
  227. profiles.setProfile(
  228. profilesSettings,
  229. defaultProfile
  230. )
  231. def _openProfileChooser(self):
  232. if self._handler and self._handler.hasActiveJobs():
  233. QMessageBox.information(
  234. self,
  235. _("Instances update thread active"),
  236. _("Please wait until instances finished updating before\n"
  237. "switching profiles.")
  238. )
  239. return
  240. if self.__execProfileChooser():
  241. self.loadProfile()
  242. def __finalizeProfileChooser(self, dialog):
  243. """ Profiles may have been added or removed.
  244. - Store profiles.conf
  245. - Remove removed profile conf files
  246. """
  247. self._profiles.saveProfiles()
  248. self._profiles.removeProfileFiles(dialog.removedProfiles())
  249. def _openSettingsWindow(self):
  250. if not self._settingsWindow:
  251. self._settingsWindow = SettingsWindow(
  252. self._settingsModel,
  253. self._searchModel,
  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.searchContainer.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. # Custom Anchor commands
  335. AnchorCMD.deserialize(
  336. profileSettings.value('customAnchorCmd', dict(), dict)
  337. )
  338. # Load defaults for new profiles.
  339. if profile.preset:
  340. from searxqt import defaults
  341. preset = defaults.Presets[profile.preset]
  342. # Settings
  343. if profile.type == InstancesModelTypes.Stats2:
  344. self._settingsModel.loadSettings(
  345. deepcopy(preset.get('settings', {})),
  346. stats2=True
  347. )
  348. elif profile.type == InstancesModelTypes.User:
  349. self._settingsModel.loadSettings(
  350. deepcopy(preset.get('settings', {})),
  351. stats2=False
  352. )
  353. # Guard
  354. self._guard.deserialize(
  355. deepcopy(preset.get('guard', {}))
  356. )
  357. # InstancesView
  358. self.instancesWidget.loadSettings(
  359. deepcopy(preset.get('instancesView', {}))
  360. )
  361. # InstancesFilter
  362. self.instanceFilter.loadSettings(
  363. deepcopy(preset.get('instancesFilter', {}))
  364. )
  365. # Instances
  366. self._handler.setData(
  367. deepcopy(preset.get('data', {}))
  368. )
  369. del preset
  370. del defaults
  371. def saveProfile(self):
  372. """ Save current profile
  373. """
  374. profile = self._profiles.current()
  375. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  376. profileSettings.setValue(
  377. 'settings', self._settingsModel.saveSettings()
  378. )
  379. profileSettings.setValue(
  380. 'instanceFilter', self.instanceFilter.saveSettings()
  381. )
  382. profileSettings.setValue(
  383. 'instancesView', self.instancesWidget.saveSettings()
  384. )
  385. profileSettings.setValue(
  386. 'instanceSelecter', self.instanceSelecter.saveSettings()
  387. )
  388. profileSettings.setValue(
  389. 'searchContainer', self.searchContainer.saveSettings()
  390. )
  391. profileSettings.setValue(
  392. 'searchModel', self._searchModel.saveSettings()
  393. )
  394. # Guard
  395. profileSettings.setValue('Guard', self._guard.serialize())
  396. # Store the main window splitter state (between search and instances)
  397. profileSettings.setValue('splitterState', self.splitter.saveState())
  398. # Custom Anchor commands
  399. profileSettings.setValue('customAnchorCmd', AnchorCMD.serialize())
  400. # Store searx-qt version (for backward compatibility)
  401. profileSettings.setValue('version', __version__)
  402. if self._handler:
  403. profileSettings.setValue('data', self._handler.data())
  404. def loadSharedSettings(self):
  405. """ Load shared settings
  406. """
  407. settings = QSettings(SETTINGS_PATH, 'shared', self)
  408. self.resize(
  409. settings.value('windowSize', QSize(), QSize)
  410. )
  411. self.__lastSettingsWindowSize = settings.value(
  412. 'settingsWindowSize',
  413. QSize(400, 400),
  414. QSize
  415. )
  416. def saveSettings(self):
  417. # save current profile
  418. if self._profiles.current().id:
  419. self.saveProfile()
  420. # shared.conf
  421. settings = QSettings(SETTINGS_PATH, 'shared', self)
  422. settings.setValue('windowSize', self.size())
  423. if self._settingsWindow:
  424. settings.setValue(
  425. 'settingsWindowSize',
  426. self._settingsWindow.size()
  427. )