HexView.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. /// <para>Control the first byte shown by setting the <see cref="DisplayStart"/> property to an offset in the stream.</para>
  31. /// </remarks>
  32. public class HexView : View, IDesignable
  33. {
  34. private const int DEFAULT_ADDRESS_WIDTH = 8; // The default value for AddressWidth
  35. private const int NUM_BYTES_PER_HEX_COLUMN = 4;
  36. private const int HEX_COLUMN_WIDTH = NUM_BYTES_PER_HEX_COLUMN * 3 + 2; // 3 cols per byte + 1 for vert separator + right space
  37. private bool _firstNibble;
  38. private bool _leftSideHasFocus;
  39. private static readonly Rune _spaceCharRune = new (' ');
  40. private static readonly Rune _periodCharRune = Glyphs.DottedSquare;
  41. private static readonly Rune _columnSeparatorRune = Glyphs.VLineDa4;
  42. /// <summary>Initializes a <see cref="HexView"/> class.</summary>
  43. /// <param name="source">
  44. /// The <see cref="Stream"/> to view and edit as hex, this <see cref="Stream"/> must support seeking,
  45. /// or an exception will be thrown.
  46. /// </param>
  47. public HexView (Stream? source)
  48. {
  49. Source = source;
  50. CanFocus = true;
  51. CursorVisibility = CursorVisibility.Default;
  52. _leftSideHasFocus = true;
  53. _firstNibble = true;
  54. // PERF: Closure capture of 'this' creates a lot of overhead.
  55. // BUG: Closure capture of 'this' may have unexpected results depending on how this is called.
  56. // The above two comments apply to all the lambdas passed to all calls to AddCommand below.
  57. AddCommand (Command.Left, () => MoveLeft ());
  58. AddCommand (Command.Right, () => MoveRight ());
  59. AddCommand (Command.Down, () => MoveDown (BytesPerLine));
  60. AddCommand (Command.Up, () => MoveUp (BytesPerLine));
  61. AddCommand (Command.PageUp, () => MoveUp (BytesPerLine * Viewport.Height));
  62. AddCommand (Command.PageDown, () => MoveDown (BytesPerLine * Viewport.Height));
  63. AddCommand (Command.Start, () => MoveHome ());
  64. AddCommand (Command.End, () => MoveEnd ());
  65. AddCommand (Command.LeftStart, () => MoveLeftStart ());
  66. AddCommand (Command.RightEnd, () => MoveEndOfLine ());
  67. AddCommand (Command.StartOfPage, () => MoveUp (BytesPerLine * ((int)(Address - _displayStart) / BytesPerLine)));
  68. AddCommand (
  69. Command.EndOfPage,
  70. () => MoveDown (BytesPerLine * (Viewport.Height - 1 - (int)(Address - _displayStart) / BytesPerLine))
  71. );
  72. AddCommand (Command.DeleteCharLeft, () => true);
  73. AddCommand (Command.DeleteCharRight, () => true);
  74. AddCommand (Command.Insert, () => true);
  75. KeyBindings.Add (Key.CursorLeft, Command.Left);
  76. KeyBindings.Add (Key.CursorRight, Command.Right);
  77. KeyBindings.Add (Key.CursorDown, Command.Down);
  78. KeyBindings.Add (Key.CursorUp, Command.Up);
  79. KeyBindings.Add (Key.PageUp, Command.PageUp);
  80. KeyBindings.Add (Key.PageDown, Command.PageDown);
  81. KeyBindings.Add (Key.Home, Command.Start);
  82. KeyBindings.Add (Key.End, Command.End);
  83. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.LeftStart);
  84. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.RightEnd);
  85. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.StartOfPage);
  86. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.EndOfPage);
  87. KeyBindings.Add (Key.Backspace, Command.DeleteCharLeft);
  88. KeyBindings.Add (Key.Delete, Command.DeleteCharRight);
  89. KeyBindings.Add (Key.InsertChar, Command.Insert);
  90. KeyBindings.Remove (Key.Space);
  91. KeyBindings.Remove (Key.Enter);
  92. SubviewsLaidOut += HexView_LayoutComplete;
  93. }
  94. /// <summary>Initializes a <see cref="HexView"/> class.</summary>
  95. public HexView () : this (new MemoryStream ()) { }
  96. /// <summary>
  97. /// Gets or sets whether this <see cref="HexView"/> allows editing of the <see cref="Stream"/> of the underlying
  98. /// <see cref="Stream"/>.
  99. /// </summary>
  100. /// <value><c>true</c> to allow edits; otherwise, <c>false</c>.</value>
  101. public bool AllowEdits { get; set; } = true;
  102. /// <summary>Gets the current edit position.</summary>
  103. public Point Position
  104. {
  105. get
  106. {
  107. if (_source is null || BytesPerLine == 0)
  108. {
  109. return Point.Empty;
  110. }
  111. var delta = (int)Address;
  112. int line = delta / BytesPerLine;
  113. int item = delta % BytesPerLine;
  114. return new (item, line);
  115. }
  116. }
  117. ///<inheritdoc/>
  118. public override Point? PositionCursor ()
  119. {
  120. var delta = (int)(Address - _displayStart);
  121. int line = delta / BytesPerLine;
  122. int item = delta % BytesPerLine;
  123. int block = item / NUM_BYTES_PER_HEX_COLUMN;
  124. int column = item % NUM_BYTES_PER_HEX_COLUMN * 3;
  125. int x = GetLeftSideStartColumn () + block * HEX_COLUMN_WIDTH + column + (_firstNibble ? 0 : 1);
  126. int y = line;
  127. if (!_leftSideHasFocus)
  128. {
  129. x = GetLeftSideStartColumn () + BytesPerLine / NUM_BYTES_PER_HEX_COLUMN * HEX_COLUMN_WIDTH + item - 1;
  130. }
  131. Move (x, y);
  132. return new (x, y);
  133. }
  134. private SortedDictionary<long, byte> _edits = [];
  135. /// <summary>
  136. /// Gets a <see cref="SortedDictionary{TKey, TValue}"/> describing the edits done to the <see cref="HexView"/>.
  137. /// Each Key indicates an offset where an edit was made and the Value is the changed byte.
  138. /// </summary>
  139. /// <value>The edits.</value>
  140. public IReadOnlyDictionary<long, byte> Edits => _edits;
  141. private Stream? _source;
  142. /// <summary>
  143. /// Sets or gets the <see cref="Stream"/> the <see cref="HexView"/> is operating on; the stream must support
  144. /// seeking ( <see cref="Stream.CanSeek"/> == true).
  145. /// </summary>
  146. /// <value>The source.</value>
  147. public Stream? Source
  148. {
  149. get => _source;
  150. set
  151. {
  152. ArgumentNullException.ThrowIfNull (value);
  153. if (!value!.CanSeek)
  154. {
  155. throw new ArgumentException (@"The source stream must be seekable (CanSeek property)");
  156. }
  157. _source = value;
  158. if (_displayStart > _source.Length)
  159. {
  160. DisplayStart = 0;
  161. }
  162. if (Address > _source.Length)
  163. {
  164. Address = 0;
  165. }
  166. SetNeedsLayout ();
  167. SetNeedsDisplay ();
  168. }
  169. }
  170. private int _bpl;
  171. /// <summary>The bytes length per line.</summary>
  172. public int BytesPerLine
  173. {
  174. get => _bpl;
  175. set
  176. {
  177. _bpl = value;
  178. RaisePositionChanged ();
  179. }
  180. }
  181. private long _address;
  182. /// <summary>Gets or sets the current byte position in the <see cref="Stream"/>.</summary>
  183. public long Address
  184. {
  185. get => _address;
  186. set
  187. {
  188. if (_address == value)
  189. {
  190. return;
  191. }
  192. //ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual (value, Source!.Length, $"Position");
  193. _address = value;
  194. RaisePositionChanged ();
  195. }
  196. }
  197. private long _displayStart;
  198. // TODO: Use Viewport content scrolling instead
  199. /// <summary>
  200. /// Sets or gets the offset into the <see cref="Stream"/> that will be displayed at the top of the
  201. /// <see cref="HexView"/>.
  202. /// </summary>
  203. /// <value>The display start.</value>
  204. public long DisplayStart
  205. {
  206. get => _displayStart;
  207. set
  208. {
  209. Address = value;
  210. SetDisplayStart (value);
  211. }
  212. }
  213. private int _addressWidth = DEFAULT_ADDRESS_WIDTH;
  214. /// <summary>
  215. /// Gets or sets the width of the Address column on the left. Set to 0 to hide. The default is 8.
  216. /// </summary>
  217. public int AddressWidth
  218. {
  219. get => _addressWidth;
  220. set
  221. {
  222. if (_addressWidth == value)
  223. {
  224. return;
  225. }
  226. _addressWidth = value;
  227. SetNeedsDisplay ();
  228. SetNeedsLayout ();
  229. }
  230. }
  231. private int GetLeftSideStartColumn () { return AddressWidth == 0 ? 0 : AddressWidth + 1; }
  232. internal void SetDisplayStart (long value)
  233. {
  234. if (value > 0 && value >= _source?.Length)
  235. {
  236. _displayStart = _source.Length - 1;
  237. }
  238. else if (value < 0)
  239. {
  240. _displayStart = 0;
  241. }
  242. else
  243. {
  244. _displayStart = value;
  245. }
  246. SetNeedsDisplay ();
  247. }
  248. /// <summary>
  249. /// Applies and edits made to the <see cref="Stream"/> and resets the contents of the
  250. /// <see cref="Edits"/> property.
  251. /// </summary>
  252. /// <param name="stream">If provided also applies the changes to the passed <see cref="Stream"/>.</param>
  253. /// .
  254. public void ApplyEdits (Stream? stream = null)
  255. {
  256. foreach (KeyValuePair<long, byte> kv in _edits)
  257. {
  258. _source!.Position = kv.Key;
  259. _source.WriteByte (kv.Value);
  260. _source.Flush ();
  261. if (stream is { })
  262. {
  263. stream.Position = kv.Key;
  264. stream.WriteByte (kv.Value);
  265. stream.Flush ();
  266. }
  267. }
  268. _edits = new ();
  269. SetNeedsDisplay ();
  270. }
  271. /// <summary>
  272. /// Discards the edits made to the <see cref="Stream"/> by resetting the contents of the
  273. /// <see cref="Edits"/> property.
  274. /// </summary>
  275. public void DiscardEdits () { _edits = new (); }
  276. /// <inheritdoc/>
  277. protected override bool OnMouseEvent (MouseEventArgs me)
  278. {
  279. if (_source is null)
  280. {
  281. return false;
  282. }
  283. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  284. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  285. && !me.Flags.HasFlag (MouseFlags.WheeledDown)
  286. && !me.Flags.HasFlag (MouseFlags.WheeledUp))
  287. {
  288. return false;
  289. }
  290. if (!HasFocus)
  291. {
  292. SetFocus ();
  293. }
  294. if (me.Flags == MouseFlags.WheeledDown)
  295. {
  296. DisplayStart = Math.Min (DisplayStart + BytesPerLine, GetEditedSize ());
  297. return true;
  298. }
  299. if (me.Flags == MouseFlags.WheeledUp)
  300. {
  301. DisplayStart = Math.Max (DisplayStart - BytesPerLine, 0);
  302. return true;
  303. }
  304. if (me.Position.X < GetLeftSideStartColumn ())
  305. {
  306. return true;
  307. }
  308. int nblocks = BytesPerLine / NUM_BYTES_PER_HEX_COLUMN;
  309. int blocksSize = nblocks * HEX_COLUMN_WIDTH;
  310. int blocksRightOffset = GetLeftSideStartColumn () + blocksSize - 1;
  311. if (me.Position.X > blocksRightOffset + BytesPerLine - 1)
  312. {
  313. return true;
  314. }
  315. bool clickIsOnLeftSide = me.Position.X >= blocksRightOffset;
  316. long lineStart = me.Position.Y * BytesPerLine + _displayStart;
  317. int x = me.Position.X - GetLeftSideStartColumn () + 1;
  318. int block = x / HEX_COLUMN_WIDTH;
  319. x -= block * 2;
  320. int empty = x % 3;
  321. int item = x / 3;
  322. if (!clickIsOnLeftSide && item > 0 && (empty == 0 || x == block * HEX_COLUMN_WIDTH + HEX_COLUMN_WIDTH - 1 - block * 2))
  323. {
  324. return true;
  325. }
  326. _firstNibble = true;
  327. if (clickIsOnLeftSide)
  328. {
  329. Address = Math.Min (lineStart + me.Position.X - blocksRightOffset, GetEditedSize ());
  330. }
  331. else
  332. {
  333. Address = Math.Min (lineStart + item, GetEditedSize ());
  334. }
  335. if (me.Flags == MouseFlags.Button1DoubleClicked)
  336. {
  337. _leftSideHasFocus = !clickIsOnLeftSide;
  338. if (_leftSideHasFocus)
  339. {
  340. _firstNibble = empty == 1;
  341. }
  342. else
  343. {
  344. _firstNibble = true;
  345. }
  346. }
  347. SetNeedsDisplay ();
  348. return true;
  349. }
  350. ///<inheritdoc/>
  351. protected override bool OnDrawingContent (Rectangle viewport)
  352. {
  353. if (Source is null)
  354. {
  355. return true;
  356. }
  357. Attribute currentAttribute;
  358. Attribute current = GetFocusColor ();
  359. Driver?.SetAttribute (current);
  360. Move (0, 0);
  361. int nBlocks = BytesPerLine / NUM_BYTES_PER_HEX_COLUMN;
  362. var data = new byte [nBlocks * NUM_BYTES_PER_HEX_COLUMN * viewport.Height];
  363. Source.Position = _displayStart;
  364. int n = _source!.Read (data, 0, data.Length);
  365. Attribute selectedAttribute = GetHotNormalColor ();
  366. Attribute editedAttribute = new Attribute (GetNormalColor ().Foreground.GetHighlightColor (), GetNormalColor ().Background);
  367. Attribute editingAttribute = new Attribute (GetFocusColor ().Background, GetFocusColor ().Foreground);
  368. for (var line = 0; line < viewport.Height; line++)
  369. {
  370. Rectangle lineRect = new (0, line, viewport.Width, 1);
  371. if (!Viewport.Contains (lineRect))
  372. {
  373. continue;
  374. }
  375. Move (0, line);
  376. currentAttribute = new Attribute (GetNormalColor ().Foreground.GetHighlightColor (), GetNormalColor ().Background);
  377. Driver?.SetAttribute (currentAttribute);
  378. var address = $"{_displayStart + line * nBlocks * NUM_BYTES_PER_HEX_COLUMN:x8}";
  379. Driver?.AddStr ($"{address.Substring (8 - AddressWidth)}");
  380. if (AddressWidth > 0)
  381. {
  382. Driver?.AddStr (" ");
  383. }
  384. SetAttribute (GetNormalColor ());
  385. for (var block = 0; block < nBlocks; block++)
  386. {
  387. for (var b = 0; b < NUM_BYTES_PER_HEX_COLUMN; b++)
  388. {
  389. int offset = line * nBlocks * NUM_BYTES_PER_HEX_COLUMN + block * NUM_BYTES_PER_HEX_COLUMN + b;
  390. byte value = GetData (data, offset, out bool edited);
  391. if (offset + _displayStart == Address)
  392. {
  393. // Selected
  394. SetAttribute (_leftSideHasFocus ? editingAttribute : (edited ? editedAttribute : selectedAttribute));
  395. }
  396. else
  397. {
  398. SetAttribute (edited ? editedAttribute : GetNormalColor ());
  399. }
  400. Driver?.AddStr (offset >= n && !edited ? " " : $"{value:x2}");
  401. SetAttribute (GetNormalColor ());
  402. Driver?.AddRune (_spaceCharRune);
  403. }
  404. Driver?.AddStr (block + 1 == nBlocks ? " " : $"{_columnSeparatorRune} ");
  405. }
  406. for (var byteIndex = 0; byteIndex < nBlocks * NUM_BYTES_PER_HEX_COLUMN; byteIndex++)
  407. {
  408. int offset = line * nBlocks * NUM_BYTES_PER_HEX_COLUMN + byteIndex;
  409. byte b = GetData (data, offset, out bool edited);
  410. Rune c;
  411. var utf8BytesConsumed = 0;
  412. if (offset >= n && !edited)
  413. {
  414. c = _spaceCharRune;
  415. }
  416. else
  417. {
  418. switch (b)
  419. {
  420. //case < 32:
  421. // c = _periodCharRune;
  422. // break;
  423. case > 127:
  424. {
  425. var utf8 = GetData (data, offset, 4, out bool _);
  426. OperationStatus status = Rune.DecodeFromUtf8 (utf8, out c, out utf8BytesConsumed);
  427. while (status == OperationStatus.NeedMoreData)
  428. {
  429. status = Rune.DecodeFromUtf8 (utf8, out c, out utf8BytesConsumed);
  430. }
  431. break;
  432. }
  433. default:
  434. Rune.DecodeFromUtf8 (new (ref b), out c, out _);
  435. break;
  436. }
  437. }
  438. if (offset + _displayStart == Address)
  439. {
  440. // Selected
  441. SetAttribute (_leftSideHasFocus ? editingAttribute : (edited ? editedAttribute : selectedAttribute));
  442. }
  443. else
  444. {
  445. SetAttribute (edited ? editedAttribute : GetNormalColor ());
  446. }
  447. Driver?.AddRune (c);
  448. for (var i = 1; i < utf8BytesConsumed; i++)
  449. {
  450. byteIndex++;
  451. Driver?.AddRune (_periodCharRune);
  452. }
  453. }
  454. }
  455. return true;
  456. void SetAttribute (Attribute attribute)
  457. {
  458. if (currentAttribute != attribute)
  459. {
  460. currentAttribute = attribute;
  461. Driver?.SetAttribute (attribute);
  462. }
  463. }
  464. }
  465. /// <summary>Raises the <see cref="Edited"/> event.</summary>
  466. protected void RaiseEdited (HexViewEditEventArgs e)
  467. {
  468. OnEdited (e);
  469. Edited?.Invoke (this, e);
  470. }
  471. /// <summary>Event to be invoked when an edit is made on the <see cref="Stream"/>.</summary>
  472. public event EventHandler<HexViewEditEventArgs>? Edited;
  473. /// <summary>
  474. /// </summary>
  475. /// <param name="e"></param>
  476. protected virtual void OnEdited (HexViewEditEventArgs e) { }
  477. /// <summary>
  478. /// Call this when <see cref="Position"/> (and <see cref="Address"/>) has changed. Raises the
  479. /// <see cref="PositionChanged"/> event.
  480. /// </summary>
  481. protected void RaisePositionChanged ()
  482. {
  483. SetNeedsDisplay ();
  484. HexViewEventArgs args = new (Address, Position, BytesPerLine);
  485. OnPositionChanged (args);
  486. PositionChanged?.Invoke (this, args);
  487. }
  488. /// <summary>
  489. /// Called when <see cref="Position"/> (and <see cref="Address"/>) has changed.
  490. /// </summary>
  491. protected virtual void OnPositionChanged (HexViewEventArgs e) { }
  492. /// <summary>Raised when <see cref="Position"/> (and <see cref="Address"/>) has 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. // BUGBUG: This makes no sense here.
  535. RedisplayLine (Address);
  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 screenful 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 = DisplayStart + 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 = DisplayStart + 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 HexView_LayoutComplete (object? sender, LayoutEventArgs e)
  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. RedisplayLine (Address);
  635. if (Address + bytes < GetEditedSize ())
  636. {
  637. // We can move down lines cleanly (without extending stream)
  638. Address += bytes;
  639. }
  640. else if ((bytes == BytesPerLine * Viewport.Height && _source!.Length >= DisplayStart + BytesPerLine * Viewport.Height)
  641. || (bytes <= BytesPerLine * Viewport.Height - BytesPerLine
  642. && _source!.Length <= DisplayStart + BytesPerLine * Viewport.Height))
  643. {
  644. long p = Address;
  645. // This lets address go past the end of the stream one, enabling adding to the stream.
  646. while (p + BytesPerLine <= GetEditedSize ())
  647. {
  648. p += BytesPerLine;
  649. }
  650. Address = p;
  651. }
  652. if (Address >= DisplayStart + BytesPerLine * Viewport.Height)
  653. {
  654. SetDisplayStart (DisplayStart + bytes);
  655. SetNeedsDisplay ();
  656. }
  657. else
  658. {
  659. RedisplayLine (Address);
  660. }
  661. return true;
  662. }
  663. private bool MoveEnd ()
  664. {
  665. // This lets address go past the end of the stream one, enabling adding to the stream.
  666. Address = GetEditedSize ();
  667. if (Address >= DisplayStart + BytesPerLine * Viewport.Height)
  668. {
  669. SetDisplayStart (Address);
  670. SetNeedsDisplay ();
  671. }
  672. else
  673. {
  674. RedisplayLine (Address);
  675. }
  676. return true;
  677. }
  678. private bool MoveEndOfLine ()
  679. {
  680. // This lets address go past the end of the stream one, enabling adding to the stream.
  681. Address = Math.Min (Address / BytesPerLine * BytesPerLine + BytesPerLine - 1, GetEditedSize ());
  682. SetNeedsDisplay ();
  683. return true;
  684. }
  685. private bool MoveHome ()
  686. {
  687. DisplayStart = 0;
  688. SetNeedsDisplay ();
  689. return true;
  690. }
  691. private bool MoveLeft ()
  692. {
  693. RedisplayLine (Address);
  694. if (_leftSideHasFocus)
  695. {
  696. if (!_firstNibble)
  697. {
  698. _firstNibble = true;
  699. return true;
  700. }
  701. _firstNibble = false;
  702. }
  703. if (Address == 0)
  704. {
  705. return true;
  706. }
  707. if (Address - 1 < DisplayStart)
  708. {
  709. SetDisplayStart (_displayStart - BytesPerLine);
  710. SetNeedsDisplay ();
  711. }
  712. else
  713. {
  714. RedisplayLine (Address);
  715. }
  716. Address--;
  717. return true;
  718. }
  719. private bool MoveRight ()
  720. {
  721. RedisplayLine (Address);
  722. if (_leftSideHasFocus)
  723. {
  724. if (_firstNibble)
  725. {
  726. _firstNibble = false;
  727. return true;
  728. }
  729. _firstNibble = true;
  730. }
  731. // This lets address go past the end of the stream one, enabling adding to the stream.
  732. if (Address < GetEditedSize ())
  733. {
  734. Address++;
  735. }
  736. if (Address >= DisplayStart + BytesPerLine * Viewport.Height)
  737. {
  738. SetDisplayStart (DisplayStart + BytesPerLine);
  739. SetNeedsDisplay ();
  740. }
  741. else
  742. {
  743. RedisplayLine (Address);
  744. }
  745. return true;
  746. }
  747. private long GetEditedSize ()
  748. {
  749. if (_edits.Count == 0)
  750. {
  751. return _source!.Length;
  752. }
  753. long maxEditAddress = _edits.Keys.Max ();
  754. return Math.Max (_source!.Length, maxEditAddress + 1);
  755. }
  756. private bool MoveLeftStart ()
  757. {
  758. Address = Address / BytesPerLine * BytesPerLine;
  759. SetNeedsDisplay ();
  760. return true;
  761. }
  762. private bool MoveUp (int bytes)
  763. {
  764. RedisplayLine (Address);
  765. if (Address - bytes > -1)
  766. {
  767. Address -= bytes;
  768. }
  769. if (Address < DisplayStart)
  770. {
  771. SetDisplayStart (DisplayStart - bytes);
  772. SetNeedsDisplay ();
  773. }
  774. else
  775. {
  776. RedisplayLine (Address);
  777. }
  778. return true;
  779. }
  780. private void RedisplayLine (long pos)
  781. {
  782. if (BytesPerLine == 0)
  783. {
  784. return;
  785. }
  786. var delta = (int)(pos - DisplayStart);
  787. int line = delta / BytesPerLine;
  788. SetNeedsDisplay (new (0, line, Viewport.Width, 1));
  789. }
  790. /// <inheritdoc />
  791. protected override bool OnAdvancingFocus (NavigationDirection direction, TabBehavior? behavior)
  792. {
  793. if (behavior is { } && behavior != TabStop)
  794. {
  795. return false;
  796. }
  797. if ((direction == NavigationDirection.Forward && _leftSideHasFocus)
  798. || (direction == NavigationDirection.Backward && !_leftSideHasFocus))
  799. {
  800. _leftSideHasFocus = !_leftSideHasFocus;
  801. RedisplayLine (Address);
  802. _firstNibble = true;
  803. return true;
  804. }
  805. return false;
  806. }
  807. /// <inheritdoc/>
  808. bool IDesignable.EnableForDesign ()
  809. {
  810. Source = new MemoryStream (Encoding.UTF8.GetBytes ("HexView data with wide codepoints: 𝔹Aℝ𝔽!"));
  811. return true;
  812. }
  813. }