terminal_search.dart 11 KB

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