HexView.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. #nullable enable
  2. //
  3. // HexView.cs: A hexadecimal viewer
  4. //
  5. // TODO: Support searching and highlighting of the search result
  6. // TODO: Support shrinking the stream (e.g. del/backspace should work).
  7. //
  8. using System.Buffers;
  9. namespace Terminal.Gui;
  10. /// <summary>Hex viewer and editor <see cref="View"/> over a <see cref="Stream"/></summary>
  11. /// <remarks>
  12. /// <para>
  13. /// <see cref="HexView"/> provides a hex editor on top of a seekable <see cref="Stream"/> with the left side
  14. /// showing the hex values of the bytes in the <see cref="Stream"/> and the right side showing the contents
  15. /// (filtered
  16. /// to non-control sequence ASCII characters).
  17. /// </para>
  18. /// <para>Users can switch from one side to the other by using the tab key.</para>
  19. /// <para>
  20. /// To enable editing, set <see cref="AllowEdits"/> to true. When <see cref="AllowEdits"/> is true the user can
  21. /// make changes to the hexadecimal values of the <see cref="Stream"/>. Any changes are tracked in the
  22. /// <see cref="Edits"/> property (a <see cref="SortedDictionary{TKey, TValue}"/>) indicating the position where the
  23. /// changes were made and the new values. A convenience method, <see cref="ApplyEdits"/> will apply the edits to
  24. /// the <see cref="Stream"/>.
  25. /// </para>
  26. /// <para>
  27. /// Control the byte at the caret for editing by setting the <see cref="Address"/> property to an offset in the
  28. /// stream.
  29. /// </para>
  30. /// <para>Control the first byte shown by setting the <see cref="DisplayStart"/> property to an offset in the stream.</para>
  31. /// </remarks>
  32. public class HexView : View, IDesignable
  33. {
  34. private const int DEFAULT_ADDRESS_WIDTH = 8; // The default value for AddressWidth
  35. private const int NUM_BYTES_PER_HEX_COLUMN = 4;
  36. private const int HEX_COLUMN_WIDTH = NUM_BYTES_PER_HEX_COLUMN * 3 + 2; // 3 cols per byte + 1 for vert separator + right space
  37. private bool _firstNibble;
  38. private bool _leftSideHasFocus;
  39. private static readonly Rune _spaceCharRune = new (' ');
  40. private static readonly Rune _periodCharRune = Glyphs.DottedSquare;
  41. private static readonly Rune _columnSeparatorRune = Glyphs.VLineDa4;
  42. /// <summary>Initializes a <see cref="HexView"/> class.</summary>
  43. /// <param name="source">
  44. /// The <see cref="Stream"/> to view and edit as hex, this <see cref="Stream"/> must support seeking,
  45. /// or an exception will be thrown.
  46. /// </param>
  47. public HexView (Stream? source)
  48. {
  49. Source = source;
  50. CanFocus = true;
  51. CursorVisibility = CursorVisibility.Default;
  52. _leftSideHasFocus = true;
  53. _firstNibble = true;
  54. // PERF: Closure capture of 'this' creates a lot of overhead.
  55. // BUG: Closure capture of 'this' may have unexpected results depending on how this is called.
  56. // The above two comments apply to all the lambdas passed to all calls to AddCommand below.
  57. AddCommand (Command.Left, () => MoveLeft ());
  58. AddCommand (Command.Right, () => MoveRight ());
  59. AddCommand (Command.Down, () => MoveDown (BytesPerLine));
  60. AddCommand (Command.Up, () => MoveUp (BytesPerLine));
  61. AddCommand (Command.Tab, () => Navigate (NavigationDirection.Forward));
  62. AddCommand (Command.BackTab, () => Navigate (NavigationDirection.Backward));
  63. AddCommand (Command.PageUp, () => MoveUp (BytesPerLine * Viewport.Height));
  64. AddCommand (Command.PageDown, () => MoveDown (BytesPerLine * Viewport.Height));
  65. AddCommand (Command.Start, () => MoveHome ());
  66. AddCommand (Command.End, () => MoveEnd ());
  67. AddCommand (Command.LeftStart, () => MoveLeftStart ());
  68. AddCommand (Command.RightEnd, () => MoveEndOfLine ());
  69. AddCommand (Command.StartOfPage, () => MoveUp (BytesPerLine * ((int)(Address - _displayStart) / BytesPerLine)));
  70. AddCommand (
  71. Command.EndOfPage,
  72. () => MoveDown (BytesPerLine * (Viewport.Height - 1 - (int)(Address - _displayStart) / BytesPerLine))
  73. );
  74. AddCommand (Command.DeleteCharLeft, () => true);
  75. AddCommand (Command.DeleteCharRight, () => true);
  76. AddCommand (Command.Insert, () => true);
  77. KeyBindings.Add (Key.CursorLeft, Command.Left);
  78. KeyBindings.Add (Key.CursorRight, Command.Right);
  79. KeyBindings.Add (Key.CursorDown, Command.Down);
  80. KeyBindings.Add (Key.CursorUp, Command.Up);
  81. KeyBindings.Add (Key.PageUp, Command.PageUp);
  82. KeyBindings.Add (Key.PageDown, Command.PageDown);
  83. KeyBindings.Add (Key.Home, Command.Start);
  84. KeyBindings.Add (Key.End, Command.End);
  85. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.LeftStart);
  86. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.RightEnd);
  87. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.StartOfPage);
  88. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.EndOfPage);
  89. KeyBindings.Add (Key.Tab, Command.Tab);
  90. KeyBindings.Add (Key.Tab.WithShift, Command.BackTab);
  91. KeyBindings.Add (Key.Backspace, Command.DeleteCharLeft);
  92. KeyBindings.Add (Key.Delete, Command.DeleteCharRight);
  93. KeyBindings.Add (Key.InsertChar, Command.Insert);
  94. KeyBindings.Remove (Key.Space);
  95. KeyBindings.Remove (Key.Enter);
  96. LayoutComplete += HexView_LayoutComplete;
  97. }
  98. /// <summary>Initializes a <see cref="HexView"/> class.</summary>
  99. public HexView () : this (new MemoryStream ()) { }
  100. /// <summary>
  101. /// Gets or sets whether this <see cref="HexView"/> allows editing of the <see cref="Stream"/> of the underlying
  102. /// <see cref="Stream"/>.
  103. /// </summary>
  104. /// <value><c>true</c> to allow edits; otherwise, <c>false</c>.</value>
  105. public bool AllowEdits { get; set; } = true;
  106. /// <summary>Gets the current edit position.</summary>
  107. public Point Position
  108. {
  109. get
  110. {
  111. if (_source is null || BytesPerLine == 0)
  112. {
  113. return Point.Empty;
  114. }
  115. var delta = (int)Address;
  116. int line = delta / BytesPerLine;
  117. int item = delta % BytesPerLine;
  118. return new (item, line);
  119. }
  120. }
  121. ///<inheritdoc/>
  122. public override Point? PositionCursor ()
  123. {
  124. var delta = (int)(Address - _displayStart);
  125. int line = delta / BytesPerLine;
  126. int item = delta % BytesPerLine;
  127. int block = item / NUM_BYTES_PER_HEX_COLUMN;
  128. int column = item % NUM_BYTES_PER_HEX_COLUMN * 3;
  129. int x = GetLeftSideStartColumn () + block * HEX_COLUMN_WIDTH + column + (_firstNibble ? 0 : 1);
  130. int y = line;
  131. if (!_leftSideHasFocus)
  132. {
  133. x = GetLeftSideStartColumn () + BytesPerLine / NUM_BYTES_PER_HEX_COLUMN * HEX_COLUMN_WIDTH + item - 1;
  134. }
  135. Move (x, y);
  136. return new (x, y);
  137. }
  138. private SortedDictionary<long, byte> _edits = [];
  139. /// <summary>
  140. /// Gets a <see cref="SortedDictionary{TKey, TValue}"/> describing the edits done to the <see cref="HexView"/>.
  141. /// Each Key indicates an offset where an edit was made and the Value is the changed byte.
  142. /// </summary>
  143. /// <value>The edits.</value>
  144. public IReadOnlyDictionary<long, byte> Edits => _edits;
  145. private Stream? _source;
  146. /// <summary>
  147. /// Sets or gets the <see cref="Stream"/> the <see cref="HexView"/> is operating on; the stream must support
  148. /// seeking ( <see cref="Stream.CanSeek"/> == true).
  149. /// </summary>
  150. /// <value>The source.</value>
  151. public Stream? Source
  152. {
  153. get => _source;
  154. set
  155. {
  156. ArgumentNullException.ThrowIfNull (value);
  157. if (!value!.CanSeek)
  158. {
  159. throw new ArgumentException (@"The source stream must be seekable (CanSeek property)");
  160. }
  161. _source = value;
  162. if (_displayStart > _source.Length)
  163. {
  164. DisplayStart = 0;
  165. }
  166. if (Address > _source.Length)
  167. {
  168. Address = 0;
  169. }
  170. SetNeedsDisplay ();
  171. }
  172. }
  173. private int _bpl;
  174. /// <summary>The bytes length per line.</summary>
  175. public int BytesPerLine
  176. {
  177. get => _bpl;
  178. set
  179. {
  180. _bpl = value;
  181. RaisePositionChanged ();
  182. }
  183. }
  184. private long _address;
  185. /// <summary>Gets or sets the current byte position in the <see cref="Stream"/>.</summary>
  186. public long Address
  187. {
  188. get => _address;
  189. set
  190. {
  191. if (_address == value)
  192. {
  193. return;
  194. }
  195. //ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual (value, Source!.Length, $"Position");
  196. _address = value;
  197. RaisePositionChanged ();
  198. }
  199. }
  200. private long _displayStart;
  201. // TODO: Use Viewport content scrolling instead
  202. /// <summary>
  203. /// Sets or gets the offset into the <see cref="Stream"/> that will be displayed at the top of the
  204. /// <see cref="HexView"/>.
  205. /// </summary>
  206. /// <value>The display start.</value>
  207. public long DisplayStart
  208. {
  209. get => _displayStart;
  210. set
  211. {
  212. Address = value;
  213. SetDisplayStart (value);
  214. }
  215. }
  216. private int _addressWidth = DEFAULT_ADDRESS_WIDTH;
  217. /// <summary>
  218. /// Gets or sets the width of the Address column on the left. Set to 0 to hide. The default is 8.
  219. /// </summary>
  220. public int AddressWidth
  221. {
  222. get => _addressWidth;
  223. set
  224. {
  225. if (_addressWidth == value)
  226. {
  227. return;
  228. }
  229. _addressWidth = value;
  230. SetNeedsDisplay ();
  231. }
  232. }
  233. private int GetLeftSideStartColumn () { return AddressWidth == 0 ? 0 : AddressWidth + 1; }
  234. internal void SetDisplayStart (long value)
  235. {
  236. if (value > 0 && value >= _source?.Length)
  237. {
  238. _displayStart = _source.Length - 1;
  239. }
  240. else if (value < 0)
  241. {
  242. _displayStart = 0;
  243. }
  244. else
  245. {
  246. _displayStart = value;
  247. }
  248. SetNeedsDisplay ();
  249. }
  250. /// <summary>
  251. /// Applies and edits made to the <see cref="Stream"/> and resets the contents of the
  252. /// <see cref="Edits"/> property.
  253. /// </summary>
  254. /// <param name="stream">If provided also applies the changes to the passed <see cref="Stream"/>.</param>
  255. /// .
  256. public void ApplyEdits (Stream? stream = null)
  257. {
  258. foreach (KeyValuePair<long, byte> kv in _edits)
  259. {
  260. _source!.Position = kv.Key;
  261. _source.WriteByte (kv.Value);
  262. _source.Flush ();
  263. if (stream is { })
  264. {
  265. stream.Position = kv.Key;
  266. stream.WriteByte (kv.Value);
  267. stream.Flush ();
  268. }
  269. }
  270. _edits = new ();
  271. SetNeedsDisplay ();
  272. }
  273. /// <summary>
  274. /// Discards the edits made to the <see cref="Stream"/> by resetting the contents of the
  275. /// <see cref="Edits"/> property.
  276. /// </summary>
  277. public void DiscardEdits () { _edits = new (); }
  278. /// <inheritdoc/>
  279. protected internal override bool OnMouseEvent (MouseEvent me)
  280. {
  281. if (_source is null)
  282. {
  283. return false;
  284. }
  285. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  286. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  287. && !me.Flags.HasFlag (MouseFlags.WheeledDown)
  288. && !me.Flags.HasFlag (MouseFlags.WheeledUp))
  289. {
  290. return false;
  291. }
  292. if (!HasFocus)
  293. {
  294. SetFocus ();
  295. }
  296. if (me.Flags == MouseFlags.WheeledDown)
  297. {
  298. DisplayStart = Math.Min (DisplayStart + BytesPerLine, _source.Length);
  299. return true;
  300. }
  301. if (me.Flags == MouseFlags.WheeledUp)
  302. {
  303. DisplayStart = Math.Max (DisplayStart - BytesPerLine, 0);
  304. return true;
  305. }
  306. if (me.Position.X < GetLeftSideStartColumn ())
  307. {
  308. return true;
  309. }
  310. int nblocks = BytesPerLine / NUM_BYTES_PER_HEX_COLUMN;
  311. int blocksSize = nblocks * HEX_COLUMN_WIDTH;
  312. int blocksRightOffset = GetLeftSideStartColumn () + blocksSize - 1;
  313. if (me.Position.X > blocksRightOffset + BytesPerLine - 1)
  314. {
  315. return true;
  316. }
  317. bool clickIsOnLeftSide = me.Position.X >= blocksRightOffset;
  318. long lineStart = me.Position.Y * BytesPerLine + _displayStart;
  319. int x = me.Position.X - GetLeftSideStartColumn () + 1;
  320. int block = x / HEX_COLUMN_WIDTH;
  321. x -= block * 2;
  322. int empty = x % 3;
  323. int item = x / 3;
  324. if (!clickIsOnLeftSide && item > 0 && (empty == 0 || x == block * HEX_COLUMN_WIDTH + HEX_COLUMN_WIDTH - 1 - block * 2))
  325. {
  326. return true;
  327. }
  328. _firstNibble = true;
  329. if (clickIsOnLeftSide)
  330. {
  331. Address = Math.Min (lineStart + me.Position.X - blocksRightOffset, _source.Length - 1);
  332. }
  333. else
  334. {
  335. Address = Math.Min (lineStart + item, _source.Length - 1);
  336. }
  337. if (me.Flags == MouseFlags.Button1DoubleClicked)
  338. {
  339. _leftSideHasFocus = !clickIsOnLeftSide;
  340. if (_leftSideHasFocus)
  341. {
  342. _firstNibble = empty == 1;
  343. }
  344. else
  345. {
  346. _firstNibble = true;
  347. }
  348. }
  349. SetNeedsDisplay ();
  350. return true;
  351. }
  352. ///<inheritdoc/>
  353. public override void OnDrawContent (Rectangle viewport)
  354. {
  355. if (Source is null)
  356. {
  357. return;
  358. }
  359. Attribute currentAttribute;
  360. Attribute current = GetFocusColor ();
  361. Driver.SetAttribute (current);
  362. Move (0, 0);
  363. int nblocks = BytesPerLine / NUM_BYTES_PER_HEX_COLUMN;
  364. var data = new byte [nblocks * NUM_BYTES_PER_HEX_COLUMN * viewport.Height];
  365. Source.Position = _displayStart;
  366. int n = _source.Read (data, 0, data.Length);
  367. Attribute activeColor = GetHotNormalColor ();
  368. Attribute trackingColor = GetHotFocusColor ();
  369. for (var line = 0; line < viewport.Height; line++)
  370. {
  371. Rectangle lineRect = new (0, line, viewport.Width, 1);
  372. if (!Viewport.Contains (lineRect))
  373. {
  374. continue;
  375. }
  376. Move (0, line);
  377. currentAttribute = GetHotNormalColor ();
  378. Driver.SetAttribute (currentAttribute);
  379. var address = $"{_displayStart + line * nblocks * NUM_BYTES_PER_HEX_COLUMN:x8}";
  380. Driver.AddStr ($"{address.Substring (8 - AddressWidth)}");
  381. if (AddressWidth > 0)
  382. {
  383. Driver.AddStr (" ");
  384. }
  385. SetAttribute (GetNormalColor ());
  386. for (var block = 0; block < nblocks; block++)
  387. {
  388. for (var b = 0; b < NUM_BYTES_PER_HEX_COLUMN; b++)
  389. {
  390. int offset = line * nblocks * NUM_BYTES_PER_HEX_COLUMN + block * NUM_BYTES_PER_HEX_COLUMN + b;
  391. byte value = GetData (data, offset, out bool edited);
  392. if (offset + _displayStart == Address || edited)
  393. {
  394. SetAttribute (_leftSideHasFocus ? activeColor : trackingColor);
  395. }
  396. else
  397. {
  398. SetAttribute (GetNormalColor ());
  399. }
  400. Driver.AddStr (offset >= n && !edited ? " " : $"{value:x2}");
  401. SetAttribute (GetNormalColor ());
  402. Driver.AddRune (_spaceCharRune);
  403. }
  404. Driver.AddStr (block + 1 == nblocks ? " " : $"{_columnSeparatorRune} ");
  405. }
  406. for (var bitem = 0; bitem < nblocks * NUM_BYTES_PER_HEX_COLUMN; bitem++)
  407. {
  408. int offset = line * nblocks * NUM_BYTES_PER_HEX_COLUMN + bitem;
  409. byte b = GetData (data, offset, out bool edited);
  410. Rune c;
  411. var utf8BytesConsumed = 0;
  412. if (offset >= n && !edited)
  413. {
  414. c = _spaceCharRune;
  415. }
  416. else
  417. {
  418. switch (b)
  419. {
  420. //case < 32:
  421. // c = _periodCharRune;
  422. // break;
  423. case > 127:
  424. {
  425. var utf8 = GetData (data, offset, 4, out bool _);
  426. OperationStatus status = Rune.DecodeFromUtf8 (utf8, out c, out utf8BytesConsumed);
  427. while (status == OperationStatus.NeedMoreData)
  428. {
  429. status = Rune.DecodeFromUtf8 (utf8, out c, out utf8BytesConsumed);
  430. }
  431. break;
  432. }
  433. default:
  434. Rune.DecodeFromUtf8 (new (ref b), out c, out _);
  435. break;
  436. }
  437. }
  438. if (offset + _displayStart == Address || edited)
  439. {
  440. SetAttribute (_leftSideHasFocus ? trackingColor : activeColor);
  441. }
  442. else
  443. {
  444. SetAttribute (GetNormalColor ());
  445. }
  446. Driver.AddRune (c);
  447. for (var i = 1; i < utf8BytesConsumed; i++)
  448. {
  449. bitem++;
  450. Driver.AddRune (_periodCharRune);
  451. }
  452. }
  453. }
  454. void SetAttribute (Attribute attribute)
  455. {
  456. if (currentAttribute != attribute)
  457. {
  458. currentAttribute = attribute;
  459. Driver.SetAttribute (attribute);
  460. }
  461. }
  462. }
  463. /// <summary>Raises the <see cref="Edited"/> event.</summary>
  464. protected void RaiseEdited (HexViewEditEventArgs e)
  465. {
  466. OnEdited (e);
  467. Edited?.Invoke (this, e);
  468. }
  469. /// <summary>Event to be invoked when an edit is made on the <see cref="Stream"/>.</summary>
  470. public event EventHandler<HexViewEditEventArgs>? Edited;
  471. /// <summary>
  472. /// </summary>
  473. /// <param name="e"></param>
  474. protected virtual void OnEdited (HexViewEditEventArgs e) { }
  475. /// <summary>
  476. /// Call this when <see cref="Position"/> (and <see cref="Address"/>) has changed. Raises the
  477. /// <see cref="PositionChanged"/> event.
  478. /// </summary>
  479. protected void RaisePositionChanged ()
  480. {
  481. HexViewEventArgs args = new (Address, Position, BytesPerLine);
  482. OnPositionChanged (args);
  483. PositionChanged?.Invoke (this, args);
  484. }
  485. /// <summary>
  486. /// Called when <see cref="Position"/> (and <see cref="Address"/>) has changed.
  487. /// </summary>
  488. protected virtual void OnPositionChanged (HexViewEventArgs e) { }
  489. /// <summary>Raised when <see cref="Position"/> (and <see cref="Address"/>) has changed.</summary>
  490. public event EventHandler<HexViewEventArgs>? PositionChanged;
  491. /// <inheritdoc/>
  492. public override bool OnProcessKeyDown (Key keyEvent)
  493. {
  494. if (!AllowEdits || _source is null)
  495. {
  496. return false;
  497. }
  498. if (_leftSideHasFocus)
  499. {
  500. int value;
  501. var k = (char)keyEvent.KeyCode;
  502. if (!char.IsAsciiDigit ((char)keyEvent.KeyCode))
  503. {
  504. return false;
  505. }
  506. if (k is >= 'A' and <= 'F')
  507. {
  508. value = k - 'A' + 10;
  509. }
  510. else if (k is >= 'a' and <= 'f')
  511. {
  512. value = k - 'a' + 10;
  513. }
  514. else if (k is >= '0' and <= '9')
  515. {
  516. value = k - '0';
  517. }
  518. else
  519. {
  520. return false;
  521. }
  522. if (!_edits.TryGetValue (Address, out byte b))
  523. {
  524. _source.Position = Address;
  525. b = (byte)_source.ReadByte ();
  526. }
  527. // BUGBUG: This makes no sense here.
  528. RedisplayLine (Address);
  529. if (_firstNibble)
  530. {
  531. _firstNibble = false;
  532. b = (byte)((b & 0xf) | (value << NUM_BYTES_PER_HEX_COLUMN));
  533. _edits [Address] = b;
  534. RaiseEdited (new (Address, _edits [Address]));
  535. }
  536. else
  537. {
  538. b = (byte)((b & 0xf0) | value);
  539. _edits [Address] = b;
  540. RaiseEdited (new (Address, _edits [Address]));
  541. MoveRight ();
  542. }
  543. return true;
  544. }
  545. keyEvent = keyEvent.NoAlt.NoCtrl;
  546. Rune r = keyEvent.AsRune;
  547. if (Rune.IsControl (r))
  548. {
  549. return false;
  550. }
  551. var utf8 = new byte [4];
  552. // If the rune is a wide char, encode as utf8
  553. if (r.TryEncodeToUtf8 (utf8, out int bytesWritten))
  554. {
  555. if (bytesWritten > 1)
  556. {
  557. bytesWritten = 4;
  558. }
  559. for (var utfIndex = 0; utfIndex < bytesWritten; utfIndex++)
  560. {
  561. _edits [Address] = utf8 [utfIndex];
  562. RaiseEdited (new (Address, _edits [Address]));
  563. MoveRight ();
  564. }
  565. }
  566. else
  567. {
  568. _edits [Address] = (byte)r.Value;
  569. RaiseEdited (new (Address, _edits [Address]));
  570. MoveRight ();
  571. }
  572. return true;
  573. }
  574. //
  575. // This is used to support editing of the buffer on a peer List<>,
  576. // the offset corresponds to an offset relative to DisplayStart, and
  577. // the buffer contains the contents of a screenful of data, so the
  578. // offset is relative to the buffer.
  579. //
  580. //
  581. private byte GetData (byte [] buffer, int offset, out bool edited)
  582. {
  583. long pos = DisplayStart + offset;
  584. if (_edits.TryGetValue (pos, out byte v))
  585. {
  586. edited = true;
  587. return v;
  588. }
  589. edited = false;
  590. return buffer [offset];
  591. }
  592. private byte [] GetData (byte [] buffer, int offset, int count, out bool edited)
  593. {
  594. var returnBytes = new byte [count];
  595. edited = false;
  596. long pos = DisplayStart + offset;
  597. for (long i = pos; i < pos + count; i++)
  598. {
  599. if (_edits.TryGetValue (i, out byte v))
  600. {
  601. edited = true;
  602. returnBytes [i - pos] = v;
  603. }
  604. else
  605. {
  606. if (pos < buffer.Length - 1)
  607. {
  608. returnBytes [i - pos] = buffer [pos];
  609. }
  610. }
  611. }
  612. return returnBytes;
  613. }
  614. private void HexView_LayoutComplete (object? sender, LayoutEventArgs e)
  615. {
  616. // Small buffers will just show the position, with the bsize field value (4 bytes)
  617. BytesPerLine = NUM_BYTES_PER_HEX_COLUMN;
  618. if (Viewport.Width - GetLeftSideStartColumn () >= HEX_COLUMN_WIDTH)
  619. {
  620. BytesPerLine = Math.Max (
  621. NUM_BYTES_PER_HEX_COLUMN,
  622. NUM_BYTES_PER_HEX_COLUMN * ((Viewport.Width - GetLeftSideStartColumn ()) / (HEX_COLUMN_WIDTH + NUM_BYTES_PER_HEX_COLUMN)));
  623. }
  624. }
  625. private bool MoveDown (int bytes)
  626. {
  627. RedisplayLine (Address);
  628. if (Address + bytes < GetEditedSize ())
  629. {
  630. // We can move down lines cleanly (without extending stream)
  631. Address += bytes;
  632. }
  633. else if ((bytes == BytesPerLine * Viewport.Height && _source.Length >= DisplayStart + BytesPerLine * Viewport.Height)
  634. || (bytes <= BytesPerLine * Viewport.Height - BytesPerLine
  635. && _source.Length <= DisplayStart + BytesPerLine * Viewport.Height))
  636. {
  637. long p = Address;
  638. // This lets address go past the end of the stream one, enabling adding to the stream.
  639. while (p + BytesPerLine <= GetEditedSize ())
  640. {
  641. p += BytesPerLine;
  642. }
  643. Address = p;
  644. }
  645. if (Address >= DisplayStart + BytesPerLine * Viewport.Height)
  646. {
  647. SetDisplayStart (DisplayStart + bytes);
  648. SetNeedsDisplay ();
  649. }
  650. else
  651. {
  652. RedisplayLine (Address);
  653. }
  654. return true;
  655. }
  656. private bool MoveEnd ()
  657. {
  658. // This lets address go past the end of the stream one, enabling adding to the stream.
  659. Address = GetEditedSize ();
  660. if (Address >= DisplayStart + BytesPerLine * Viewport.Height)
  661. {
  662. SetDisplayStart (Address);
  663. SetNeedsDisplay ();
  664. }
  665. else
  666. {
  667. RedisplayLine (Address);
  668. }
  669. return true;
  670. }
  671. private bool MoveEndOfLine ()
  672. {
  673. // This lets address go past the end of the stream one, enabling adding to the stream.
  674. Address = Math.Min (Address / BytesPerLine * BytesPerLine + BytesPerLine - 1, GetEditedSize ());
  675. SetNeedsDisplay ();
  676. return true;
  677. }
  678. private bool MoveHome ()
  679. {
  680. DisplayStart = 0;
  681. SetNeedsDisplay ();
  682. return true;
  683. }
  684. private bool MoveLeft ()
  685. {
  686. RedisplayLine (Address);
  687. if (_leftSideHasFocus)
  688. {
  689. if (!_firstNibble)
  690. {
  691. _firstNibble = true;
  692. return true;
  693. }
  694. _firstNibble = false;
  695. }
  696. if (Address == 0)
  697. {
  698. return true;
  699. }
  700. if (Address - 1 < DisplayStart)
  701. {
  702. SetDisplayStart (_displayStart - BytesPerLine);
  703. SetNeedsDisplay ();
  704. }
  705. else
  706. {
  707. RedisplayLine (Address);
  708. }
  709. Address--;
  710. return true;
  711. }
  712. private bool MoveRight ()
  713. {
  714. RedisplayLine (Address);
  715. if (_leftSideHasFocus)
  716. {
  717. if (_firstNibble)
  718. {
  719. _firstNibble = false;
  720. return true;
  721. }
  722. _firstNibble = true;
  723. }
  724. // This lets address go past the end of the stream one, enabling adding to the stream.
  725. if (Address < GetEditedSize ())
  726. {
  727. Address++;
  728. }
  729. if (Address >= DisplayStart + BytesPerLine * Viewport.Height)
  730. {
  731. SetDisplayStart (DisplayStart + BytesPerLine);
  732. SetNeedsDisplay ();
  733. }
  734. else
  735. {
  736. RedisplayLine (Address);
  737. }
  738. return true;
  739. }
  740. private long GetEditedSize ()
  741. {
  742. if (_edits.Count == 0)
  743. {
  744. return _source!.Length;
  745. }
  746. long maxEditAddress = _edits.Keys.Max ();
  747. return Math.Max (_source!.Length, maxEditAddress + 1);
  748. }
  749. private bool MoveLeftStart ()
  750. {
  751. Address = Address / BytesPerLine * BytesPerLine;
  752. SetNeedsDisplay ();
  753. return true;
  754. }
  755. private bool MoveUp (int bytes)
  756. {
  757. RedisplayLine (Address);
  758. if (Address - bytes > -1)
  759. {
  760. Address -= bytes;
  761. }
  762. if (Address < DisplayStart)
  763. {
  764. SetDisplayStart (DisplayStart - bytes);
  765. SetNeedsDisplay ();
  766. }
  767. else
  768. {
  769. RedisplayLine (Address);
  770. }
  771. return true;
  772. }
  773. private void RedisplayLine (long pos)
  774. {
  775. if (BytesPerLine == 0)
  776. {
  777. return;
  778. }
  779. var delta = (int)(pos - DisplayStart);
  780. int line = delta / BytesPerLine;
  781. SetNeedsDisplay (new (0, line, Viewport.Width, 1));
  782. }
  783. private bool Navigate (NavigationDirection direction)
  784. {
  785. switch (direction)
  786. {
  787. case NavigationDirection.Forward:
  788. _leftSideHasFocus = !_leftSideHasFocus;
  789. RedisplayLine (Address);
  790. _firstNibble = true;
  791. return true;
  792. case NavigationDirection.Backward:
  793. _leftSideHasFocus = !_leftSideHasFocus;
  794. RedisplayLine (Address);
  795. _firstNibble = true;
  796. return true;
  797. }
  798. return false;
  799. }
  800. /// <inheritdoc/>
  801. bool IDesignable.EnableForDesign ()
  802. {
  803. Source = new MemoryStream (Encoding.UTF8.GetBytes ("HexView data with wide codepoints: 𝔹Aℝ𝔽!"));
  804. return true;
  805. }
  806. }