HexView.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. //
  2. // HexView.cs: A hexadecimal viewer
  3. //
  4. // TODO: Support searching and highlighting of the search result
  5. // TODO: Support shrinking the stream (e.g. del/backspace should work).
  6. //
  7. using System.Buffers;
  8. namespace Terminal.Gui.Views;
  9. /// <summary>
  10. /// Provides a hex editor with the left side
  11. /// showing the hex values of the bytes in a `Stream` and the right side showing the contents
  12. /// (filtered
  13. /// to printable Unicode glyphs).
  14. /// </summary>
  15. /// <remarks>
  16. /// <para>Users can switch from one side to the other by using the tab key.</para>
  17. /// <para>
  18. /// To enable editing, set <see cref="ReadOnly"/> to true. When <see cref="ReadOnly"/> is true the user can
  19. /// make changes to the hexadecimal values of the <see cref="Stream"/>. Any changes are tracked in the
  20. /// <see cref="Edits"/> property (a <see cref="SortedDictionary{TKey, TValue}"/>) indicating the position where the
  21. /// changes were made and the new values. A convenience method, <see cref="ApplyEdits"/> will apply the edits to
  22. /// the <see cref="Stream"/>.
  23. /// </para>
  24. /// <para>
  25. /// Control the byte at the caret for editing by setting the <see cref="Address"/> property to an offset in the
  26. /// stream.
  27. /// </para>
  28. /// </remarks>
  29. public class HexView : View, IDesignable
  30. {
  31. private const int DEFAULT_ADDRESS_WIDTH = 8; // The default value for AddressWidth
  32. private const int NUM_BYTES_PER_HEX_COLUMN = 4;
  33. private const int HEX_COLUMN_WIDTH = NUM_BYTES_PER_HEX_COLUMN * 3 + 2; // 3 cols per byte + 1 for vert separator + right space
  34. private bool _firstNibble;
  35. private bool _leftSideHasFocus;
  36. private static readonly Rune _spaceCharRune = new (' ');
  37. private static readonly Rune _periodCharRune = Glyphs.DottedSquare;
  38. private static readonly Rune _columnSeparatorRune = Glyphs.VLineDa4;
  39. /// <summary>Initializes a <see cref="HexView"/> class.</summary>
  40. /// <param name="source">
  41. /// The <see cref="Stream"/> to view and edit as hex, this <see cref="Stream"/> must support seeking,
  42. /// or an exception will be thrown.
  43. /// </param>
  44. public HexView (Stream? source)
  45. {
  46. Source = source;
  47. CanFocus = true;
  48. CursorVisibility = CursorVisibility.Default;
  49. _leftSideHasFocus = true;
  50. _firstNibble = true;
  51. AddCommand (Command.Select, HandleMouseClick);
  52. AddCommand (Command.Left, () => MoveLeft ());
  53. AddCommand (Command.Right, () => MoveRight ());
  54. AddCommand (Command.Down, () => MoveDown (BytesPerLine));
  55. AddCommand (Command.Up, () => MoveUp (BytesPerLine));
  56. AddCommand (Command.PageUp, () => MoveUp (BytesPerLine * Viewport.Height));
  57. AddCommand (Command.PageDown, () => MoveDown (BytesPerLine * Viewport.Height));
  58. AddCommand (Command.Start, () => MoveHome ());
  59. AddCommand (Command.End, () => MoveEnd ());
  60. AddCommand (Command.LeftStart, () => MoveLeftStart ());
  61. AddCommand (Command.RightEnd, () => MoveEndOfLine ());
  62. AddCommand (Command.StartOfPage, () => MoveUp (BytesPerLine * ((int)(Address - Viewport.Y) / BytesPerLine)));
  63. AddCommand (
  64. Command.EndOfPage,
  65. () => MoveDown (BytesPerLine * (Viewport.Height - 1 - (int)(Address - Viewport.Y) / BytesPerLine))
  66. );
  67. AddCommand (Command.ScrollDown, () => ScrollVertical (1));
  68. AddCommand (Command.ScrollUp, () => ScrollVertical (-1));
  69. AddCommand (Command.DeleteCharLeft, () => true);
  70. AddCommand (Command.DeleteCharRight, () => true);
  71. AddCommand (Command.Insert, () => true);
  72. KeyBindings.Add (Key.CursorLeft, Command.Left);
  73. KeyBindings.Add (Key.CursorRight, Command.Right);
  74. KeyBindings.Add (Key.CursorDown, Command.Down);
  75. KeyBindings.Add (Key.CursorUp, Command.Up);
  76. KeyBindings.Add (Key.PageUp, Command.PageUp);
  77. KeyBindings.Add (Key.PageDown, Command.PageDown);
  78. KeyBindings.Add (Key.Home, Command.Start);
  79. KeyBindings.Add (Key.End, Command.End);
  80. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.LeftStart);
  81. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.RightEnd);
  82. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.StartOfPage);
  83. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.EndOfPage);
  84. KeyBindings.Add (Key.Backspace, Command.DeleteCharLeft);
  85. KeyBindings.Add (Key.Delete, Command.DeleteCharRight);
  86. KeyBindings.Add (Key.InsertChar, Command.Insert);
  87. KeyBindings.Remove (Key.Space);
  88. KeyBindings.Remove (Key.Enter);
  89. // The Select handler deals with both single and double clicks
  90. MouseBindings.ReplaceCommands (MouseFlags.Button1Clicked, Command.Select);
  91. MouseBindings.Add (MouseFlags.Button1DoubleClicked, Command.Select);
  92. MouseBindings.Add (MouseFlags.WheeledUp, Command.ScrollUp);
  93. MouseBindings.Add (MouseFlags.WheeledDown, Command.ScrollDown);
  94. SubViewsLaidOut += HexViewSubViewsLaidOut;
  95. }
  96. private void HexViewSubViewsLaidOut (object? sender, LayoutEventArgs e)
  97. {
  98. SetBytesPerLine ();
  99. SetContentSize (
  100. new (
  101. GetLeftSideStartColumn () + BytesPerLine / NUM_BYTES_PER_HEX_COLUMN * HEX_COLUMN_WIDTH + BytesPerLine - 1,
  102. (int)(GetEditedSize () / BytesPerLine) + 1));
  103. }
  104. /// <summary>Initializes a <see cref="HexView"/> class.</summary>
  105. public HexView () : this (new MemoryStream ()) { }
  106. /// <summary>
  107. /// Gets or sets whether this <see cref="HexView"/> allows editing of the <see cref="Stream"/> of the underlying
  108. /// <see cref="Stream"/>. The default is <see langword="false"/>.
  109. /// </summary>
  110. public bool ReadOnly { get; set; } = false;
  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. long line = address / BytesPerLine;
  120. long 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 (DrawContext? context)
  359. {
  360. if (Source is null)
  361. {
  362. return true;
  363. }
  364. long addressOfFirstLine = Viewport.Y * BytesPerLine;
  365. int nBlocks = BytesPerLine / NUM_BYTES_PER_HEX_COLUMN;
  366. var data = new byte [nBlocks * NUM_BYTES_PER_HEX_COLUMN * Viewport.Height];
  367. Source.Position = addressOfFirstLine;
  368. long bytesRead = Source!.Read (data, 0, data.Length);
  369. Attribute selectedAttribute = GetAttributeForRole (VisualRole.Active);
  370. Attribute editedAttribute = GetAttributeForRole (VisualRole.Editable);
  371. editedAttribute = editedAttribute with { Style = editedAttribute.Style | TextStyle.Italic | TextStyle.Underline };
  372. Attribute editingAttribute = GetAttributeForRole (ReadOnly ? VisualRole.ReadOnly : VisualRole.Editable);
  373. Attribute addressAttribute = GetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Active);
  374. for (var line = 0; line < Viewport.Height; line++)
  375. {
  376. int max = -Viewport.X;
  377. Move (max, line);
  378. long addressOfLine = addressOfFirstLine + line * nBlocks * NUM_BYTES_PER_HEX_COLUMN;
  379. if (addressOfLine <= GetEditedSize ())
  380. {
  381. SetAttribute (addressAttribute);
  382. }
  383. else
  384. {
  385. SetAttributeForRole (VisualRole.Disabled);
  386. }
  387. var address = $"{addressOfLine:x8}";
  388. AddStr ($"{address.Substring (8 - AddressWidth)}");
  389. SetAttribute (editingAttribute);
  390. if (AddressWidth > 0)
  391. {
  392. AddStr (" ");
  393. }
  394. for (var block = 0; block < nBlocks; block++)
  395. {
  396. for (var b = 0; b < NUM_BYTES_PER_HEX_COLUMN; b++)
  397. {
  398. int offset = line * nBlocks * NUM_BYTES_PER_HEX_COLUMN + block * NUM_BYTES_PER_HEX_COLUMN + b;
  399. byte value = GetData (data, offset, out bool edited);
  400. if (offset + addressOfFirstLine == Address)
  401. {
  402. // Selected
  403. SetAttribute (_leftSideHasFocus ? editingAttribute : edited ? editedAttribute : GetAttributeForRole (VisualRole.Focus));
  404. }
  405. else
  406. {
  407. SetAttribute (edited ? editedAttribute : editingAttribute);
  408. }
  409. AddStr (offset >= bytesRead && !edited ? " " : $"{value:x2}");
  410. SetAttribute (editingAttribute);
  411. AddRune (_spaceCharRune);
  412. }
  413. AddStr (block + 1 == nBlocks ? " " : $"{_columnSeparatorRune} ");
  414. }
  415. for (var byteIndex = 0; byteIndex < nBlocks * NUM_BYTES_PER_HEX_COLUMN; byteIndex++)
  416. {
  417. int offset = line * nBlocks * NUM_BYTES_PER_HEX_COLUMN + byteIndex;
  418. byte b = GetData (data, offset, out bool edited);
  419. Rune c;
  420. var utf8BytesConsumed = 0;
  421. if (offset >= bytesRead && !edited)
  422. {
  423. c = _spaceCharRune;
  424. }
  425. else
  426. {
  427. switch (b)
  428. {
  429. //case < 32:
  430. // c = _periodCharRune;
  431. // break;
  432. case > 127:
  433. {
  434. byte [] utf8 = GetData (data, offset, 4, out bool _);
  435. OperationStatus status = Rune.DecodeFromUtf8 (utf8, out c, out utf8BytesConsumed);
  436. while (status == OperationStatus.NeedMoreData)
  437. {
  438. status = Rune.DecodeFromUtf8 (utf8, out c, out utf8BytesConsumed);
  439. }
  440. break;
  441. }
  442. default:
  443. Rune.DecodeFromUtf8 (new (ref b), out c, out _);
  444. break;
  445. }
  446. }
  447. if (offset + Source.Position == Address)
  448. {
  449. // Selected
  450. SetAttribute (_leftSideHasFocus ? editingAttribute : edited ? editedAttribute : selectedAttribute);
  451. }
  452. else
  453. {
  454. SetAttribute (edited ? editedAttribute : editingAttribute);
  455. }
  456. AddRune (c);
  457. for (var i = 1; i < utf8BytesConsumed; i++)
  458. {
  459. byteIndex++;
  460. AddRune (_periodCharRune);
  461. }
  462. }
  463. SetAttribute (editingAttribute);
  464. // Fill rest of line
  465. for (int x = max; x < Viewport.Width; x++)
  466. {
  467. AddRune (new Rune (' '));
  468. }
  469. }
  470. return true;
  471. }
  472. /// <summary>Raises the <see cref="Edited"/> event.</summary>
  473. protected void RaiseEdited (HexViewEditEventArgs e)
  474. {
  475. OnEdited (e);
  476. Edited?.Invoke (this, e);
  477. }
  478. /// <summary>Event to be invoked when an edit is made on the <see cref="Stream"/>.</summary>
  479. public event EventHandler<HexViewEditEventArgs>? Edited;
  480. /// <summary>
  481. /// </summary>
  482. /// <param name="e"></param>
  483. protected virtual void OnEdited (HexViewEditEventArgs e) { }
  484. /// <summary>
  485. /// Call this when the position (see <see cref="GetPosition"/>) and <see cref="Address"/> have changed. Raises the
  486. /// <see cref="PositionChanged"/> event.
  487. /// </summary>
  488. protected void RaisePositionChanged ()
  489. {
  490. HexViewEventArgs args = new (Address, GetPosition (Address), BytesPerLine);
  491. OnPositionChanged (args);
  492. PositionChanged?.Invoke (this, args);
  493. }
  494. /// <summary>
  495. /// Called when the position (see <see cref="GetPosition"/>) and <see cref="Address"/> have changed.
  496. /// </summary>
  497. protected virtual void OnPositionChanged (HexViewEventArgs e) { }
  498. /// <summary>Raised when the position (see <see cref="GetPosition"/>) and <see cref="Address"/> have changed.</summary>
  499. public event EventHandler<HexViewEventArgs>? PositionChanged;
  500. /// <inheritdoc/>
  501. protected override bool OnKeyDownNotHandled (Key keyEvent)
  502. {
  503. if (ReadOnly || _source is null)
  504. {
  505. return false;
  506. }
  507. if (keyEvent.IsAlt)
  508. {
  509. return false;
  510. }
  511. if (_leftSideHasFocus)
  512. {
  513. int value;
  514. var k = (char)keyEvent.KeyCode;
  515. if (!char.IsAsciiHexDigit ((char)keyEvent.KeyCode))
  516. {
  517. return false;
  518. }
  519. if (k is >= 'A' and <= 'F')
  520. {
  521. value = k - 'A' + 10;
  522. }
  523. else if (k is >= 'a' and <= 'f')
  524. {
  525. value = k - 'a' + 10;
  526. }
  527. else if (k is >= '0' and <= '9')
  528. {
  529. value = k - '0';
  530. }
  531. else
  532. {
  533. return false;
  534. }
  535. if (!_edits.TryGetValue (Address, out byte b))
  536. {
  537. _source.Position = Address;
  538. b = (byte)_source.ReadByte ();
  539. }
  540. if (_firstNibble)
  541. {
  542. _firstNibble = false;
  543. b = (byte)((b & 0xf) | (value << NUM_BYTES_PER_HEX_COLUMN));
  544. _edits [Address] = b;
  545. RaiseEdited (new (Address, _edits [Address]));
  546. }
  547. else
  548. {
  549. b = (byte)((b & 0xf0) | value);
  550. _edits [Address] = b;
  551. RaiseEdited (new (Address, _edits [Address]));
  552. MoveRight ();
  553. }
  554. return true;
  555. }
  556. keyEvent = keyEvent.NoAlt.NoCtrl;
  557. Rune r = keyEvent.AsRune;
  558. if (Rune.IsControl (r))
  559. {
  560. return false;
  561. }
  562. var utf8 = new byte [4];
  563. // If the rune is a wide char, encode as utf8
  564. if (r.TryEncodeToUtf8 (utf8, out int bytesWritten))
  565. {
  566. if (bytesWritten > 1)
  567. {
  568. bytesWritten = 4;
  569. }
  570. for (var utfIndex = 0; utfIndex < bytesWritten; utfIndex++)
  571. {
  572. _edits [Address] = utf8 [utfIndex];
  573. RaiseEdited (new (Address, _edits [Address]));
  574. MoveRight ();
  575. }
  576. }
  577. else
  578. {
  579. _edits [Address] = (byte)r.Value;
  580. RaiseEdited (new (Address, _edits [Address]));
  581. MoveRight ();
  582. }
  583. return true;
  584. }
  585. //
  586. // This is used to support editing of the buffer on a peer List<>,
  587. // the offset corresponds to an offset relative to DisplayStart, and
  588. // the buffer contains the contents of a Viewport of data, so the
  589. // offset is relative to the buffer.
  590. //
  591. //
  592. private byte GetData (byte [] buffer, int offset, out bool edited)
  593. {
  594. long pos = Viewport.Y * BytesPerLine + offset;
  595. if (_edits.TryGetValue (pos, out byte v))
  596. {
  597. edited = true;
  598. return v;
  599. }
  600. edited = false;
  601. return buffer [offset];
  602. }
  603. private byte [] GetData (byte [] buffer, int offset, int count, out bool edited)
  604. {
  605. var returnBytes = new byte [count];
  606. edited = false;
  607. long pos = Viewport.Y + offset;
  608. for (long i = pos; i < pos + count; i++)
  609. {
  610. if (_edits.TryGetValue (i, out byte v))
  611. {
  612. edited = true;
  613. returnBytes [i - pos] = v;
  614. }
  615. else
  616. {
  617. if (pos < buffer.Length - 1)
  618. {
  619. returnBytes [i - pos] = buffer [pos];
  620. }
  621. }
  622. }
  623. return returnBytes;
  624. }
  625. private void SetBytesPerLine ()
  626. {
  627. // Small buffers will just show the position, with the bsize field value (4 bytes)
  628. BytesPerLine = NUM_BYTES_PER_HEX_COLUMN;
  629. if (Viewport.Width - GetLeftSideStartColumn () >= HEX_COLUMN_WIDTH)
  630. {
  631. BytesPerLine = Math.Max (
  632. NUM_BYTES_PER_HEX_COLUMN,
  633. NUM_BYTES_PER_HEX_COLUMN * ((Viewport.Width - GetLeftSideStartColumn ()) / (HEX_COLUMN_WIDTH + NUM_BYTES_PER_HEX_COLUMN)));
  634. }
  635. }
  636. private bool MoveDown (int bytes)
  637. {
  638. if (Address + bytes < GetEditedSize ())
  639. {
  640. // We can move down lines cleanly (without extending stream)
  641. Address += bytes;
  642. }
  643. else if ((bytes == BytesPerLine * Viewport.Height && _source!.Length >= Viewport.Y * BytesPerLine + BytesPerLine * Viewport.Height)
  644. || (bytes <= BytesPerLine * Viewport.Height - BytesPerLine
  645. && _source!.Length <= Viewport.Y * BytesPerLine + BytesPerLine * Viewport.Height))
  646. {
  647. long p = Address;
  648. // This lets address go past the end of the stream one, enabling adding to the stream.
  649. while (p + BytesPerLine <= GetEditedSize ())
  650. {
  651. p += BytesPerLine;
  652. }
  653. Address = p;
  654. }
  655. return true;
  656. }
  657. private bool MoveEnd ()
  658. {
  659. // This lets address go past the end of the stream one, enabling adding to the stream.
  660. Address = GetEditedSize ();
  661. return true;
  662. }
  663. private bool MoveEndOfLine ()
  664. {
  665. // This lets address go past the end of the stream one, enabling adding to the stream.
  666. Address = Math.Min (Address / BytesPerLine * BytesPerLine + BytesPerLine - 1, GetEditedSize ());
  667. return true;
  668. }
  669. private bool MoveHome ()
  670. {
  671. Address = 0;
  672. return true;
  673. }
  674. private bool MoveLeft ()
  675. {
  676. if (_leftSideHasFocus)
  677. {
  678. if (!_firstNibble)
  679. {
  680. _firstNibble = true;
  681. return true;
  682. }
  683. _firstNibble = false;
  684. }
  685. if (Address == 0)
  686. {
  687. return true;
  688. }
  689. Address--;
  690. return true;
  691. }
  692. private bool MoveRight ()
  693. {
  694. if (_leftSideHasFocus)
  695. {
  696. if (_firstNibble)
  697. {
  698. _firstNibble = false;
  699. return true;
  700. }
  701. _firstNibble = true;
  702. }
  703. // This lets address go past the end of the stream one, enabling adding to the stream.
  704. if (Address < GetEditedSize ())
  705. {
  706. Address++;
  707. }
  708. return true;
  709. }
  710. private bool MoveLeftStart ()
  711. {
  712. Address = Address / BytesPerLine * BytesPerLine;
  713. return true;
  714. }
  715. private bool MoveUp (int bytes)
  716. {
  717. Address -= bytes;
  718. return true;
  719. }
  720. /// <inheritdoc/>
  721. protected override bool OnAdvancingFocus (NavigationDirection direction, TabBehavior? behavior)
  722. {
  723. if (behavior is { } && behavior != TabStop)
  724. {
  725. return false;
  726. }
  727. if ((direction == NavigationDirection.Forward && _leftSideHasFocus)
  728. || (direction == NavigationDirection.Backward && !_leftSideHasFocus))
  729. {
  730. _leftSideHasFocus = !_leftSideHasFocus;
  731. _firstNibble = true;
  732. SetNeedsDraw ();
  733. return true;
  734. }
  735. return false;
  736. }
  737. /// <inheritdoc/>
  738. bool IDesignable.EnableForDesign ()
  739. {
  740. Source = new MemoryStream (Encoding.UTF8.GetBytes ("HexView data with wide codepoints: 𝔹Aℝ𝔽!"));
  741. return true;
  742. }
  743. }