Osc8UrlLinker.cs 8.6 KB

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