HexView.cs 27 KB

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