Menu

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

Download this file

312 lines (268 with data), 12.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
# -*- coding: utf-8 -*-
"""
Copyright (C) 2013 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 unittest
import bisect
import re
import threading
from typing import List,Tuple,Optional
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFontMetrics, QFont
from PyQt5.QtWidgets import QWidget
from tools.FileTools import fopen
from tools import AsynchronousTask
from fulltextindex import FullTextIndex
from widgets.SourceHighlightingTextEdit import SourceHighlightingTextEdit
from widgets import RecyclingVerticalScrollArea
from AppConfig import appConfig
import HighlightingRulesCache
from Ui_MatchesOverview import Ui_MatchesOverview
# Accepts a list of touples each containing a start and end index. After calling the function
# consecutive touples which overlapped or adjoin are collapsed into one touple. This is done in place.
# ranges = [(1,3),(2,5),(7,2)]
# Result is [(1,5),(7,2)]
def collapseAdjoiningRanges(ranges: List[Tuple[int,int]]) -> None:
i=0
while i+1 < len(ranges):
r1 = ranges[i]
r2 = ranges[i+1]
if r1[1]+1>=r2[0]:
rn = (r1[0],r2[1])
del ranges[i]
del ranges[i]
ranges.insert(i,rn)
else:
i+= 1
class TestCollapseOverlappingRanges(unittest.TestCase):
def test(self) -> None:
ranges: List[Tuple[int,int]] = []
collapseAdjoiningRanges(ranges)
self.assertEqual(ranges, [])
ranges = [(1, 3), (5, 7)]
collapseAdjoiningRanges(ranges)
self.assertEqual(ranges, [(1, 3), (5, 7)])
ranges = [(1,3),(2,5),(7, 9)]
collapseAdjoiningRanges(ranges)
self.assertEqual(ranges, [(1, 5), (7, 9)])
ranges = [(1,2),(3,5),(4, 9)]
collapseAdjoiningRanges(ranges)
self.assertEqual(ranges, [(1, 9)])
class FixedSizeSourcePreview(SourceHighlightingTextEdit):
def __init__(self, parent: QWidget=None) -> None:
super().__init__(parent)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
class Line:
def __init__(self, charPos: int, lineNumber: int) -> None:
self.charPos = charPos
self.lineNumber = lineNumber
def __lt__ (self, other: 'Line') -> bool:
return self.charPos < other.charPos
# Detects quickly which character position corresponds to which line number.
# The first line numer is 1.
class LineMapping:
def __init__(self,text: str) -> None:
self.list: List[Line] = []
self.numberMap = {1:0} # line 1 always starts at 0
self.text = text
reLineBreak = re.compile("\\n")
cur = 0
line = 1
while True:
result = reLineBreak.search(text, cur)
if result:
startPos, endPos = result.span()
self.list.append(Line(startPos,line))
self.numberMap[line+1] = endPos
cur = endPos
line = line + 1
else:
break
def findLineNumber (self, charPos: int) -> int:
if not self.list:
return 0
pos = bisect.bisect_left (self.list, Line(charPos,0))
if pos >= len(self.list):
return self.list[-1].lineNumber+1
return self.list[pos].lineNumber
def getLine(self, lineNumber: int) -> str:
if lineNumber == 0 or lineNumber > len(self.numberMap):
return ""
startPos = self.numberMap[lineNumber]
if lineNumber == len(self.numberMap):
endPos = len(self.text)
else:
endPos = self.numberMap[lineNumber+1]-1
return self.text [startPos:endPos]
def lineCount(self) -> int:
return len(self.numberMap)
class TestLineMapping(unittest.TestCase):
def test(self) -> None:
m = LineMapping("")
self.assertEqual(m.lineCount(), 1)
self.assertEqual(m.findLineNumber(0), 0)
self.assertEqual(m.findLineNumber(10), 0)
# 0000000000011111111111
# 012345 67890 12345 678
m = LineMapping("hallo\nwelt\ntest\n123")
self.assertEqual(m.lineCount(), 4)
exp = {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2, 10: 2, 11: 3, 12: 3, 13: 3, 14: 3, 15: 3, 16: 4, 17: 4, 18: 4, 19: 4, 20: 4, 21: 4, 22: 4, 23: 4, 24: 4}
for charPos, lineNumber in exp.items():
self.assertEqual(m.findLineNumber(charPos), lineNumber)
self.assertEqual(m.getLine(0), "")
self.assertEqual(m.getLine(1), "hallo")
self.assertEqual(m.getLine(2), "welt")
self.assertEqual(m.getLine(3), "test")
self.assertEqual(m.getLine(4), "123")
self.assertEqual(m.getLine(5), "")
class MatchesInFile:
def __init__(self, name: str) -> None:
self.name = name
self.matches: List[Tuple[int, List[str]]] = []
def addMatches (self, nLineNumberStart: int, lines: List[str]) -> None:
self.matches.append((nLineNumberStart, lines))
# Returns a list of all matches in all files
# This reads all files and retrieves the matches with some lines surounding them
def extractMatches (matches: List[str], searchData: FullTextIndex.ContentQuery, linesOfContext: int, cancelEvent: threading.Event=None) -> List[MatchesInFile]:
results: List[MatchesInFile] = []
for name in matches:
matchList = MatchesInFile(name)
try:
with fopen(name) as file:
text = file.read()
except:
matchList.addMatches(0, ["Failed to open file"])
else:
lineIndex = LineMapping(text)
ranges = []
for startPos, _ in searchData.matches(text):
lineNumber = lineIndex.findLineNumber(startPos)
startLine = lineNumber-linesOfContext
if startLine < 1:
startLine = 1
endLine = lineNumber+linesOfContext
if endLine > lineIndex.lineCount():
endLine = lineIndex.lineCount()
ranges.append((startLine, endLine))
# Collapse overlapping ranges into one
collapseAdjoiningRanges (ranges)
for startLine, endLine in ranges:
lines = []
for i in range(startLine, endLine+1):
lines.append(lineIndex.getLine(i))
matchList.addMatches(startLine, lines)
results.append(matchList)
if cancelEvent and cancelEvent.is_set():
return results
return results
class MatchesOverview (QWidget):
# Triggered if a selection was finished while holding a modifier key down
selectionFinishedWithKeyboardModifier = pyqtSignal('QString', int)
def __init__ (self, parent: QWidget) -> None:
super().__init__(parent)
self.ui = Ui_MatchesOverview()
self.ui.setupUi(self)
self.matches: Optional[List[str]] = None
self.searchData: Optional[FullTextIndex.ContentQuery] = None
self.resultHandled = True
self.sourceFont = None
self.lineHeight = 0
self.tabWidth = 4
self.linesOfContext = 2
self.scrollItems = RecyclingVerticalScrollArea.SrollAreaItemList()
self.matchIndexes: List[int] = []
def reloadConfig (self, font: QFont) -> None:
self.sourceFont = font
metrics = QFontMetrics(self.sourceFont)
self.lineHeight = metrics.height()
linesOfContext = appConfig().previewLines
if linesOfContext % 2:
linesOfContext /= 2
else:
linesOfContext = (linesOfContext+1)/2
if linesOfContext < 1:
linesOfContext = 1
self.linesOfContext = int(linesOfContext)
config = appConfig().SourceViewer
self.tabWidth = config.TabWidth
# TODO: rebuild self.scrollItems if the font changed or tab width changed...
def setSearchResult(self, matches: List[str], searchData: FullTextIndex.ContentQuery) -> None:
self.matches = matches
self.searchData = searchData
self.resultHandled = False
if self.isVisible():
self.__handleResult()
def activate (self) -> None:
if not self.resultHandled:
self.__handleResult ()
def scrollToFile (self, index: int) -> None:
if index >= len(self.matchIndexes):
return
self.ui.scrollArea.scrollToNthItem(self.matchIndexes[index])
def __handleResult(self) -> None:
self.resultHandled = True
self.scrollItems.clear()
self.matchIndexes = []
if self.matches:
results = AsynchronousTask.execute (self, extractMatches, self.matches, self.searchData, self.linesOfContext,
bEnableCancel=True)
for result in results:
index = self.__addHeader(result.name)
self.matchIndexes.append(index)
for startLine, lines in result.matches:
self.__addText(result.name, startLine, lines)
self.ui.scrollArea.setItems(self.scrollItems)
def __addHeader(self, text: str) -> int:
return self.__addLine(text, True)
def __addLine(self, text: str, bIsBold:bool = False) -> int:
labelItem = RecyclingVerticalScrollArea.Labeltem(text, bIsBold, 20)
return self.scrollItems.addItem(labelItem)
def __addText(self, name: str, startLine: int, lines: List[str]) -> int:
text = "\n".join(lines)
scrollBarHeight = 24
height = len(lines)*self.lineHeight+11+scrollBarHeight
editItem = FixedSizeSourcePreviewItem (self, startLine, text, name, height)
return self.scrollItems.addItem(editItem)
class FixedSizeSourcePreviewItem (RecyclingVerticalScrollArea.ScrollAreaItem):
def __init__(self, matchesOverview: MatchesOverview, startLine: int, text: str, name: str, height: int) -> None:
super ().__init__(height)
self.matchesOverview = matchesOverview
self.startLine = startLine
self.text = text
self.name = name
def generateItem (self, parent: QWidget) -> QWidget:
item = FixedSizeSourcePreview(parent)
# Forward the signal to MatchesOverview instance
item.selectionFinishedWithKeyboardModifier.connect (self.matchesOverview.selectionFinishedWithKeyboardModifier)
return item
def configureItem(self, item: QWidget) -> None:
rules = HighlightingRulesCache.rules().getRulesByFileName(self.name, self.matchesOverview.sourceFont)
item.setFont(self.matchesOverview.sourceFont)
item.setTabStopWidth(self.matchesOverview.tabWidth*10)
item.highlighter.setHighlightingRules (rules)
item.highlighter.setSearchData (self.matchesOverview.searchData)
item.setPlainText(self.text)
item.showLineNumbers(True, self.startLine)
def getType(self) -> str:
return "FixedSizeSourcePreview"
def main() -> None:
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
w = MatchesOverview(None)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
unittest.main()
#main()
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.