terminal_search.dart 11 KB

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