terminal_search.dart 11 KB

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