terminal_search.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import 'package:equatable/equatable.dart';
  2. import 'package:xterm/buffer/line/line.dart';
  3. import 'package:xterm/terminal/terminal.dart';
  4. import 'package:xterm/util/constants.dart';
  5. /// Represents a search result.
  6. /// This instance will be replaced as a whole when the search has to be re-triggered
  7. /// It stores the hits the search produced and the navigation state inside
  8. /// the search results
  9. class TerminalSearchResult {
  10. final _hitsByLine = Map<int, List<TerminalSearchHit>>();
  11. late final _allHits;
  12. int _currentSearchHit = 0;
  13. /// creates a new search result instance from the given hits
  14. TerminalSearchResult.fromHits(List<TerminalSearchHit> hits) {
  15. _allHits = hits;
  16. for (final hit in hits) {
  17. if (!_hitsByLine.containsKey(hit.startLineIndex)) {
  18. _hitsByLine[hit.startLineIndex] =
  19. List<TerminalSearchHit>.empty(growable: true);
  20. }
  21. if (!_hitsByLine.containsKey(hit.endLineIndex)) {
  22. _hitsByLine[hit.endLineIndex] =
  23. List<TerminalSearchHit>.empty(growable: true);
  24. }
  25. _hitsByLine[hit.startLineIndex]!.add(hit);
  26. if (hit.startLineIndex != hit.endLineIndex) {
  27. _hitsByLine[hit.endLineIndex]!.add(hit);
  28. }
  29. }
  30. if (_allHits.length > 0) {
  31. _currentSearchHit = _allHits.length;
  32. } else {
  33. _currentSearchHit = 0;
  34. }
  35. }
  36. /// creates an empty search result
  37. TerminalSearchResult.empty()
  38. : _allHits = List<TerminalSearchHit>.empty(growable: false);
  39. /// returns all hits of this search result
  40. List<TerminalSearchHit> get allHits => _allHits;
  41. /// returns the number of the current search hit
  42. int get currentSearchHit => _currentSearchHit;
  43. /// sets the current search hit number
  44. void set currentSearchHit(int currentSearchHit) {
  45. if (_allHits.length <= 0) {
  46. _currentSearchHit = 0;
  47. } else {
  48. _currentSearchHit = currentSearchHit.clamp(1, _allHits.length).toInt();
  49. }
  50. }
  51. }
  52. /// Represents one search hit
  53. class TerminalSearchHit {
  54. TerminalSearchHit(
  55. this.startLineIndex, this.startIndex, this.endLineIndex, this.endIndex);
  56. /// index of the line where the hit starts
  57. final int startLineIndex;
  58. /// index of the hit start inside the start line
  59. final int startIndex;
  60. /// index of the line where the hit starts
  61. final int endLineIndex;
  62. /// index of the hit end inside the end line
  63. final int endIndex;
  64. /// checks if the given cell (line / col) is contained in this hit
  65. bool contains(int line, int col) {
  66. if (line < startLineIndex || line > endLineIndex) {
  67. return false;
  68. }
  69. if (line == startLineIndex && startLineIndex == endLineIndex) {
  70. return col >= startIndex && col < endIndex;
  71. }
  72. if (line == startLineIndex) {
  73. return col >= startIndex;
  74. }
  75. if (line == endLineIndex) {
  76. return col < endIndex;
  77. }
  78. // here we are sure that the given point is inside a full line match
  79. return true;
  80. }
  81. }
  82. /// represents options for a terminal search
  83. class TerminalSearchOptions extends Equatable {
  84. TerminalSearchOptions({
  85. this.caseSensitive = false,
  86. this.matchWholeWord = false,
  87. this.useRegex = false,
  88. });
  89. /// defines if the search should be case sensitive. If set to [false] then
  90. /// the search will be case insensitive
  91. final bool caseSensitive;
  92. /// defines if the search should match whole words.
  93. final bool matchWholeWord;
  94. /// defines if the search should treat the pattern as a regex, or not
  95. final bool useRegex;
  96. /// creates a new TerminalSearchOptions instance based on this one changing the
  97. /// given parameters
  98. TerminalSearchOptions copyWith(
  99. {bool? caseSensitive, bool? matchWholeWord, bool? useRegex}) {
  100. return TerminalSearchOptions(
  101. caseSensitive: caseSensitive ?? this.caseSensitive,
  102. matchWholeWord: matchWholeWord ?? this.matchWholeWord,
  103. useRegex: useRegex ?? this.useRegex,
  104. );
  105. }
  106. @override
  107. bool get stringify => true;
  108. @override
  109. List<Object?> get props => [
  110. caseSensitive,
  111. matchWholeWord,
  112. useRegex,
  113. ];
  114. }
  115. /// represents a search task.
  116. /// A search task can deliver search results based on the given parameters.
  117. /// It takes care to cache the results as long as possible and re-trigger a
  118. /// search on demand only when necessary
  119. class TerminalSearchTask {
  120. TerminalSearchTask(this._search, this._terminal, this._dirtyTagName,
  121. this._terminalSearchOptions);
  122. final TerminalSearch _search;
  123. final Terminal _terminal;
  124. String? _pattern = null;
  125. bool _isPatternDirty = true;
  126. RegExp? _searchRegexp = null;
  127. final String _dirtyTagName;
  128. TerminalSearchOptions _terminalSearchOptions;
  129. bool _isActive = false;
  130. /// indicates if the current search task is active
  131. bool get isActive => _isActive;
  132. /// sets the active state of this search task
  133. void set isActive(bool isActive) {
  134. _isActive = isActive;
  135. if (isActive) {
  136. _invalidate();
  137. }
  138. }
  139. bool? _hasBeenUsingAltBuffer;
  140. TerminalSearchResult? _lastSearchResult = null;
  141. bool _isAnyLineDirty() {
  142. final bufferLength = _terminal.buffer.lines.length;
  143. for (var i = 0; i < bufferLength; i++) {
  144. if (_terminal.buffer.lines[i].isTagDirty(_dirtyTagName)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. void _markLinesForSearchDone() {
  151. final bufferLength = _terminal.buffer.lines.length;
  152. for (var i = 0; i < bufferLength; i++) {
  153. _terminal.buffer.lines[i].markTagAsNonDirty(_dirtyTagName);
  154. }
  155. }
  156. bool _isTerminalStateDirty() {
  157. if (_isAnyLineDirty()) {
  158. return true;
  159. }
  160. if (_hasBeenUsingAltBuffer != null &&
  161. _hasBeenUsingAltBuffer! != _terminal.isUsingAltBuffer()) {
  162. return true;
  163. }
  164. return false;
  165. }
  166. bool get _isDirty {
  167. if (_isPatternDirty) {
  168. return true;
  169. }
  170. return _isTerminalStateDirty();
  171. }
  172. /// the currently used pattern of this search task
  173. String? get pattern => _pattern;
  174. /// sets the pattern to use for this search task
  175. void set pattern(String? newPattern) {
  176. if (newPattern != _pattern) {
  177. _pattern = newPattern;
  178. _invalidate();
  179. }
  180. }
  181. /// the currently used search options
  182. TerminalSearchOptions get options => _terminalSearchOptions;
  183. /// sets the search options to use
  184. void set options(TerminalSearchOptions newOptions) {
  185. if (_terminalSearchOptions == newOptions) {
  186. return;
  187. }
  188. _terminalSearchOptions = newOptions;
  189. _invalidate();
  190. }
  191. /// returns the hit that is currently the selected one (based on the search
  192. /// result navigation)
  193. TerminalSearchHit? get currentSearchHitObject {
  194. if (searchResult.allHits.length >= searchResult.currentSearchHit &&
  195. searchResult.currentSearchHit > 0) {
  196. return searchResult.allHits[searchResult.currentSearchHit - 1];
  197. }
  198. return null;
  199. }
  200. /// the number of search hits in the current search result
  201. int get numberOfSearchHits => searchResult.allHits.length;
  202. /// number of the hit that is currently selected
  203. int get currentSearchHit => searchResult.currentSearchHit;
  204. /// sets the hit number that shall be selected
  205. void set currentSearchHit(int currentSearchHit) {
  206. searchResult.currentSearchHit = currentSearchHit;
  207. }
  208. void _invalidate() {
  209. _isPatternDirty = true;
  210. _searchRegexp = null;
  211. _lastSearchResult = null;
  212. }
  213. /// returns the current search result or triggers a new search if it has to
  214. /// the result is a up to date search result either way
  215. TerminalSearchResult get searchResult {
  216. if (_pattern == null || !_isActive) {
  217. return TerminalSearchResult.empty();
  218. }
  219. if (_lastSearchResult != null && !_isDirty) {
  220. return _lastSearchResult!;
  221. }
  222. final terminalWidth = _terminal.terminalWidth;
  223. if (_searchRegexp == null) {
  224. var pattern = _pattern!;
  225. if (!_terminalSearchOptions.useRegex) {
  226. pattern = RegExp.escape(_pattern!);
  227. }
  228. final regex = '(?<hit>$pattern)';
  229. _searchRegexp = RegExp(regex,
  230. caseSensitive: _terminalSearchOptions.caseSensitive,
  231. multiLine: false);
  232. }
  233. final hits = List<TerminalSearchHit>.empty(growable: true);
  234. for (final match
  235. in _searchRegexp!.allMatches(_search.terminalSearchString)) {
  236. final start = match.start;
  237. final end = match.end;
  238. final startLineIndex = (start / terminalWidth).floor();
  239. final endLineIndex = (end / terminalWidth).floor();
  240. // subtract the lines that got added in order to get the index inside the line
  241. final startIndex = start - startLineIndex * terminalWidth;
  242. final endIndex = end - endLineIndex * terminalWidth;
  243. if (_terminalSearchOptions.matchWholeWord) {
  244. // we match a whole word when the hit fulfills:
  245. // 1) starts at a line beginning or has a word-separator before it
  246. final startIsOK =
  247. startIndex == 0 || kWordSeparators.contains(match.input[start - 1]);
  248. // 2) ends with a line or has a word-separator after it
  249. final endIsOK = endIndex == terminalWidth ||
  250. kWordSeparators.contains(match.input[end]);
  251. if (!startIsOK || !endIsOK) {
  252. continue;
  253. }
  254. }
  255. hits.add(
  256. TerminalSearchHit(
  257. startLineIndex,
  258. startIndex,
  259. endLineIndex,
  260. endIndex,
  261. ),
  262. );
  263. }
  264. _markLinesForSearchDone();
  265. _isPatternDirty = false;
  266. _lastSearchResult = TerminalSearchResult.fromHits(hits);
  267. _hasBeenUsingAltBuffer = _terminal.isUsingAltBuffer();
  268. return _lastSearchResult!;
  269. }
  270. }
  271. /// main entry for terminal searches. This class is the factory for search tasks
  272. /// and will cache the search string that gets generated out of the terminal content
  273. /// so that all search tasks created by this search can use the same cached search string
  274. class TerminalSearch {
  275. TerminalSearch(this._terminal);
  276. final Terminal _terminal;
  277. String? _cachedSearchString;
  278. int? _lastTerminalWidth;
  279. /// creates a new search task that will use this search to access a cached variant
  280. /// of the terminal search string
  281. TerminalSearchTask createSearchTask(String dirtyTagName) {
  282. return TerminalSearchTask(
  283. this, _terminal, dirtyTagName, TerminalSearchOptions());
  284. }
  285. /// returns the current terminal search string. The search string will be
  286. /// refreshed on demand if
  287. String get terminalSearchString {
  288. final bufferLength = _terminal.buffer.lines.length;
  289. final terminalWidth = _terminal.terminalWidth;
  290. var isAnySearchStringInvalid = false;
  291. for (var i = 0; i < bufferLength; i++) {
  292. if (!_terminal.buffer.lines[i].hasCachedSearchString) {
  293. isAnySearchStringInvalid = true;
  294. }
  295. }
  296. late String completeSearchString;
  297. if (_cachedSearchString != null &&
  298. _lastTerminalWidth != null &&
  299. _lastTerminalWidth! == terminalWidth &&
  300. !isAnySearchStringInvalid) {
  301. completeSearchString = _cachedSearchString!;
  302. } else {
  303. final bufferContent = StringBuffer();
  304. for (var i = 0; i < bufferLength; i++) {
  305. final BufferLine line = _terminal.buffer.lines[i];
  306. final searchString = line.toSearchString(terminalWidth);
  307. bufferContent.write(searchString);
  308. if (searchString.length < terminalWidth) {
  309. // fill up so that the row / col can be mapped back later on
  310. bufferContent.writeAll(
  311. List<String>.filled(terminalWidth - searchString.length, ' '));
  312. }
  313. }
  314. completeSearchString = bufferContent.toString();
  315. _cachedSearchString = completeSearchString;
  316. _lastTerminalWidth = terminalWidth;
  317. }
  318. return completeSearchString;
  319. }
  320. }