CollectionNavigatorBase.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. namespace Terminal.Gui.Views;
  2. /// <inheritdoc/>
  3. internal abstract class CollectionNavigatorBase : ICollectionNavigator
  4. {
  5. private readonly object _lock = new ();
  6. private DateTime _lastKeystroke = DateTime.Now;
  7. private string _searchString = "";
  8. /// <inheritdoc/>
  9. public ICollectionNavigatorMatcher Matcher { get; set; } = new DefaultCollectionNavigatorMatcher ();
  10. /// <inheritdoc/>
  11. public string SearchString
  12. {
  13. get
  14. {
  15. lock (_lock)
  16. {
  17. return _searchString;
  18. }
  19. }
  20. private set
  21. {
  22. lock (_lock)
  23. {
  24. _searchString = value;
  25. }
  26. OnSearchStringChanged (new (value));
  27. }
  28. }
  29. /// <inheritdoc/>
  30. public int TypingDelay { get; set; } = 500;
  31. /// <inheritdoc/>
  32. public int? GetNextMatchingItem (int? currentIndex, char keyStruck)
  33. {
  34. if (currentIndex.HasValue && currentIndex < 0)
  35. {
  36. throw new ArgumentOutOfRangeException (nameof (currentIndex), @"Must be non-negative");
  37. }
  38. if (!char.IsControl (keyStruck))
  39. {
  40. // maybe user pressed 'd' and now presses 'd' again.
  41. // a candidate search is things that begin with "dd"
  42. // but if we find none then we must fallback on cycling
  43. // d instead and discard the candidate state
  44. var candidateState = "";
  45. TimeSpan elapsedTime;
  46. string currentSearchString;
  47. lock (_lock)
  48. {
  49. elapsedTime = DateTime.Now - _lastKeystroke;
  50. currentSearchString = _searchString;
  51. }
  52. Logging.Debug ($"CollectionNavigator began processing '{keyStruck}', it has been {elapsedTime} since last keystroke");
  53. // is it a second or third (etc) keystroke within a short time
  54. if (currentSearchString.Length > 0 && elapsedTime < TimeSpan.FromMilliseconds (TypingDelay))
  55. {
  56. // "dd" is a candidate
  57. candidateState = currentSearchString + keyStruck;
  58. Logging.Debug ($"Appending, search is now for '{candidateState}'");
  59. }
  60. else
  61. {
  62. // its a fresh keystroke after some time
  63. // or its first ever key press
  64. SearchString = new (keyStruck, 1);
  65. Logging.Debug ("It has been too long since last key press so beginning new search");
  66. }
  67. int? idxCandidate = GetNextMatchingItem (
  68. currentIndex,
  69. candidateState,
  70. // prefer not to move if there are multiple characters e.g. "ca" + 'r' should stay on "car" and not jump to "cart"
  71. candidateState.Length > 1
  72. );
  73. Logging.Debug ($"CollectionNavigator searching (preferring minimum movement) matched:{idxCandidate}");
  74. if (idxCandidate is { })
  75. {
  76. // found "dd" so candidate search string is accepted
  77. lock (_lock)
  78. {
  79. _lastKeystroke = DateTime.Now;
  80. }
  81. SearchString = candidateState;
  82. Logging.Debug ($"Found collection item that matched search:{idxCandidate}");
  83. return idxCandidate;
  84. }
  85. //// nothing matches "dd" so discard it as a candidate
  86. //// and just cycle "d" instead
  87. lock (_lock)
  88. {
  89. _lastKeystroke = DateTime.Now;
  90. }
  91. idxCandidate = GetNextMatchingItem (currentIndex, candidateState);
  92. Logging.Debug ($"CollectionNavigator searching (any match) matched:{idxCandidate}");
  93. // if a match wasn't found, the user typed a 'wrong' key in their search ("can" + 'z'
  94. // instead of "can" + 'd').
  95. if (SearchString.Length > 1 && idxCandidate is null)
  96. {
  97. Logging.Debug ("CollectionNavigator ignored key and returned existing index");
  98. // ignore it since we're still within the typing delay
  99. // don't add it to SearchString either
  100. return currentIndex;
  101. }
  102. // if no changes to current state manifested
  103. if (idxCandidate == currentIndex || idxCandidate is null)
  104. {
  105. Logging.Debug ("CollectionNavigator found no changes to current index, so clearing search");
  106. // clear history and treat as a fresh letter
  107. ClearSearchString ();
  108. // match on the fresh letter alone
  109. SearchString = new (keyStruck, 1);
  110. idxCandidate = GetNextMatchingItem (currentIndex, SearchString);
  111. Logging.Debug ($"CollectionNavigator new SearchString {SearchString} matched index:{idxCandidate}");
  112. return idxCandidate ?? currentIndex;
  113. }
  114. Logging.Debug ($"CollectionNavigator final answer was:{idxCandidate}");
  115. // Found another "d" or just leave index as it was
  116. return idxCandidate;
  117. }
  118. Logging.Debug ("CollectionNavigator found key press was not actionable so clearing search and returning null");
  119. // clear state because keypress was a control char
  120. ClearSearchString ();
  121. // control char indicates no selection
  122. return null;
  123. }
  124. /// <summary>This event is raised when <see cref="SearchString"/> is changed. Useful for debugging.</summary>
  125. public event EventHandler<KeystrokeNavigatorEventArgs>? SearchStringChanged;
  126. /// <summary>Returns the collection being navigated element at <paramref name="idx"/>.</summary>
  127. /// <returns></returns>
  128. protected abstract object ElementAt (int idx);
  129. /// <summary>Return the number of elements in the collection</summary>
  130. protected abstract int GetCollectionLength ();
  131. /// <summary>
  132. /// Raised when the <see cref="SearchString"/> is changed. Useful for debugging. Raises the
  133. /// <see cref="SearchStringChanged"/> event.
  134. /// </summary>
  135. /// <param name="e"></param>
  136. protected virtual void OnSearchStringChanged (KeystrokeNavigatorEventArgs e) { SearchStringChanged?.Invoke (this, e); }
  137. /// <summary>Gets the index of the next item in the collection that matches <paramref name="search"/>.</summary>
  138. /// <param name="currentIndex">The index in the collection to start the search from.</param>
  139. /// <param name="search">The search string to use.</param>
  140. /// <param name="minimizeMovement">
  141. /// Set to <see langword="true"/> to stop the search on the first match if there are
  142. /// multiple matches for <paramref name="search"/>. e.g. "ca" + 'r' should stay on "car" and not jump to "cart". If
  143. /// <see langword="false"/> (the default), the next matching item will be returned, even if it is above in the
  144. /// collection.
  145. /// </param>
  146. /// <returns>The index of the next matching item or <see langword="null"/> if no match was found.</returns>
  147. internal int? GetNextMatchingItem (int? currentIndex, string search, bool minimizeMovement = false)
  148. {
  149. if (string.IsNullOrEmpty (search))
  150. {
  151. return null;
  152. }
  153. int collectionLength = GetCollectionLength ();
  154. if (currentIndex.HasValue && currentIndex < collectionLength && Matcher.IsMatch (search, ElementAt (currentIndex.Value)))
  155. {
  156. // we are already at a match
  157. if (minimizeMovement)
  158. {
  159. // if we would rather not jump around (e.g. user is typing lots of text to get this match)
  160. return currentIndex;
  161. }
  162. for (var i = 1; i < collectionLength; i++)
  163. {
  164. //circular
  165. int? idxCandidate = (i + currentIndex) % collectionLength;
  166. if (Matcher.IsMatch (search, ElementAt (idxCandidate!.Value)))
  167. {
  168. return idxCandidate;
  169. }
  170. }
  171. // nothing else starts with the search term
  172. return currentIndex;
  173. }
  174. // search terms no longer match the current selection or there is none
  175. for (var i = 0; i < collectionLength; i++)
  176. {
  177. if (Matcher.IsMatch (search, ElementAt (i)))
  178. {
  179. return i;
  180. }
  181. }
  182. // Nothing matches
  183. return null;
  184. }
  185. private void ClearSearchString ()
  186. {
  187. SearchString = "";
  188. lock (_lock)
  189. {
  190. _lastKeystroke = DateTime.Now;
  191. }
  192. }
  193. }