HexView.cs 18 KB

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