HexView.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. private 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. AddKeyBinding (Key.CursorLeft, Command.Left);
  75. AddKeyBinding (Key.CursorRight, Command.Right);
  76. AddKeyBinding (Key.CursorDown, Command.LineDown);
  77. AddKeyBinding (Key.CursorUp, Command.LineUp);
  78. AddKeyBinding (Key.Enter, Command.ToggleChecked);
  79. AddKeyBinding ('v' + Key.AltMask, Command.PageUp);
  80. AddKeyBinding (Key.PageUp, Command.PageUp);
  81. AddKeyBinding (Key.V | Key.CtrlMask, Command.PageDown);
  82. AddKeyBinding (Key.PageDown, Command.PageDown);
  83. AddKeyBinding (Key.Home, Command.TopHome);
  84. AddKeyBinding (Key.End, Command.BottomEnd);
  85. AddKeyBinding (Key.CursorLeft | Key.CtrlMask, Command.StartOfLine);
  86. AddKeyBinding (Key.CursorRight | Key.CtrlMask, Command.EndOfLine);
  87. AddKeyBinding (Key.CursorUp | Key.CtrlMask, Command.StartOfPage);
  88. AddKeyBinding (Key.CursorDown | Key.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. if (!value.CanSeek)
  112. throw new ArgumentException ("The source stream must be seekable (CanSeek property)", "source");
  113. source = value;
  114. if (displayStart > source.Length)
  115. DisplayStart = 0;
  116. if (position > source.Length)
  117. position = 0;
  118. SetNeedsDisplay ();
  119. }
  120. }
  121. internal void SetDisplayStart (long value)
  122. {
  123. if (value > 0 && value >= source.Length)
  124. displayStart = source.Length - 1;
  125. else if (value < 0)
  126. displayStart = 0;
  127. else
  128. displayStart = value;
  129. SetNeedsDisplay ();
  130. }
  131. /// <summary>
  132. /// Sets or gets the offset into the <see cref="Stream"/> that will displayed at the top of the <see cref="HexView"/>
  133. /// </summary>
  134. /// <value>The display start.</value>
  135. public long DisplayStart {
  136. get => displayStart;
  137. set {
  138. position = value;
  139. SetDisplayStart (value);
  140. }
  141. }
  142. const int displayWidth = 9;
  143. const int bsize = 4;
  144. int bpl;
  145. private int bytesPerLine {
  146. get => bpl;
  147. set {
  148. bpl = value;
  149. OnPositionChanged ();
  150. }
  151. }
  152. /// <inheritdoc/>
  153. public override Rect Frame {
  154. get => base.Frame;
  155. set {
  156. base.Frame = value;
  157. // Small buffers will just show the position, with the bsize field value (4 bytes)
  158. bytesPerLine = bsize;
  159. if (value.Width - displayWidth > 17)
  160. bytesPerLine = bsize * ((value.Width - displayWidth) / 18);
  161. }
  162. }
  163. //
  164. // This is used to support editing of the buffer on a peer List<>,
  165. // the offset corresponds to an offset relative to DisplayStart, and
  166. // the buffer contains the contents of a screenful of data, so the
  167. // offset is relative to the buffer.
  168. //
  169. //
  170. byte GetData (byte [] buffer, int offset, out bool edited)
  171. {
  172. var pos = DisplayStart + offset;
  173. if (edits.TryGetValue (pos, out byte v)) {
  174. edited = true;
  175. return v;
  176. }
  177. edited = false;
  178. return buffer [offset];
  179. }
  180. ///<inheritdoc/>
  181. public override void OnDrawContent (Rect contentArea)
  182. {
  183. Attribute currentAttribute;
  184. var current = ColorScheme.Focus;
  185. Driver.SetAttribute (current);
  186. Move (0, 0);
  187. var frame = Frame;
  188. var nblocks = bytesPerLine / bsize;
  189. var data = new byte [nblocks * bsize * frame.Height];
  190. Source.Position = displayStart;
  191. var n = source.Read (data, 0, data.Length);
  192. var activeColor = ColorScheme.HotNormal;
  193. var trackingColor = ColorScheme.HotFocus;
  194. for (int line = 0; line < frame.Height; line++) {
  195. var lineRect = new Rect (0, line, frame.Width, 1);
  196. if (!Bounds.Contains (lineRect))
  197. continue;
  198. Move (0, line);
  199. Driver.SetAttribute (ColorScheme.HotNormal);
  200. Driver.AddStr (string.Format ("{0:x8} ", displayStart + line * nblocks * bsize));
  201. currentAttribute = ColorScheme.HotNormal;
  202. SetAttribute (GetNormalColor ());
  203. for (int block = 0; block < nblocks; block++) {
  204. for (int b = 0; b < bsize; b++) {
  205. var offset = (line * nblocks * bsize) + block * bsize + b;
  206. var value = GetData (data, offset, out bool edited);
  207. if (offset + displayStart == position || edited)
  208. SetAttribute (leftSide ? activeColor : trackingColor);
  209. else
  210. SetAttribute (GetNormalColor ());
  211. Driver.AddStr (offset >= n && !edited ? " " : string.Format ("{0:x2}", value));
  212. SetAttribute (GetNormalColor ());
  213. Driver.AddRune ((Rune)' ');
  214. }
  215. Driver.AddStr (block + 1 == nblocks ? " " : "| ");
  216. }
  217. for (int bitem = 0; bitem < nblocks * bsize; bitem++) {
  218. var offset = line * nblocks * bsize + bitem;
  219. var b = GetData (data, offset, out bool edited);
  220. Rune c;
  221. if (offset >= n && !edited)
  222. c = (Rune)' ';
  223. else {
  224. if (b < 32)
  225. c = (Rune)'.';
  226. else if (b > 127)
  227. c = (Rune)'.';
  228. else
  229. Rune.DecodeFromUtf8 (new ReadOnlySpan<byte> (b), out c, out _);
  230. }
  231. if (offset + displayStart == position || edited)
  232. SetAttribute (leftSide ? trackingColor : activeColor);
  233. else
  234. SetAttribute (GetNormalColor ());
  235. Driver.AddRune (c);
  236. }
  237. }
  238. void SetAttribute (Attribute attribute)
  239. {
  240. if (currentAttribute != attribute) {
  241. currentAttribute = attribute;
  242. Driver.SetAttribute (attribute);
  243. }
  244. }
  245. }
  246. ///<inheritdoc/>
  247. public override void PositionCursor ()
  248. {
  249. var delta = (int)(position - displayStart);
  250. var line = delta / bytesPerLine;
  251. var item = delta % bytesPerLine;
  252. var block = item / bsize;
  253. var column = (item % bsize) * 3;
  254. if (leftSide)
  255. Move (displayWidth + block * 14 + column + (firstNibble ? 0 : 1), line);
  256. else
  257. Move (displayWidth + (bytesPerLine / bsize) * 14 + item - 1, line);
  258. }
  259. void RedisplayLine (long pos)
  260. {
  261. var delta = (int)(pos - DisplayStart);
  262. var line = delta / bytesPerLine;
  263. SetNeedsDisplay (new Rect (0, line, Frame.Width, 1));
  264. }
  265. bool MoveEndOfLine ()
  266. {
  267. position = Math.Min ((position / bytesPerLine * bytesPerLine) + bytesPerLine - 1, source.Length);
  268. SetNeedsDisplay ();
  269. return true;
  270. }
  271. bool MoveStartOfLine ()
  272. {
  273. position = position / bytesPerLine * bytesPerLine;
  274. SetNeedsDisplay ();
  275. return true;
  276. }
  277. bool MoveEnd ()
  278. {
  279. position = source.Length;
  280. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  281. SetDisplayStart (position);
  282. SetNeedsDisplay ();
  283. } else
  284. RedisplayLine (position);
  285. return true;
  286. }
  287. bool MoveHome ()
  288. {
  289. DisplayStart = 0;
  290. SetNeedsDisplay ();
  291. return true;
  292. }
  293. bool ToggleSide ()
  294. {
  295. leftSide = !leftSide;
  296. RedisplayLine (position);
  297. firstNibble = true;
  298. return true;
  299. }
  300. bool MoveLeft ()
  301. {
  302. RedisplayLine (position);
  303. if (leftSide) {
  304. if (!firstNibble) {
  305. firstNibble = true;
  306. return true;
  307. }
  308. firstNibble = false;
  309. }
  310. if (position == 0)
  311. return true;
  312. if (position - 1 < DisplayStart) {
  313. SetDisplayStart (displayStart - bytesPerLine);
  314. SetNeedsDisplay ();
  315. } else
  316. RedisplayLine (position);
  317. position--;
  318. return true;
  319. }
  320. bool MoveRight ()
  321. {
  322. RedisplayLine (position);
  323. if (leftSide) {
  324. if (firstNibble) {
  325. firstNibble = false;
  326. return true;
  327. } else
  328. firstNibble = true;
  329. }
  330. if (position < source.Length)
  331. position++;
  332. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  333. SetDisplayStart (DisplayStart + bytesPerLine);
  334. SetNeedsDisplay ();
  335. } else
  336. RedisplayLine (position);
  337. return true;
  338. }
  339. bool MoveUp (int bytes)
  340. {
  341. RedisplayLine (position);
  342. if (position - bytes > -1)
  343. position -= bytes;
  344. if (position < DisplayStart) {
  345. SetDisplayStart (DisplayStart - bytes);
  346. SetNeedsDisplay ();
  347. } else
  348. RedisplayLine (position);
  349. return true;
  350. }
  351. bool MoveDown (int bytes)
  352. {
  353. RedisplayLine (position);
  354. if (position + bytes < source.Length)
  355. position += bytes;
  356. else if ((bytes == bytesPerLine * Frame.Height && source.Length >= (DisplayStart + bytesPerLine * Frame.Height))
  357. || (bytes <= (bytesPerLine * Frame.Height - bytesPerLine) && source.Length <= (DisplayStart + bytesPerLine * Frame.Height))) {
  358. var p = position;
  359. while (p + bytesPerLine < source.Length) {
  360. p += bytesPerLine;
  361. }
  362. position = p;
  363. }
  364. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  365. SetDisplayStart (DisplayStart + bytes);
  366. SetNeedsDisplay ();
  367. } else
  368. RedisplayLine (position);
  369. return true;
  370. }
  371. /// <inheritdoc/>
  372. public override bool ProcessKey (KeyEvent keyEvent)
  373. {
  374. var result = InvokeKeybindings (keyEvent);
  375. if (result != null)
  376. return (bool)result;
  377. if (!AllowEdits)
  378. return false;
  379. // Ignore control characters and other special keys
  380. if (keyEvent.Key < Key.Space || keyEvent.Key > Key.CharMask)
  381. return false;
  382. if (leftSide) {
  383. int value;
  384. var k = (char)keyEvent.Key;
  385. if (k >= 'A' && k <= 'F')
  386. value = k - 'A' + 10;
  387. else if (k >= 'a' && k <= 'f')
  388. value = k - 'a' + 10;
  389. else if (k >= '0' && k <= '9')
  390. value = k - '0';
  391. else
  392. return false;
  393. byte b;
  394. if (!edits.TryGetValue (position, out b)) {
  395. source.Position = position;
  396. b = (byte)source.ReadByte ();
  397. }
  398. RedisplayLine (position);
  399. if (firstNibble) {
  400. firstNibble = false;
  401. b = (byte)(b & 0xf | (value << bsize));
  402. edits [position] = b;
  403. OnEdited (new HexViewEditEventArgs (position, edits [position]));
  404. } else {
  405. b = (byte)(b & 0xf0 | value);
  406. edits [position] = b;
  407. OnEdited (new HexViewEditEventArgs (position, edits [position]));
  408. MoveRight ();
  409. }
  410. return true;
  411. } else
  412. return false;
  413. }
  414. /// <summary>
  415. /// Method used to invoke the <see cref="Edited"/> event passing the <see cref="KeyValuePair{TKey, TValue}"/>.
  416. /// </summary>
  417. /// <param name="e">The key value pair.</param>
  418. public virtual void OnEdited (HexViewEditEventArgs e)
  419. {
  420. Edited?.Invoke (this, e);
  421. }
  422. /// <summary>
  423. /// Method used to invoke the <see cref="PositionChanged"/> event passing the <see cref="HexViewEventArgs"/> arguments.
  424. /// </summary>
  425. public virtual void OnPositionChanged ()
  426. {
  427. PositionChanged?.Invoke (this, new HexViewEventArgs (Position, CursorPosition, BytesPerLine));
  428. }
  429. /// <inheritdoc/>
  430. public override bool MouseEvent (MouseEvent me)
  431. {
  432. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  433. && !me.Flags.HasFlag (MouseFlags.WheeledDown) && !me.Flags.HasFlag (MouseFlags.WheeledUp))
  434. return false;
  435. if (!HasFocus)
  436. SetFocus ();
  437. if (me.Flags == MouseFlags.WheeledDown) {
  438. DisplayStart = Math.Min (DisplayStart + bytesPerLine, source.Length);
  439. return true;
  440. }
  441. if (me.Flags == MouseFlags.WheeledUp) {
  442. DisplayStart = Math.Max (DisplayStart - bytesPerLine, 0);
  443. return true;
  444. }
  445. if (me.X < displayWidth)
  446. return true;
  447. var nblocks = bytesPerLine / bsize;
  448. var blocksSize = nblocks * 14;
  449. var blocksRightOffset = displayWidth + blocksSize - 1;
  450. if (me.X > blocksRightOffset + bytesPerLine - 1)
  451. return true;
  452. leftSide = me.X >= blocksRightOffset;
  453. var lineStart = (me.Y * bytesPerLine) + displayStart;
  454. var x = me.X - displayWidth + 1;
  455. var block = x / 14;
  456. x -= block * 2;
  457. var empty = x % 3;
  458. var item = x / 3;
  459. if (!leftSide && item > 0 && (empty == 0 || x == (block * 14) + 14 - 1 - (block * 2)))
  460. return true;
  461. firstNibble = true;
  462. if (leftSide)
  463. position = Math.Min (lineStart + me.X - blocksRightOffset, source.Length);
  464. else
  465. position = Math.Min (lineStart + item, source.Length);
  466. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  467. leftSide = !leftSide;
  468. if (leftSide)
  469. firstNibble = empty == 1;
  470. else
  471. firstNibble = true;
  472. }
  473. SetNeedsDisplay ();
  474. return true;
  475. }
  476. /// <summary>
  477. /// Gets or sets whether this <see cref="HexView"/> allow editing of the <see cref="Stream"/>
  478. /// of the underlying <see cref="Stream"/>.
  479. /// </summary>
  480. /// <value><c>true</c> if allow edits; otherwise, <c>false</c>.</value>
  481. public bool AllowEdits { get; set; } = true;
  482. /// <summary>
  483. /// Gets a <see cref="SortedDictionary{TKey, TValue}"/> describing the edits done to the <see cref="HexView"/>.
  484. /// Each Key indicates an offset where an edit was made and the Value is the changed byte.
  485. /// </summary>
  486. /// <value>The edits.</value>
  487. public IReadOnlyDictionary<long, byte> Edits => edits;
  488. /// <summary>
  489. /// Gets the current character position starting at one, related to the <see cref="Stream"/>.
  490. /// </summary>
  491. public long Position => position + 1;
  492. /// <summary>
  493. /// Gets the current cursor position starting at one for both, line and column.
  494. /// </summary>
  495. public Point CursorPosition {
  496. get {
  497. var delta = (int)position;
  498. var line = delta / bytesPerLine + 1;
  499. var item = delta % bytesPerLine + 1;
  500. return new Point (item, line);
  501. }
  502. }
  503. /// <summary>
  504. /// The bytes length per line.
  505. /// </summary>
  506. public int BytesPerLine => bytesPerLine;
  507. /// <summary>
  508. /// This method applies and edits made to the <see cref="Stream"/> and resets the
  509. /// contents of the <see cref="Edits"/> property.
  510. /// </summary>
  511. /// <param name="stream">If provided also applies the changes to the passed <see cref="Stream"/></param>.
  512. public void ApplyEdits (Stream stream = null)
  513. {
  514. foreach (var kv in edits) {
  515. source.Position = kv.Key;
  516. source.WriteByte (kv.Value);
  517. source.Flush ();
  518. if (stream != null) {
  519. stream.Position = kv.Key;
  520. stream.WriteByte (kv.Value);
  521. stream.Flush ();
  522. }
  523. }
  524. edits = new SortedDictionary<long, byte> ();
  525. SetNeedsDisplay ();
  526. }
  527. /// <summary>
  528. /// This method discards the edits made to the <see cref="Stream"/> by resetting the
  529. /// contents of the <see cref="Edits"/> property.
  530. /// </summary>
  531. public void DiscardEdits ()
  532. {
  533. edits = new SortedDictionary<long, byte> ();
  534. }
  535. private CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  536. /// <summary>
  537. /// Get / Set the wished cursor when the field is focused
  538. /// </summary>
  539. public CursorVisibility DesiredCursorVisibility {
  540. get => desiredCursorVisibility;
  541. set {
  542. if (desiredCursorVisibility != value && HasFocus) {
  543. Application.Driver.SetCursorVisibility (value);
  544. }
  545. desiredCursorVisibility = value;
  546. }
  547. }
  548. ///<inheritdoc/>
  549. public override bool OnEnter (View view)
  550. {
  551. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  552. return base.OnEnter (view);
  553. }
  554. }
  555. }