Osc8UrlLinker.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #nullable enable
  2. namespace Terminal.Gui.Drivers;
  3. internal static class Osc8UrlLinker
  4. {
  5. internal readonly struct Options
  6. {
  7. internal readonly string [] _allowedSchemes;
  8. internal readonly bool _validateWithUri;
  9. private Options (string [] allowedSchemes, bool validateWithUri)
  10. {
  11. _allowedSchemes = allowedSchemes;
  12. _validateWithUri = validateWithUri;
  13. }
  14. public static Options CreateDefault ()
  15. {
  16. return new Options (
  17. allowedSchemes: ["http", "https", "ftp", "ftps"],
  18. validateWithUri: true
  19. );
  20. }
  21. }
  22. private static readonly Options _defaultOptions = Options.CreateDefault ();
  23. internal static StringBuilder WrapOsc8 (StringBuilder input)
  24. {
  25. return WrapOsc8 (input, _defaultOptions);
  26. }
  27. internal static StringBuilder WrapOsc8 (StringBuilder input, Options options)
  28. {
  29. if (input.Length == 0)
  30. {
  31. return input;
  32. }
  33. string text = input.ToString ();
  34. int len = text.Length;
  35. StringBuilder? result = null;
  36. int copyFrom = 0;
  37. int i = 0;
  38. while (i < len)
  39. {
  40. if (text [i] == '\x1B')
  41. {
  42. int escEnd = ParseEscapeSequence (text, i, len);
  43. if (result != null)
  44. {
  45. if (i > copyFrom)
  46. {
  47. result.Append (text, copyFrom, i - copyFrom);
  48. }
  49. result.Append (text, i, escEnd - i);
  50. copyFrom = escEnd;
  51. }
  52. i = escEnd;
  53. continue;
  54. }
  55. int segStart = i;
  56. int nextEsc = text.IndexOf ('\x1B', segStart);
  57. if (nextEsc < 0)
  58. {
  59. nextEsc = len;
  60. }
  61. bool changed;
  62. string processed = WrapPlainText (text, segStart, nextEsc, options, out changed);
  63. if (changed)
  64. {
  65. result ??= new StringBuilder (text.Length + 100);
  66. if (segStart > copyFrom)
  67. {
  68. result.Append (text, copyFrom, segStart - copyFrom);
  69. }
  70. result.Append (processed);
  71. copyFrom = nextEsc;
  72. }
  73. i = nextEsc;
  74. }
  75. if (result is null)
  76. {
  77. return input;
  78. }
  79. if (copyFrom < len)
  80. {
  81. result.Append (text, copyFrom, len - copyFrom);
  82. }
  83. return result;
  84. }
  85. private static int ParseEscapeSequence (string text, int start, int len)
  86. {
  87. int i = start;
  88. if (i + 1 >= len)
  89. {
  90. return len;
  91. }
  92. char c1 = text [i + 1];
  93. if (c1 == '[')
  94. {
  95. int j = i + 2;
  96. while (j < len)
  97. {
  98. char ch = text [j++];
  99. if (ch >= '@' && ch <= '~')
  100. {
  101. break;
  102. }
  103. }
  104. return j;
  105. }
  106. if (c1 == ']')
  107. {
  108. int j = i + 2;
  109. while (j < len)
  110. {
  111. char ch = text [j++];
  112. if (ch == '\x07')
  113. {
  114. break;
  115. }
  116. if (ch == '\x1B')
  117. {
  118. if (j < len && text [j] == '\\')
  119. {
  120. j++;
  121. break;
  122. }
  123. }
  124. }
  125. return j;
  126. }
  127. return Math.Min (i + 2, len);
  128. }
  129. private static string WrapPlainText (string full, int start, int endExclusive, Options options, out bool changed)
  130. {
  131. ReadOnlySpan<char> span = full.AsSpan (start, endExclusive - start);
  132. ReadOnlySpan<char> delimiter = "://".AsSpan ();
  133. int i = 0;
  134. int copyFrom = 0;
  135. StringBuilder? sb = null;
  136. while (i < span.Length)
  137. {
  138. int rel = span.Slice (i).IndexOf (delimiter, StringComparison.Ordinal);
  139. if (rel < 0)
  140. {
  141. break;
  142. }
  143. int delimAt = i + rel;
  144. int schemeEnd = delimAt;
  145. int schemeStart = schemeEnd - 1;
  146. while (schemeStart >= 0 && char.IsLetter (span [schemeStart]))
  147. {
  148. schemeStart--;
  149. }
  150. schemeStart++;
  151. if (schemeStart < 0 || schemeStart >= schemeEnd)
  152. {
  153. i = delimAt + delimiter.Length;
  154. continue;
  155. }
  156. ReadOnlySpan<char> scheme = span.Slice (schemeStart, schemeEnd - schemeStart);
  157. if (!IsAllowedScheme (scheme, options))
  158. {
  159. i = delimAt + delimiter.Length;
  160. continue;
  161. }
  162. int urlStart = schemeStart;
  163. int j = delimAt + delimiter.Length;
  164. while (j < span.Length && !IsUrlTerminator (span [j]))
  165. {
  166. j++;
  167. }
  168. // Trim punctuation from the end of the URL, but remember it so we can re-append it after the hyperlink
  169. int urlEnd = TrimTrailingPunctuation (span, urlStart, j);
  170. ReadOnlySpan<char> trailing = span.Slice (urlEnd, j - urlEnd);
  171. if (urlEnd <= (delimAt + delimiter.Length))
  172. {
  173. i = j;
  174. continue;
  175. }
  176. string candidate = span.Slice (urlStart, urlEnd - urlStart).ToString ();
  177. Uri? _;
  178. if (options._validateWithUri && !IsValidUrl (candidate, options, out _))
  179. {
  180. i = j;
  181. continue;
  182. }
  183. sb ??= new StringBuilder (span.Length + 64);
  184. if (urlStart > copyFrom)
  185. {
  186. sb.Append (span.Slice (copyFrom, urlStart - copyFrom));
  187. }
  188. // Preserve original candidate for link target and display
  189. string linkTarget = candidate;
  190. sb.Append (EscSeqUtils.OSC_StartHyperlink (linkTarget));
  191. sb.Append (candidate);
  192. sb.Append (EscSeqUtils.OSC_EndHyperlink ());
  193. // Re-append the trimmed punctuation/suffix (e.g., "!", ",", ")")
  194. if (!trailing.IsEmpty)
  195. {
  196. sb.Append (trailing);
  197. }
  198. copyFrom = j;
  199. i = j;
  200. }
  201. if (sb is null)
  202. {
  203. changed = false;
  204. return span.ToString ();
  205. }
  206. if (copyFrom < span.Length)
  207. {
  208. sb.Append (span.Slice (copyFrom));
  209. }
  210. changed = true;
  211. return sb.ToString ();
  212. }
  213. private static bool IsAllowedScheme (ReadOnlySpan<char> scheme, Options options)
  214. {
  215. for (int i = 0; i < options._allowedSchemes.Length; i++)
  216. {
  217. string s = options._allowedSchemes [i];
  218. if (scheme.Equals (s, StringComparison.OrdinalIgnoreCase))
  219. {
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. private static bool IsUrlTerminator (char c)
  226. {
  227. return char.IsWhiteSpace (c) || c == '<' || c == '>' || c == '"' || c == '\'' || c == '\x1B';
  228. }
  229. private static int TrimTrailingPunctuation (ReadOnlySpan<char> span, int start, int end)
  230. {
  231. int e = end;
  232. while (e > start)
  233. {
  234. char c = span [e - 1];
  235. if (c is '.' or ',' or '!' or '?' or ';' or ':' or ']' or '}' or '"')
  236. {
  237. e--;
  238. }
  239. else
  240. {
  241. break;
  242. }
  243. }
  244. if (e > start && span [e - 1] == ')')
  245. {
  246. int opens = 0;
  247. int closes = 0;
  248. for (int k = start; k < e; k++)
  249. {
  250. if (span [k] == '(')
  251. {
  252. opens++;
  253. }
  254. else if (span [k] == ')')
  255. {
  256. closes++;
  257. }
  258. }
  259. while (e > start && closes > opens && span [e - 1] == ')')
  260. {
  261. e--;
  262. closes--;
  263. }
  264. }
  265. return e;
  266. }
  267. private static bool IsValidUrl (string candidate, Options options, out Uri? uri)
  268. {
  269. if (Uri.TryCreate (candidate, UriKind.Absolute, out uri))
  270. {
  271. for (int i = 0; i < options._allowedSchemes.Length; i++)
  272. {
  273. string s = options._allowedSchemes [i];
  274. if (uri.Scheme.Equals (s, StringComparison.OrdinalIgnoreCase))
  275. {
  276. return true;
  277. }
  278. }
  279. }
  280. uri = null;
  281. return false;
  282. }
  283. }