HexView.cs 28 KB

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