Menu

[8f66b6]: / SearchPage.py  Maximize  Restore  History

Download this file

586 lines (508 with data), 28.2 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# -*- coding: utf-8 -*-
"""
Copyright (C) 2011 Oliver Tengler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
from typing import List, Tuple, Optional, cast
from enum import IntEnum
from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal, QPoint, QUrl, QModelIndex, QSettings
from PyQt5.QtGui import QFont, QDesktopServices, QShowEvent, QFocusEvent
from PyQt5.QtWidgets import QFrame, QWidget, QApplication, QMenu, QMessageBox, QFileDialog, QHBoxLayout, QSpacerItem, QSizePolicy
from tools import AsynchronousTask
from dialogs.UserHintDialog import showUserHint, ButtonType
from dialogs.RegExTesterDlg import RegExTesterDlg
from dialogs import StackTraceMessageBox
import PathVisualizerDelegate
from fulltextindex import FullTextIndex
from fulltextindex import Query
from fulltextindex.IndexConfiguration import IndexConfiguration, IndexMode
import SearchAsync
import CustomContextMenu
import AppConfig
from StringListModel import StringListModel
from Ui_SearchPage import Ui_SearchPage
userHintUseWildcards = """
<p align='justify'>The search matches words exactly as entered. In order to match words with unknown parts use the asterisk as wildcard.
E.g. <b>part*</b> matches also <b>partial</b>. See the help for more information about the search syntax.</p>
"""
userHintContentNotIndexed = """
<p align='justify'>The file content is not indexed. Try indexing the content if the search performance is not good enough.</p>
"""
userHintFileNameNotIndexed = """
<p align='justify'>The file names are not indexed. Try indexing file names if the search performance is not good enough.</p>
"""
def getCustomScriptsFromDisk() -> List[str]:
return [s for s in os.listdir("scripts") if os.path.splitext(s)[1].lower() == ".script"]
SearchParams = Tuple[str, str, str, bool]
class SearchType(IntEnum):
SearchContent = 1
SearchName = 2
class SearchPage (QWidget):
# Triggered when a new search tab is requested which should be opened using a given search string
# First parameter is the search string, the second the display name of the search configuration (IndexConfiguration)
newSearchRequested = pyqtSignal(str, str)
# Triggered when a search has finished
searchFinished = pyqtSignal(QWidget, str)
# Triggered whenever the view becomes visible and whenever the current file changes
documentShown = pyqtSignal(str)
def __init__ (self, parent: QWidget) -> None:
super ().__init__(parent)
self.ui = Ui_SearchPage()
self.ui.setupUi(self)
self.ui.frameSearch.setProperty("shadeBackground", True) # fill background with gradient as defined in style sheet
self.ui.frameResult.setProperty("shadeBackground", True) # fill background with gradient as defined in style sheet
self.ui.listView.setItemDelegate(PathVisualizerDelegate.PathVisualizerDelegate(self.ui.listView))
self.ui.listView.activated.connect(self.fileSelected)
self.ui.listView.doubleClicked.connect(self.openFileWithSystem)
self.ui.listView.customContextMenuRequested.connect(self.contextMenuRequested)
self.ui.listView.clicked.connect(self.fileSelected)
self.ui.comboSearch.lineEdit().returnPressed.connect(self.performSearch)
self.ui.comboFolderFilter.lineEdit().returnPressed.connect(self.performSearch)
self.ui.comboExtensionFilter.lineEdit().returnPressed.connect(self.performSearch)
self.ui.sourceViewer.selectionFinishedWithKeyboardModifier.connect(self.newSearchBasedOnSelection)
self.ui.sourceViewer.noPreviousMatch.connect(self.previousFile)
self.ui.sourceViewer.noNextMatch.connect(self.nextFile)
self.ui.matchesOverview.selectionFinishedWithKeyboardModifier.connect(self.newSearchBasedOnSelection)
self.ui.buttonRegEx.clicked.connect(self.showRegExTester)
self.ui.comboLocation.currentIndexChanged[str].connect(self.currentLocationChanged) # pylint: disable=unsubscriptable-object
self.ui.buttonSwitchView.clicked.connect(self.switchView)
self.ui.buttonSearch.clicked.connect(self.performSearch)
self.ui.buttonLockResultSet.clicked.connect(self.lockResultSet)
self.ui.buttonInfo.clicked.connect(self.performanceInfo)
self.ui.buttonExport.clicked.connect(self.exportMatches)
self.ui.buttonCustomScripts.clicked.connect(self.execCustomScripts)
self.ui.buttonChangeSearchType.clicked.connect(self.changeSearchTypeMenu)
self.ui.splitter.setSizes((1, 2)) # distribute splitter space 1:2
self.perfReport: Optional[FullTextIndex.PerformanceReport] = None
self.searchType: SearchType = SearchType.SearchContent
self.searchLocationList: List[IndexConfiguration] = []
self.currentConfigName = self.__chooseInitialLocation ()
self.unavailableConfigName: str = ""
self.commonKeywordMap = self.__loadCommonKeywordMap()
self.matches: FullTextIndex.SearchResult = []
self.sourceFont: QFont = None
self.lockedResultSet: Optional[FullTextIndex.SearchResult] = None # matches are filtered with this set
# Hide the custom scripts button if there are no custom scripts on disk
if not getCustomScriptsFromDisk():
self.ui.buttonCustomScripts.hide()
# Hide the performance info button if showPerformanceButton is false
if not AppConfig.appConfig().showPerformanceButton:
self.ui.buttonInfo.hide()
# Move some elements of the search bar to a second row if the screen width is too small. This avoid
# clipping errors if the widget has to paint below minimum size.
screenGeometry = QApplication.desktop().screenGeometry()
if screenGeometry.width() < 1200:
self.__layoutForLowScreenWidth()
def showEvent(self, _: QShowEvent) -> None:
self.documentShown.emit(self.ui.sourceViewer.currentFile)
@pyqtSlot()
def changeSearchTypeMenu(self) -> None:
self.ui.buttonChangeSearchType.setChecked(True)
menu = QMenu()
menu.setMinimumWidth(self.ui.buttonChangeSearchType.x() + self.ui.buttonChangeSearchType.width() - self.ui.buttonSearch.x())
actions = []
actions.append(menu.addAction("Find content", lambda: self.setSearchType(SearchType.SearchContent)))
actions.append(menu.addAction("Find name", lambda: self.setSearchType(SearchType.SearchName)))
pos = self.mapToGlobal(self.ui.widgetSearch.pos())
pos += QPoint(0, self.ui.buttonSearch.height())
menu.exec(pos)
self.ui.buttonChangeSearchType.setChecked(False)
def setSearchType(self, searchType: SearchType) -> None:
if self.searchType == searchType:
return
self.searchType = searchType
self.ui.buttonCustomScripts.setEnabled(self.searchType == SearchType.SearchContent)
self.ui.buttonSwitchView.setEnabled(self.searchType == SearchType.SearchContent)
if self.searchType == SearchType.SearchName:
self.switchView(False)
self.ui.buttonSwitchView.setChecked(False)
self.ui.buttonSearch.setText("Find name")
else:
self.ui.buttonSearch.setText("Find content")
# Return the display name of the initial config. This is either the configured default location or if there is no default location
# the last used location.
def __chooseInitialLocation (self) -> str:
configName = cast(str,AppConfig.appConfig().defaultLocation) # Display name of current config
if not configName:
configName = cast(str,AppConfig.lastUsedConfigName())
return configName
def __loadCommonKeywordMap(self) -> FullTextIndex.CommonKeywordMap:
try:
return FullTextIndex.buildMapFromCommonKeywordFile (AppConfig.appConfig().commonKeywords)
except:
return {}
def focusInEvent (self, _: QFocusEvent) -> None:
self.ui.comboSearch.setFocus(Qt.ActiveWindowFocusReason)
@pyqtSlot(bool)
def switchView(self, bChecked: bool) -> None:
if bChecked:
self.ui.stackedWidget.setCurrentIndex(1)
self.ui.matchesOverview.activate()
else:
self.ui.stackedWidget.setCurrentIndex(0)
def __updateSourceFont (self) -> QFont:
if not self.sourceFont:
self.sourceFont = QFont()
config = AppConfig.appConfig().SourceViewer
# Apply font and tab changes (if any)
if self.sourceFont.family().lower() != config.FontFamily.lower() or self.sourceFont.pointSize() != config.FontSize:
self.sourceFont.setFamily(config.FontFamily)
self.sourceFont.setPointSize(config.FontSize)
return self.sourceFont
@pyqtSlot(list)
def reloadConfig (self, searchLocationList: List[IndexConfiguration]) -> None:
# updateSearchLocationList rebuilds the list which modifies self.currentConfigName so the current config must be preserved
backupCurrentConfigName = self.currentConfigName
self.__updateSearchLocationList (searchLocationList)
if self.unavailableConfigName and self.setCurrentSearchLocation (self.unavailableConfigName):
# Successfully switched backed to previous config
self.unavailableConfigName = ""
elif not self.setCurrentSearchLocation (backupCurrentConfigName):
# The config is no longer available. This happens most probably during an index update. If the config becomes available later
# we can switch back to it.
self.unavailableConfigName = backupCurrentConfigName
self.ui.sourceViewer.reloadConfig(self.__updateSourceFont())
self.ui.matchesOverview.reloadConfig(self.__updateSourceFont())
def __updateSearchLocationList(self, searchLocationList: List[IndexConfiguration]) -> None:
self.searchLocationList = searchLocationList
self.ui.comboLocation.clear()
if len(self.searchLocationList) <=1:
self.ui.comboLocation.hide()
self.ui.labelLocation.hide()
else:
self.ui.comboLocation.show()
self.ui.labelLocation.show()
for config in self.searchLocationList:
self.ui.comboLocation.addItem(config.displayName(), config)
def setCurrentSearchLocation(self, searchLocationName: str) -> bool:
foundLocation = False
configName = ""
for i, config in enumerate (self.searchLocationList):
if searchLocationName == config.displayName():
self.ui.comboLocation.setCurrentIndex(i)
foundLocation=True
configName=searchLocationName
# Nothing found, select first one or nothing if the list is empty
if not foundLocation:
if self.searchLocationList:
self.ui.comboLocation.setCurrentIndex (0)
configName = self.searchLocationList[0].displayName()
else:
self.ui.comboLocation.setCurrentIndex(-1)
configName = ""
self.currentConfigName = configName
self.__restoreSearchTerms()
return foundLocation
@pyqtSlot(str)
def currentLocationChanged(self, currentConfigName: str) -> None:
self.currentConfigName = currentConfigName
self.__restoreSearchTerms()
@pyqtSlot(QModelIndex)
def fileSelected (self, index: QModelIndex) -> None:
model = self.ui.listView.model()
if model.getSelectedFileIndex() != -1:
model.setEditorState(model.getSelectedFileIndex(), self.ui.sourceViewer.saveEditorState())
model.setSelectedFileIndex (index.row())
name = index.data(Qt.UserRole)
self.showFile (name)
self.ui.matchesOverview.scrollToFile(index.row())
editorState = self.ui.listView.model().getEditorState(index.row())
if editorState:
self.ui.sourceViewer.restoreEditorState(editorState)
def showFile (self, name: str) -> None:
if self.ui.sourceViewer.currentFile != name:
self.ui.sourceViewer.showFile(name)
self.documentShown.emit(name)
@pyqtSlot()
def nextFile (self) -> None:
self.__changeSelectedFile (1)
@pyqtSlot()
def previousFile (self) -> None:
self.__changeSelectedFile (-1)
def __changeSelectedFile (self, increment: int) -> None:
index = self.ui.listView.currentIndex()
if index.isValid():
nextIndex = self.ui.listView.model().index(index.row()+increment, 0)
if nextIndex.isValid():
self.ui.listView.setCurrentIndex(nextIndex)
self.ui.listView.activated.emit(nextIndex)
@pyqtSlot(str, int)
def newSearchBasedOnSelection (self, text: str, modifiers: int) -> None:
if modifiers & Qt.ControlModifier:
if modifiers & Qt.ShiftModifier:
# Search in the same search page
self.searchForText(text)
else:
# Search in a new tab
self.newSearchRequested.emit(text, self.ui.comboLocation.currentText())
def getSearchParameterFromUI (self) -> SearchParams:
strSearch = self.ui.comboSearch.currentText().strip()
strFolderFilter = self.ui.comboFolderFilter.currentText().strip()
strExtensionFilter = self.ui.comboExtensionFilter.currentText().strip()
bCaseSensitive = self.ui.checkCaseSensitive.checkState() == Qt.Checked
return (strSearch, strFolderFilter, strExtensionFilter, bCaseSensitive)
def __currentIndexConf(self) -> IndexConfiguration:
i = self.ui.comboLocation.currentIndex()
config: IndexConfiguration = self.ui.comboLocation.model().index(i, 0).data(Qt.UserRole)
return config
# Returns the search parameters from the UI and the current search configuration (IndexConfiguration) object
def __prepareSearch (self) -> Tuple[SearchParams, IndexConfiguration]:
self.__updateSearchResult(SearchAsync.ResultSet()) # clear current results
indexConf = self.__currentIndexConf()
params = self.getSearchParameterFromUI()
return (params, indexConf)
@pyqtSlot()
def execCustomScripts (self) -> None:
scripts = getCustomScriptsFromDisk()
menu = QMenu()
actions = []
for script in scripts:
actions.append(menu.addAction(os.path.splitext(script)[0]))
pos = self.mapToGlobal(self.ui.buttonCustomScripts.pos())
pos += QPoint(0, self.ui.buttonCustomScripts.height())
result = menu.exec(pos)
if not result:
return
try:
script = scripts[actions.index(result)]
except ValueError:
return
params, indexConf = self.__prepareSearch ()
if not indexConf:
return
try:
result = SearchAsync.customSearch (self, script, params, indexConf, self.commonKeywordMap)
except:
self.reportCustomSearchFailed ()
else:
self.__updateSearchResult(result)
def searchForText (self, text: str) -> None:
self.ui.comboSearch.setEditText(text)
self.ui.comboSearch.insertItem(0, text)
self.performSearch()
@pyqtSlot()
def performSearch (self) -> None:
params, indexConf = self.__prepareSearch ()
if not indexConf:
return
AppConfig.setLastUsedConfigName(indexConf.displayName())
try:
if self.searchType == SearchType.SearchContent:
result = SearchAsync.searchContent (self, params, indexConf, self.commonKeywordMap)
else:
result = SearchAsync.searchFileName (self, params, indexConf)
except Query.QueryError as error:
self.reportQueryError(error)
except:
self.reportFailedSearch(indexConf)
else:
self.__updateSearchResult(result)
self.__rememberSearchTerms()
text = self.tr(userHintUseWildcards)
if self.searchType == SearchType.SearchContent:
showUserHint (self, "useWildcards", self.tr("Try using wildcards"), text, ButtonType.OK)
if indexConf.indexUpdateMode != IndexMode.NoIndexWanted:
if self.searchType == SearchType.SearchContent and not indexConf.isContentIndexed():
text = self.tr(userHintContentNotIndexed)
showUserHint (self, "contentSearchNotIndexed_" + indexConf.displayName(), self.tr("This search can be faster"), text, ButtonType.OK)
if self.searchType == SearchType.SearchName and not indexConf.isFileNameIndexed():
text = self.tr(userHintFileNameNotIndexed)
showUserHint (self, "fileNameSearchNotIndexed_" + indexConf.displayName(), self.tr("This search can be faster"), text, ButtonType.OK)
def __updateSearchResult (self, result: SearchAsync.ResultSet) -> None:
if result.label:
self.searchFinished.emit(self, result.label)
self.perfReport = result.perfReport
# Filter results if we currently have a locked result set
if self.lockedResultSet:
matches = FullTextIndex.intersectSortedLists (self.lockedResultSet, result.matches)
else:
matches = result.matches
self.matches = matches
self.ui.sourceViewer.setSearchData (result.searchData)
self.ui.matchesOverview.setSearchResult(self.matches, result.searchData)
self.ui.labelMatches.setText("%u " % (len(matches), ) + self.tr("matches"))
model = StringListModel(matches)
sizeHint = self.ui.listView.itemDelegate().computeSizeHint(matches, model.cutLeft)
model.setSizeHint(sizeHint)
self.ui.listView.setModel(model)
# Activate first match if enabled in config
if AppConfig.appConfig().activateFirstMatch:
if model.rowCount() > 0:
index = self.ui.listView.model().index(0, 0)
if index.isValid():
self.ui.listView.setCurrentIndex(index)
self.ui.listView.activated.emit(index)
@pyqtSlot(bool)
def lockResultSet (self, bChecked: bool) -> None:
if bChecked:
self.lockedResultSet = self.matches[:] # copy the matches, a reference is not enough
else:
self.lockedResultSet = None
@pyqtSlot(QModelIndex)
def openFileWithSystem(self, index: QModelIndex) -> None:
name = index.data(Qt.UserRole)
url = QUrl.fromLocalFile (name)
QDesktopServices.openUrl (url)
@pyqtSlot()
def performanceInfo (self) -> None:
if not self.perfReport:
return
QMessageBox.information(self, self.tr("Performance info"), str(self.perfReport),
QMessageBox.StandardButtons(QMessageBox.Ok), QMessageBox.Ok)
@pyqtSlot()
def exportMatches(self) -> None:
model = self.ui.listView.model()
if not model or model.rowCount()==0:
return
result = ""
for row in range(model.rowCount()):
index = model.index(row, 0)
if result:
result += os.linesep
result += model.data(index, Qt.UserRole)
exportFile = QFileDialog.getSaveFileName(
self,
self.tr("Export matches"),
self.tr("export.txt"),
self.tr("txt"))[0] # tuple returned, selection and used filter
if not exportFile:
return
with open (exportFile, "w", -1, "utf_8_sig") as output:
output.write(result)
@pyqtSlot(QPoint)
def contextMenuRequested(self, pos: QPoint) -> None:
files = self.__getSelectedFiles()
if not files:
return
fullpath = files[0]
name = os.path.split(fullpath)[1]
menu = QMenu()
menu.addAction(self.tr("Copy &full path"), lambda: self.__copyFullPaths(files))
if len(files)==1:
menu.addAction(self.tr("Copy &path of containing folder"), lambda: self.__copyPathOfContainingFolder(fullpath))
menu.addAction(self.tr("Copy file &name"), lambda: self.__copyFileNames(files))
if len(files)==1:
menu.addAction(self.tr("Open containing f&older"), lambda: self.__browseToFolder(fullpath))
menu.addAction(self.tr("Search for") + " '" + name + "'", lambda: self.__searchForFileName(name))
entries = CustomContextMenu.customMenuEntries (AppConfig.appConfig())
filePairSelected = len(self.__getSelectedFiles()) == 2
for entry in entries:
try:
entry.executionFailed.disconnect() # will raise error if there are no connections
except:
pass
entry.executionFailed.connect (self.reportCustomContextMenuFailed)
if (entry.filePair and filePairSelected) or not entry.filePair:
# The default lambda argument is used to preserve the value of entry for each lambda. Otherwise all lambdas would call the last entry.execute
# See http://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture-in-python
menu.addAction(entry.title, lambda entry=entry: AsynchronousTask.execute (self, entry.execute, self.__getSelectedFiles()))
menu.exec(self.ui.listView.mapToGlobal(pos))
@pyqtSlot()
def showRegExTester(self) -> None:
tester = RegExTesterDlg(self)
tester.setAttribute(Qt.WA_DeleteOnClose)
tester.show()
def __copyFullPaths(self, names: List[str]) -> None:
clipboard = QApplication.clipboard()
clipboard.setText(os.linesep.join(names))
def __copyPathOfContainingFolder(self, name: str) -> None:
clipboard = QApplication.clipboard()
clipboard.setText(os.path.split(name)[0])
def __copyFileNames(self, names: List[str]) -> None:
clipboard = QApplication.clipboard()
text = os.linesep.join(os.path.split(name)[1] for name in names)
clipboard.setText(text)
def __browseToFolder (self, name: str) -> None:
if os.name != "nt":
url = QUrl.fromLocalFile (os.path.split(name)[0])
QDesktopServices.openUrl (url)
else:
import subprocess
subprocess.Popen (["explorer.exe", "/select,", name])
def __searchForFileName (self, name: str) -> None:
self.newSearchRequested.emit(name, self.ui.comboLocation.currentText())
def __getSelectedFiles (self) -> List[str]:
filenames = []
indexes = self.ui.listView.selectedIndexes ()
for index in indexes:
if index.isValid():
filenames.append (index.data(Qt.UserRole))
return filenames
def __layoutForLowScreenWidth (self) -> None:
self.ui.frameSearch2 = QFrame(self) # type: ignore
self.ui.frameSearch2.setProperty("shadeBackground", True) # type: ignore
self.ui.horizontalLayout2 = QHBoxLayout(self.ui.frameSearch2) # type: ignore
self.ui.horizontalLayout2.setContentsMargins(22, 0, 22, -1) # type: ignore
layout = self.ui.horizontalLayout2 # type: ignore
layout.removeWidget(self.ui.labelFolderFilter)
layout.removeWidget(self.ui.comboFolderFilter)
layout.removeWidget(self.ui.labelExtensionFilter)
layout.removeWidget(self.ui.comboExtensionFilter)
layout.removeWidget(self.ui.checkCaseSensitive)
layout.addWidget(self.ui.labelFolderFilter)
layout.addWidget(self.ui.comboFolderFilter)
layout.addWidget(self.ui.labelExtensionFilter)
layout.addWidget(self.ui.comboExtensionFilter)
layout.addWidget(self.ui.checkCaseSensitive)
layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
self.layout().insertWidget(1, self.ui.frameSearch2) # type: ignore
def __restoreSearchTerms(self) -> None:
currentText = self.ui.comboSearch.currentText()
self.ui.comboSearch.clear()
if self.currentConfigName:
settings = QSettings(AppConfig.appCompany, AppConfig.appName)
key = "SearchTerms_"+self.currentConfigName
if settings.value(key):
strList = settings.value(key)
self.ui.comboSearch.addItems(strList)
self.ui.comboSearch.setEditText(currentText)
def __rememberSearchTerms(self) -> None:
model = self.ui.comboSearch.model()
if not model or model.rowCount()==0:
return
terms=[]
for row in range(min(20,model.rowCount())):
index = model.index(row, 0)
terms.append(model.data(index, Qt.DisplayRole))
settings = QSettings(AppConfig.appCompany, AppConfig.appName)
settings.setValue("SearchTerms_"+self.currentConfigName, terms)
@pyqtSlot(CustomContextMenu.ContextMenuError)
def reportCustomContextMenuFailed (self, contextMenuError: CustomContextMenu.ContextMenuError) -> None:
if not contextMenuError.exception:
QMessageBox.warning(self,
self.tr("Custom context menu failed"),
self.tr("Failed to start '") + contextMenuError.program + self.tr("' for:\n") + "\n".join(contextMenuError.failedFiles),
QMessageBox.StandardButtons(QMessageBox.Ok))
else:
QMessageBox.warning(self,
self.tr("Custom context menu failed"),
self.tr("The custom context menu script '") + contextMenuError.program + self.tr("' failed to execute:\n") + contextMenuError.exception,
QMessageBox.StandardButtons(QMessageBox.Ok))
def reportQueryError(self, error: Query.QueryError) -> None:
StackTraceMessageBox.show(self,
self.tr("Search not possible"),
str(error))
def reportFailedSearch(self, indexConf: IndexConfiguration) -> None:
"""Show the user possible reason why the search threw an exception."""
if indexConf.generatesIndex():
StackTraceMessageBox.show(self,
self.tr("Search failed"),
self.tr("""Maybe the index has not been generated yet or is not accessible?"""))
else:
StackTraceMessageBox.show(self,
self.tr("Search failed"),
self.tr("""Please check that the search location exists and is accessible."""))
def reportCustomSearchFailed (self) -> None:
StackTraceMessageBox.show(self,
self.tr("Custom search failed"),
self.tr("Custom search scripts are written in Python. Click on 'Show details' to display the stack trace."))
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.