HexView.cs 27 KB

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