HexView.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. //
  2. // HexView.cs: A hexadecimal viewer
  3. //
  4. // TODO:
  5. // - Support searching and highlighting of the search result
  6. // - Bug showing the last line
  7. //
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Text;
  12. namespace Terminal.Gui;
  13. /// <summary>
  14. /// An hex viewer and editor <see cref="View"/> over a <see cref="System.IO.Stream"/>
  15. /// </summary>
  16. /// <remarks>
  17. /// <para>
  18. /// <see cref="HexView"/> provides a hex editor on top of a seekable <see cref="Stream"/> with the left side showing an hex
  19. /// dump of the values in the <see cref="Stream"/> and the right side showing the contents (filtered to
  20. /// non-control sequence ASCII characters).
  21. /// </para>
  22. /// <para>
  23. /// Users can switch from one side to the other by using the tab key.
  24. /// </para>
  25. /// <para>
  26. /// To enable editing, set <see cref="AllowEdits"/> to true. When <see cref="AllowEdits"/> is true
  27. /// the user can make changes to the hexadecimal values of the <see cref="Stream"/>. Any changes are tracked
  28. /// in the <see cref="Edits"/> property (a <see cref="SortedDictionary{TKey, TValue}"/>) indicating
  29. /// the position where the changes were made and the new values. A convenience method, <see cref="ApplyEdits"/>
  30. /// will apply the edits to the <see cref="Stream"/>.
  31. /// </para>
  32. /// <para>
  33. /// Control the first byte shown by setting the <see cref="DisplayStart"/> property
  34. /// to an offset in the stream.
  35. /// </para>
  36. /// </remarks>
  37. public partial class HexView : View {
  38. SortedDictionary<long, byte> edits = new SortedDictionary<long, byte> ();
  39. Stream source;
  40. long displayStart, pos;
  41. bool firstNibble, leftSide;
  42. long position {
  43. get => pos;
  44. set {
  45. pos = value;
  46. OnPositionChanged ();
  47. }
  48. }
  49. /// <summary>
  50. /// Initializes a <see cref="HexView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  51. /// </summary>
  52. /// <param name="source">The <see cref="Stream"/> to view and edit as hex, this <see cref="Stream"/> must support seeking, or an exception will be thrown.</param>
  53. public HexView (Stream source) : base ()
  54. {
  55. Source = source;
  56. CanFocus = true;
  57. leftSide = true;
  58. firstNibble = true;
  59. // Things this view knows how to do
  60. AddCommand (Command.Left, () => MoveLeft ());
  61. AddCommand (Command.Right, () => MoveRight ());
  62. AddCommand (Command.LineDown, () => MoveDown (bytesPerLine));
  63. AddCommand (Command.LineUp, () => MoveUp (bytesPerLine));
  64. AddCommand (Command.ToggleChecked, () => ToggleSide ());
  65. AddCommand (Command.PageUp, () => MoveUp (bytesPerLine * Frame.Height));
  66. AddCommand (Command.PageDown, () => MoveDown (bytesPerLine * Frame.Height));
  67. AddCommand (Command.TopHome, () => MoveHome ());
  68. AddCommand (Command.BottomEnd, () => MoveEnd ());
  69. AddCommand (Command.StartOfLine, () => MoveStartOfLine ());
  70. AddCommand (Command.EndOfLine, () => MoveEndOfLine ());
  71. AddCommand (Command.StartOfPage, () => MoveUp (bytesPerLine * ((int)(position - displayStart) / bytesPerLine)));
  72. AddCommand (Command.EndOfPage, () => MoveDown (bytesPerLine * (Frame.Height - 1 - (int)(position - displayStart) / bytesPerLine)));
  73. // Default keybindings for this view
  74. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  75. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  76. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  77. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  78. KeyBindings.Add (KeyCode.Enter, Command.ToggleChecked);
  79. KeyBindings.Add ('v' + KeyCode.AltMask, Command.PageUp);
  80. KeyBindings.Add (KeyCode.PageUp, Command.PageUp);
  81. KeyBindings.Add (KeyCode.V | KeyCode.CtrlMask, Command.PageDown);
  82. KeyBindings.Add (KeyCode.PageDown, Command.PageDown);
  83. KeyBindings.Add (KeyCode.Home, Command.TopHome);
  84. KeyBindings.Add (KeyCode.End, Command.BottomEnd);
  85. KeyBindings.Add (KeyCode.CursorLeft | KeyCode.CtrlMask, Command.StartOfLine);
  86. KeyBindings.Add (KeyCode.CursorRight | KeyCode.CtrlMask, Command.EndOfLine);
  87. KeyBindings.Add (KeyCode.CursorUp | KeyCode.CtrlMask, Command.StartOfPage);
  88. KeyBindings.Add (KeyCode.CursorDown | KeyCode.CtrlMask, Command.EndOfPage);
  89. }
  90. /// <summary>
  91. /// Initializes a <see cref="HexView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  92. /// </summary>
  93. public HexView () : this (source: new MemoryStream ()) { }
  94. /// <summary>
  95. /// Event to be invoked when an edit is made on the <see cref="Stream"/>.
  96. /// </summary>
  97. public event EventHandler<HexViewEditEventArgs> Edited;
  98. /// <summary>
  99. /// Event to be invoked when the position and cursor position changes.
  100. /// </summary>
  101. public event EventHandler<HexViewEventArgs> PositionChanged;
  102. /// <summary>
  103. /// Sets or gets the <see cref="Stream"/> the <see cref="HexView"/> is operating on; the stream must support seeking (<see cref="Stream.CanSeek"/> == true).
  104. /// </summary>
  105. /// <value>The source.</value>
  106. public Stream Source {
  107. get => source;
  108. set {
  109. if (value == null) {
  110. throw new ArgumentNullException ("source");
  111. }
  112. if (!value.CanSeek) {
  113. throw new ArgumentException ("The source stream must be seekable (CanSeek property)", "source");
  114. }
  115. source = value;
  116. if (displayStart > source.Length) {
  117. DisplayStart = 0;
  118. }
  119. if (position > source.Length) {
  120. position = 0;
  121. }
  122. SetNeedsDisplay ();
  123. }
  124. }
  125. internal void SetDisplayStart (long value)
  126. {
  127. if (value > 0 && value >= source.Length) {
  128. displayStart = source.Length - 1;
  129. } else if (value < 0) {
  130. displayStart = 0;
  131. } else {
  132. displayStart = value;
  133. }
  134. SetNeedsDisplay ();
  135. }
  136. /// <summary>
  137. /// Sets or gets the offset into the <see cref="Stream"/> that will displayed at the top of the <see cref="HexView"/>
  138. /// </summary>
  139. /// <value>The display start.</value>
  140. public long DisplayStart {
  141. get => displayStart;
  142. set {
  143. position = value;
  144. SetDisplayStart (value);
  145. }
  146. }
  147. const int displayWidth = 9;
  148. const int bsize = 4;
  149. int bpl;
  150. int bytesPerLine {
  151. get => bpl;
  152. set {
  153. bpl = value;
  154. OnPositionChanged ();
  155. }
  156. }
  157. /// <inheritdoc/>
  158. public override Rect Frame {
  159. get => base.Frame;
  160. set {
  161. base.Frame = value;
  162. // Small buffers will just show the position, with the bsize field value (4 bytes)
  163. bytesPerLine = bsize;
  164. if (value.Width - displayWidth > 17) {
  165. bytesPerLine = bsize * ((value.Width - displayWidth) / 18);
  166. }
  167. }
  168. }
  169. //
  170. // This is used to support editing of the buffer on a peer List<>,
  171. // the offset corresponds to an offset relative to DisplayStart, and
  172. // the buffer contains the contents of a screenful of data, so the
  173. // offset is relative to the buffer.
  174. //
  175. //
  176. byte GetData (byte [] buffer, int offset, out bool edited)
  177. {
  178. long pos = DisplayStart + offset;
  179. if (edits.TryGetValue (pos, out byte v)) {
  180. edited = true;
  181. return v;
  182. }
  183. edited = false;
  184. return buffer [offset];
  185. }
  186. ///<inheritdoc/>
  187. public override void OnDrawContent (Rect contentArea)
  188. {
  189. Attribute currentAttribute;
  190. var current = ColorScheme.Focus;
  191. Driver.SetAttribute (current);
  192. Move (0, 0);
  193. var frame = Frame;
  194. int nblocks = bytesPerLine / bsize;
  195. byte [] data = new byte [nblocks * bsize * frame.Height];
  196. Source.Position = displayStart;
  197. int n = source.Read (data, 0, data.Length);
  198. var activeColor = ColorScheme.HotNormal;
  199. var trackingColor = ColorScheme.HotFocus;
  200. for (int line = 0; line < frame.Height; line++) {
  201. var lineRect = new Rect (0, line, frame.Width, 1);
  202. if (!Bounds.Contains (lineRect)) {
  203. continue;
  204. }
  205. Move (0, line);
  206. Driver.SetAttribute (ColorScheme.HotNormal);
  207. Driver.AddStr (string.Format ("{0:x8} ", displayStart + line * nblocks * bsize));
  208. currentAttribute = ColorScheme.HotNormal;
  209. SetAttribute (GetNormalColor ());
  210. for (int block = 0; block < nblocks; block++) {
  211. for (int b = 0; b < bsize; b++) {
  212. int offset = line * nblocks * bsize + block * bsize + b;
  213. byte value = GetData (data, offset, out bool edited);
  214. if (offset + displayStart == position || edited) {
  215. SetAttribute (leftSide ? activeColor : trackingColor);
  216. } else {
  217. SetAttribute (GetNormalColor ());
  218. }
  219. Driver.AddStr (offset >= n && !edited ? " " : string.Format ("{0:x2}", value));
  220. SetAttribute (GetNormalColor ());
  221. Driver.AddRune ((Rune)' ');
  222. }
  223. Driver.AddStr (block + 1 == nblocks ? " " : "| ");
  224. }
  225. for (int bitem = 0; bitem < nblocks * bsize; bitem++) {
  226. int offset = line * nblocks * bsize + bitem;
  227. byte b = GetData (data, offset, out bool edited);
  228. Rune c;
  229. if (offset >= n && !edited) {
  230. c = (Rune)' ';
  231. } else {
  232. if (b < 32) {
  233. c = (Rune)'.';
  234. } else if (b > 127) {
  235. c = (Rune)'.';
  236. } else {
  237. Rune.DecodeFromUtf8 (new ReadOnlySpan<byte> (ref b), out c, out _);
  238. }
  239. }
  240. if (offset + displayStart == position || edited) {
  241. SetAttribute (leftSide ? trackingColor : activeColor);
  242. } else {
  243. SetAttribute (GetNormalColor ());
  244. }
  245. Driver.AddRune (c);
  246. }
  247. }
  248. void SetAttribute (Attribute attribute)
  249. {
  250. if (currentAttribute != attribute) {
  251. currentAttribute = attribute;
  252. Driver.SetAttribute (attribute);
  253. }
  254. }
  255. }
  256. ///<inheritdoc/>
  257. public override void PositionCursor ()
  258. {
  259. int delta = (int)(position - displayStart);
  260. int line = delta / bytesPerLine;
  261. int item = delta % bytesPerLine;
  262. int block = item / bsize;
  263. int column = item % bsize * 3;
  264. if (leftSide) {
  265. Move (displayWidth + block * 14 + column + (firstNibble ? 0 : 1), line);
  266. } else {
  267. Move (displayWidth + bytesPerLine / bsize * 14 + item - 1, line);
  268. }
  269. }
  270. void RedisplayLine (long pos)
  271. {
  272. int delta = (int)(pos - DisplayStart);
  273. int line = delta / bytesPerLine;
  274. SetNeedsDisplay (new Rect (0, line, Frame.Width, 1));
  275. }
  276. bool MoveEndOfLine ()
  277. {
  278. position = Math.Min (position / bytesPerLine * bytesPerLine + bytesPerLine - 1, source.Length);
  279. SetNeedsDisplay ();
  280. return true;
  281. }
  282. bool MoveStartOfLine ()
  283. {
  284. position = position / bytesPerLine * bytesPerLine;
  285. SetNeedsDisplay ();
  286. return true;
  287. }
  288. bool MoveEnd ()
  289. {
  290. position = source.Length;
  291. if (position >= DisplayStart + bytesPerLine * Frame.Height) {
  292. SetDisplayStart (position);
  293. SetNeedsDisplay ();
  294. } else {
  295. RedisplayLine (position);
  296. }
  297. return true;
  298. }
  299. bool MoveHome ()
  300. {
  301. DisplayStart = 0;
  302. SetNeedsDisplay ();
  303. return true;
  304. }
  305. bool ToggleSide ()
  306. {
  307. leftSide = !leftSide;
  308. RedisplayLine (position);
  309. firstNibble = true;
  310. return true;
  311. }
  312. bool MoveLeft ()
  313. {
  314. RedisplayLine (position);
  315. if (leftSide) {
  316. if (!firstNibble) {
  317. firstNibble = true;
  318. return true;
  319. }
  320. firstNibble = false;
  321. }
  322. if (position == 0) {
  323. return true;
  324. }
  325. if (position - 1 < DisplayStart) {
  326. SetDisplayStart (displayStart - bytesPerLine);
  327. SetNeedsDisplay ();
  328. } else {
  329. RedisplayLine (position);
  330. }
  331. position--;
  332. return true;
  333. }
  334. bool MoveRight ()
  335. {
  336. RedisplayLine (position);
  337. if (leftSide) {
  338. if (firstNibble) {
  339. firstNibble = false;
  340. return true;
  341. } else {
  342. firstNibble = true;
  343. }
  344. }
  345. if (position < source.Length) {
  346. position++;
  347. }
  348. if (position >= DisplayStart + bytesPerLine * Frame.Height) {
  349. SetDisplayStart (DisplayStart + bytesPerLine);
  350. SetNeedsDisplay ();
  351. } else {
  352. RedisplayLine (position);
  353. }
  354. return true;
  355. }
  356. bool MoveUp (int bytes)
  357. {
  358. RedisplayLine (position);
  359. if (position - bytes > -1) {
  360. position -= bytes;
  361. }
  362. if (position < DisplayStart) {
  363. SetDisplayStart (DisplayStart - bytes);
  364. SetNeedsDisplay ();
  365. } else {
  366. RedisplayLine (position);
  367. }
  368. return true;
  369. }
  370. bool MoveDown (int bytes)
  371. {
  372. RedisplayLine (position);
  373. if (position + bytes < source.Length) {
  374. position += bytes;
  375. } else if (bytes == bytesPerLine * Frame.Height && source.Length >= DisplayStart + bytesPerLine * Frame.Height
  376. || bytes <= bytesPerLine * Frame.Height - bytesPerLine && source.Length <= DisplayStart + bytesPerLine * Frame.Height) {
  377. long p = position;
  378. while (p + bytesPerLine < source.Length) {
  379. p += bytesPerLine;
  380. }
  381. position = p;
  382. }
  383. if (position >= DisplayStart + bytesPerLine * Frame.Height) {
  384. SetDisplayStart (DisplayStart + bytes);
  385. SetNeedsDisplay ();
  386. } else {
  387. RedisplayLine (position);
  388. }
  389. return true;
  390. }
  391. /// <inheritdoc/>
  392. public override bool OnProcessKeyDown (Key keyEvent)
  393. {
  394. if (!AllowEdits) {
  395. return false;
  396. }
  397. // Ignore control characters and other special keys
  398. if (keyEvent.KeyCode < KeyCode.Space || keyEvent.KeyCode > KeyCode.CharMask) {
  399. return false;
  400. }
  401. if (leftSide) {
  402. int value;
  403. char k = (char)keyEvent.KeyCode;
  404. if (k >= 'A' && k <= 'F') {
  405. value = k - 'A' + 10;
  406. } else if (k >= 'a' && k <= 'f') {
  407. value = k - 'a' + 10;
  408. } else if (k >= '0' && k <= '9') {
  409. value = k - '0';
  410. } else {
  411. return false;
  412. }
  413. byte b;
  414. if (!edits.TryGetValue (position, out b)) {
  415. source.Position = position;
  416. b = (byte)source.ReadByte ();
  417. }
  418. RedisplayLine (position);
  419. if (firstNibble) {
  420. firstNibble = false;
  421. b = (byte)(b & 0xf | value << bsize);
  422. edits [position] = b;
  423. OnEdited (new HexViewEditEventArgs (position, edits [position]));
  424. } else {
  425. b = (byte)(b & 0xf0 | value);
  426. edits [position] = b;
  427. OnEdited (new HexViewEditEventArgs (position, edits [position]));
  428. MoveRight ();
  429. }
  430. return true;
  431. } else {
  432. return false;
  433. }
  434. }
  435. /// <summary>
  436. /// Method used to invoke the <see cref="Edited"/> event passing the <see cref="KeyValuePair{TKey, TValue}"/>.
  437. /// </summary>
  438. /// <param name="e">The key value pair.</param>
  439. public virtual void OnEdited (HexViewEditEventArgs e)
  440. {
  441. Edited?.Invoke (this, e);
  442. }
  443. /// <summary>
  444. /// Method used to invoke the <see cref="PositionChanged"/> event passing the <see cref="HexViewEventArgs"/> arguments.
  445. /// </summary>
  446. public virtual void OnPositionChanged ()
  447. {
  448. PositionChanged?.Invoke (this, new HexViewEventArgs (Position, CursorPosition, BytesPerLine));
  449. }
  450. /// <inheritdoc/>
  451. public override bool MouseEvent (MouseEvent me)
  452. {
  453. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  454. && !me.Flags.HasFlag (MouseFlags.WheeledDown) && !me.Flags.HasFlag (MouseFlags.WheeledUp)) {
  455. return false;
  456. }
  457. if (!HasFocus) {
  458. SetFocus ();
  459. }
  460. if (me.Flags == MouseFlags.WheeledDown) {
  461. DisplayStart = Math.Min (DisplayStart + bytesPerLine, source.Length);
  462. return true;
  463. }
  464. if (me.Flags == MouseFlags.WheeledUp) {
  465. DisplayStart = Math.Max (DisplayStart - bytesPerLine, 0);
  466. return true;
  467. }
  468. if (me.X < displayWidth) {
  469. return true;
  470. }
  471. int nblocks = bytesPerLine / bsize;
  472. int blocksSize = nblocks * 14;
  473. int blocksRightOffset = displayWidth + blocksSize - 1;
  474. if (me.X > blocksRightOffset + bytesPerLine - 1) {
  475. return true;
  476. }
  477. leftSide = me.X >= blocksRightOffset;
  478. long lineStart = me.Y * bytesPerLine + displayStart;
  479. int x = me.X - displayWidth + 1;
  480. int block = x / 14;
  481. x -= block * 2;
  482. int empty = x % 3;
  483. int item = x / 3;
  484. if (!leftSide && item > 0 && (empty == 0 || x == block * 14 + 14 - 1 - block * 2)) {
  485. return true;
  486. }
  487. firstNibble = true;
  488. if (leftSide) {
  489. position = Math.Min (lineStart + me.X - blocksRightOffset, source.Length);
  490. } else {
  491. position = Math.Min (lineStart + item, source.Length);
  492. }
  493. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  494. leftSide = !leftSide;
  495. if (leftSide) {
  496. firstNibble = empty == 1;
  497. } else {
  498. firstNibble = true;
  499. }
  500. }
  501. SetNeedsDisplay ();
  502. return true;
  503. }
  504. /// <summary>
  505. /// Gets or sets whether this <see cref="HexView"/> allow editing of the <see cref="Stream"/>
  506. /// of the underlying <see cref="Stream"/>.
  507. /// </summary>
  508. /// <value><c>true</c> if allow edits; otherwise, <c>false</c>.</value>
  509. public bool AllowEdits { get; set; } = true;
  510. /// <summary>
  511. /// Gets a <see cref="SortedDictionary{TKey, TValue}"/> describing the edits done to the <see cref="HexView"/>.
  512. /// Each Key indicates an offset where an edit was made and the Value is the changed byte.
  513. /// </summary>
  514. /// <value>The edits.</value>
  515. public IReadOnlyDictionary<long, byte> Edits => edits;
  516. /// <summary>
  517. /// Gets the current character position starting at one, related to the <see cref="Stream"/>.
  518. /// </summary>
  519. public long Position => position + 1;
  520. /// <summary>
  521. /// Gets the current cursor position starting at one for both, line and column.
  522. /// </summary>
  523. public Point CursorPosition {
  524. get {
  525. int delta = (int)position;
  526. int line = delta / bytesPerLine + 1;
  527. int item = delta % bytesPerLine + 1;
  528. return new Point (item, line);
  529. }
  530. }
  531. /// <summary>
  532. /// The bytes length per line.
  533. /// </summary>
  534. public int BytesPerLine => bytesPerLine;
  535. /// <summary>
  536. /// This method applies and edits made to the <see cref="Stream"/> and resets the
  537. /// contents of the <see cref="Edits"/> property.
  538. /// </summary>
  539. /// <param name="stream">If provided also applies the changes to the passed <see cref="Stream"/></param>.
  540. public void ApplyEdits (Stream stream = null)
  541. {
  542. foreach (var kv in edits) {
  543. source.Position = kv.Key;
  544. source.WriteByte (kv.Value);
  545. source.Flush ();
  546. if (stream != null) {
  547. stream.Position = kv.Key;
  548. stream.WriteByte (kv.Value);
  549. stream.Flush ();
  550. }
  551. }
  552. edits = new SortedDictionary<long, byte> ();
  553. SetNeedsDisplay ();
  554. }
  555. /// <summary>
  556. /// This method discards the edits made to the <see cref="Stream"/> by resetting the
  557. /// contents of the <see cref="Edits"/> property.
  558. /// </summary>
  559. public void DiscardEdits ()
  560. {
  561. edits = new SortedDictionary<long, byte> ();
  562. }
  563. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  564. /// <summary>
  565. /// Get / Set the wished cursor when the field is focused
  566. /// </summary>
  567. public CursorVisibility DesiredCursorVisibility {
  568. get => desiredCursorVisibility;
  569. set {
  570. if (desiredCursorVisibility != value && HasFocus) {
  571. Application.Driver.SetCursorVisibility (value);
  572. }
  573. desiredCursorVisibility = value;
  574. }
  575. }
  576. ///<inheritdoc/>
  577. public override bool OnEnter (View view)
  578. {
  579. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  580. return base.OnEnter (view);
  581. }
  582. }