HexView.cs 27 KB

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