HexView.cs 18 KB

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