main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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._guard
  253. )
  254. self._settingsWindow.resize(self.__lastSettingsWindowSize)
  255. self._settingsWindow.show()
  256. self._settingsWindow.activateWindow() # Bring it to front
  257. self._settingsWindow.closed.connect(self._delSettingsWindow)
  258. def _delSettingsWindow(self):
  259. self._settingsWindow.closed.disconnect()
  260. self._settingsWindow.deleteLater()
  261. self._settingsWindow = None
  262. def __handlerThreadChanged(self):
  263. self._handlerThreadStatusLabel.setText(
  264. self._handler.currentJobStr()
  265. )
  266. def loadProfile(self):
  267. profile = self._profiles.current()
  268. self.setWindowTitle(f"Searx-Qt - {profile.name}")
  269. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  270. # Clean previous stuff
  271. if self._handler:
  272. self._handler.threadStarted.disconnect(
  273. self.__handlerThreadChanged
  274. )
  275. self._handler.threadFinished.disconnect(
  276. self.__handlerThreadChanged
  277. )
  278. self._handler.deleteLater()
  279. self._handler = None
  280. if self._settingsWindow:
  281. self._delSettingsWindow()
  282. self.searchContainer.reset()
  283. # Set new models
  284. if profile.type == InstancesModelTypes.Stats2:
  285. self._handler = Stats2Model(self._requestHandler, self)
  286. instancesModel = Stats2InstancesModel(self._handler, parent=self)
  287. enginesModel = Stats2EnginesModel(self._handler, parent=self)
  288. self._settingsModel.loadSettings(
  289. profileSettings.value('settings', dict(), dict),
  290. stats2=True
  291. )
  292. elif profile.type == InstancesModelTypes.User:
  293. self._handler = UserInstancesHandler(self._requestHandler, self)
  294. instancesModel = UserInstancesModel(self._handler, parent=self)
  295. enginesModel = UserEnginesModel(self._handler, parent=self)
  296. self._settingsModel.loadSettings(
  297. profileSettings.value('settings', dict(), dict),
  298. stats2=False
  299. )
  300. else:
  301. print(f"ERROR unknown profile type '{profile.type}'")
  302. sys.exit(1)
  303. self._persistantInstancesModel.setModel(instancesModel)
  304. self._persistantEnginesModel.setModel(enginesModel)
  305. self._handler.setData(
  306. profileSettings.value('data', dict(), dict)
  307. )
  308. self._handler.threadStarted.connect(self.__handlerThreadChanged)
  309. self._handler.threadFinished.connect(self.__handlerThreadChanged)
  310. # Load settings
  311. self.instanceFilter.loadSettings(
  312. profileSettings.value('instanceFilter', dict(), dict)
  313. )
  314. self.instancesWidget.loadSettings(
  315. profileSettings.value('instancesView', dict(), dict)
  316. )
  317. self.instanceSelecter.loadSettings(
  318. profileSettings.value('instanceSelecter', dict(), dict)
  319. )
  320. self.searchContainer.loadSettings(
  321. profileSettings.value('searchContainer', dict(), dict)
  322. )
  323. self._searchModel.loadSettings(
  324. profileSettings.value('searchModel', dict(), dict)
  325. )
  326. # Guard
  327. self._guard.deserialize(profileSettings.value('Guard', dict(), dict))
  328. # Load main window splitter state (between search and instances)
  329. self.splitter.restoreState(
  330. profileSettings.value('splitterState', QByteArray(), QByteArray)
  331. )
  332. # Load defaults for new profiles.
  333. if profile.preset:
  334. from searxqt import defaults
  335. preset = defaults.Presets[profile.preset]
  336. # Settings
  337. if profile.type == InstancesModelTypes.Stats2:
  338. self._settingsModel.loadSettings(
  339. deepcopy(preset.get('settings', {})),
  340. stats2=True
  341. )
  342. elif profile.type == InstancesModelTypes.User:
  343. self._settingsModel.loadSettings(
  344. deepcopy(preset.get('settings', {})),
  345. stats2=False
  346. )
  347. # Guard
  348. self._guard.deserialize(
  349. deepcopy(preset.get('guard', {}))
  350. )
  351. # InstancesView
  352. self.instancesWidget.loadSettings(
  353. deepcopy(preset.get('instancesView', {}))
  354. )
  355. # InstancesFilter
  356. self.instanceFilter.loadSettings(
  357. deepcopy(preset.get('instancesFilter', {}))
  358. )
  359. # Instances
  360. self._handler.setData(
  361. deepcopy(preset.get('data', {}))
  362. )
  363. del preset
  364. del defaults
  365. def saveProfile(self):
  366. """ Save current profile
  367. """
  368. profile = self._profiles.current()
  369. profileSettings = QSettings(PROFILES_PATH, profile.id, self)
  370. profileSettings.setValue(
  371. 'settings', self._settingsModel.saveSettings()
  372. )
  373. profileSettings.setValue(
  374. 'instanceFilter', self.instanceFilter.saveSettings()
  375. )
  376. profileSettings.setValue(
  377. 'instancesView', self.instancesWidget.saveSettings()
  378. )
  379. profileSettings.setValue(
  380. 'instanceSelecter', self.instanceSelecter.saveSettings()
  381. )
  382. profileSettings.setValue(
  383. 'searchContainer', self.searchContainer.saveSettings()
  384. )
  385. profileSettings.setValue(
  386. 'searchModel', self._searchModel.saveSettings()
  387. )
  388. # Guard
  389. profileSettings.setValue('Guard', self._guard.serialize())
  390. # Store the main window splitter state (between search and instances)
  391. profileSettings.setValue('splitterState', self.splitter.saveState())
  392. # Store searx-qt version (for backward compatibility)
  393. profileSettings.setValue('version', __version__)
  394. if self._handler:
  395. profileSettings.setValue('data', self._handler.data())
  396. def loadSharedSettings(self):
  397. """ Load shared settings
  398. """
  399. settings = QSettings(SETTINGS_PATH, 'shared', self)
  400. self.resize(
  401. settings.value('windowSize', QSize(), QSize)
  402. )
  403. self.__lastSettingsWindowSize = settings.value(
  404. 'settingsWindowSize',
  405. QSize(400, 400),
  406. QSize
  407. )
  408. def saveSettings(self):
  409. # save current profile
  410. if self._profiles.current().id:
  411. self.saveProfile()
  412. # shared.conf
  413. settings = QSettings(SETTINGS_PATH, 'shared', self)
  414. settings.setValue('windowSize', self.size())
  415. if self._settingsWindow:
  416. settings.setValue(
  417. 'settingsWindowSize',
  418. self._settingsWindow.size()
  419. )