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._handler = None
  78. self._settingsWindow = None
  79. # Request handler
  80. self._requestHandler = RequestsHandler()
  81. self._settingsModel = SettingsModel(self._requestHandler.settings, self)
  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(f"<b>{_('Instance')}:</b> {url}")
  160. # Disable/enable instances view on search status change.
  161. def __searchStatusChanged(self, status):
  162. if status == SearchStatus.Busy:
  163. self.instancesWidget.setEnabled(False)
  164. else:
  165. self.instancesWidget.setEnabled(True)
  166. def closeEvent(self, event=None):
  167. # Disable everything.
  168. self.setEnabled(False)
  169. # Wait till all threads finished
  170. if self.searchContainer.isBusy():
  171. log.info("- Waiting for search thread to finish...", self)
  172. self.searchContainer.cancelAll()
  173. log.info("- Search thread finished.")
  174. if self._handler and self._handler.hasActiveJobs():
  175. log.info(
  176. "- Waiting for update instances thread to finish...",
  177. self
  178. )
  179. self._handler.cancelAll()
  180. log.info("- Instances update thread finished.", self)
  181. self.saveSettings()
  182. log.info("- Settings saved.", self)
  183. # Remove currently active profile id from the active list.
  184. self._profiles.setProfile(
  185. self._profiles.settings(),
  186. ProfileItem()
  187. )
  188. QApplication.closeAllWindows()
  189. log.info("Bye!", self)
  190. def _openAboutDialog(self):
  191. about.show(self)
  192. def __execProfileChooser(self):
  193. """ This only sets the profile, it does not load it.
  194. Returns True on success, False when something went wrong.
  195. """
  196. profiles = self._profiles
  197. profilesSettings = profiles.settings()
  198. profiles.loadProfiles(profilesSettings) # read profiles.conf
  199. dialog = ProfileChooserDialog(profiles)
  200. if dialog.exec():
  201. currentProfile = profiles.current()
  202. selectedProfile = dialog.selectedProfile()
  203. # Save current profile if one is set.
  204. if currentProfile.id:
  205. self.saveProfile()
  206. profiles.setProfile(
  207. profilesSettings,
  208. selectedProfile
  209. )
  210. else:
  211. self.__finalizeProfileChooser(dialog)
  212. return False
  213. self.__finalizeProfileChooser(dialog)
  214. return True
  215. def __profileChooserInit(self):
  216. profiles = self._profiles
  217. profilesSettings = profiles.settings()
  218. profiles.loadProfiles(profilesSettings) # read profiles.conf
  219. activeProfiles = profiles.getActiveProfiles(profilesSettings)
  220. defaultProfile = profiles.default()
  221. if defaultProfile is None or defaultProfile.id in activeProfiles:
  222. if not self.__execProfileChooser():
  223. sys.exit()
  224. else:
  225. # Load default profile.
  226. profiles.setProfile(
  227. profilesSettings,
  228. defaultProfile
  229. )
  230. def _openProfileChooser(self):
  231. if self._handler and self._handler.hasActiveJobs():
  232. QMessageBox.information(
  233. self,
  234. _("Instances update thread active"),
  235. _("Please wait until instances finished updating before\n"
  236. "switching profiles.")
  237. )
  238. return
  239. if self.__execProfileChooser():
  240. self.loadProfile()
  241. def __finalizeProfileChooser(self, dialog):
  242. """ Profiles may have been added or removed.
  243. - Store profiles.conf
  244. - Remove removed profile conf files
  245. """
  246. self._profiles.saveProfiles()
  247. self._profiles.removeProfileFiles(dialog.removedProfiles())
  248. def _openSettingsWindow(self):
  249. if not self._settingsWindow:
  250. self._settingsWindow = SettingsWindow(
  251. self._settingsModel,
  252. self._searchModel,
  253. self._guard
  254. )
  255. self._settingsWindow.resize(self.__lastSettingsWindowSize)
  256. self._settingsWindow.show()
  257. self._settingsWindow.activateWindow() # Bring it to front
  258. self._settingsWindow.closed.connect(self._delSettingsWindow)
  259. def _delSettingsWindow(self):
  260. self._settingsWindow.closed.disconnect()
  261. self._settingsWindow.deleteLater()
  262. self._settingsWindow = None
  263. def __handlerThreadChanged(self):
  264. self._handlerThreadStatusLabel.setText(
  265. self._handler.currentJobStr()
  266. )
  267. def loadProfile(self):
  268. profile = self._profiles.current()
  269. self.setWindowTitle(f"Searx-Qt - {profile.name}")
  270. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  271. # Clean previous stuff
  272. if self._handler:
  273. self._handler.threadStarted.disconnect(
  274. self.__handlerThreadChanged
  275. )
  276. self._handler.threadFinished.disconnect(
  277. self.__handlerThreadChanged
  278. )
  279. self._handler.deleteLater()
  280. self._handler = None
  281. if self._settingsWindow:
  282. self._delSettingsWindow()
  283. self.searchContainer.reset()
  284. # Set new models
  285. if profile.type == InstancesModelTypes.Stats2:
  286. self._handler = Stats2Model(self._requestHandler, self)
  287. instancesModel = Stats2InstancesModel(self._handler, parent=self)
  288. enginesModel = Stats2EnginesModel(self._handler, parent=self)
  289. self._settingsModel.loadSettings(
  290. profileSettings.value('settings', dict(), dict),
  291. stats2=True
  292. )
  293. elif profile.type == InstancesModelTypes.User:
  294. self._handler = UserInstancesHandler(self._requestHandler, self)
  295. instancesModel = UserInstancesModel(self._handler, parent=self)
  296. enginesModel = UserEnginesModel(self._handler, parent=self)
  297. self._settingsModel.loadSettings(
  298. profileSettings.value('settings', dict(), dict),
  299. stats2=False
  300. )
  301. else:
  302. print(f"ERROR unknown profile type '{profile.type}'")
  303. sys.exit(1)
  304. self._persistantInstancesModel.setModel(instancesModel)
  305. self._persistantEnginesModel.setModel(enginesModel)
  306. self._handler.setData(
  307. profileSettings.value('data', dict(), dict)
  308. )
  309. self._handler.threadStarted.connect(self.__handlerThreadChanged)
  310. self._handler.threadFinished.connect(self.__handlerThreadChanged)
  311. # Load settings
  312. self.instanceFilter.loadSettings(
  313. profileSettings.value('instanceFilter', dict(), dict)
  314. )
  315. self.instancesWidget.loadSettings(
  316. profileSettings.value('instancesView', dict(), dict)
  317. )
  318. self.instanceSelecter.loadSettings(
  319. profileSettings.value('instanceSelecter', dict(), dict)
  320. )
  321. self.searchContainer.loadSettings(
  322. profileSettings.value('searchContainer', dict(), dict)
  323. )
  324. self._searchModel.loadSettings(
  325. profileSettings.value('searchModel', dict(), dict)
  326. )
  327. # Guard
  328. self._guard.deserialize(profileSettings.value('Guard', dict(), dict))
  329. # Load main window splitter state (between search and instances)
  330. self.splitter.restoreState(
  331. profileSettings.value('splitterState', QByteArray(), QByteArray)
  332. )
  333. # Load defaults for new profiles.
  334. if profile.preset:
  335. from searxqt import defaults
  336. preset = defaults.Presets[profile.preset]
  337. # Settings
  338. if profile.type == InstancesModelTypes.Stats2:
  339. self._settingsModel.loadSettings(
  340. deepcopy(preset.get('settings', {})),
  341. stats2=True
  342. )
  343. elif profile.type == InstancesModelTypes.User:
  344. self._settingsModel.loadSettings(
  345. deepcopy(preset.get('settings', {})),
  346. stats2=False
  347. )
  348. # Guard
  349. self._guard.deserialize(
  350. deepcopy(preset.get('guard', {}))
  351. )
  352. # InstancesView
  353. self.instancesWidget.loadSettings(
  354. deepcopy(preset.get('instancesView', {}))
  355. )
  356. # InstancesFilter
  357. self.instanceFilter.loadSettings(
  358. deepcopy(preset.get('instancesFilter', {}))
  359. )
  360. # Instances
  361. self._handler.setData(
  362. deepcopy(preset.get('data', {}))
  363. )
  364. del preset
  365. del defaults
  366. def saveProfile(self):
  367. """ Save current profile
  368. """
  369. profile = self._profiles.current()
  370. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  371. profileSettings.setValue(
  372. 'settings', self._settingsModel.saveSettings()
  373. )
  374. profileSettings.setValue(
  375. 'instanceFilter', self.instanceFilter.saveSettings()
  376. )
  377. profileSettings.setValue(
  378. 'instancesView', self.instancesWidget.saveSettings()
  379. )
  380. profileSettings.setValue(
  381. 'instanceSelecter', self.instanceSelecter.saveSettings()
  382. )
  383. profileSettings.setValue(
  384. 'searchContainer', self.searchContainer.saveSettings()
  385. )
  386. profileSettings.setValue(
  387. 'searchModel', self._searchModel.saveSettings()
  388. )
  389. # Guard
  390. profileSettings.setValue('Guard', self._guard.serialize())
  391. # Store the main window splitter state (between search and instances)
  392. profileSettings.setValue('splitterState', self.splitter.saveState())
  393. # Store searx-qt version (for backward compatibility)
  394. profileSettings.setValue('version', __version__)
  395. if self._handler:
  396. profileSettings.setValue('data', self._handler.data())
  397. def loadSharedSettings(self):
  398. """ Load shared settings
  399. """
  400. settings = QSettings(SETTINGS_PATH, 'shared', self)
  401. self.resize(
  402. settings.value('windowSize', QSize(), QSize)
  403. )
  404. self.__lastSettingsWindowSize = settings.value(
  405. 'settingsWindowSize',
  406. QSize(400, 400),
  407. QSize
  408. )
  409. def saveSettings(self):
  410. # save current profile
  411. if self._profiles.current().id:
  412. self.saveProfile()
  413. # shared.conf
  414. settings = QSettings(SETTINGS_PATH, 'shared', self)
  415. settings.setValue('windowSize', self.size())
  416. if self._settingsWindow:
  417. settings.setValue(
  418. 'settingsWindowSize',
  419. self._settingsWindow.size()
  420. )