HexView.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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, position;
  40. bool firstNibble, leftSide;
  41. /// <summary>
  42. /// Initialzies a <see cref="HexView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  43. /// </summary>
  44. /// <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>
  45. public HexView (Stream source) : base ()
  46. {
  47. Source = source;
  48. this.source = source;
  49. CanFocus = true;
  50. leftSide = true;
  51. firstNibble = true;
  52. }
  53. /// <summary>
  54. /// Initialzies a <see cref="HexView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  55. /// </summary>
  56. public HexView () : this (source: new MemoryStream ()) { }
  57. /// <summary>
  58. /// Sets or gets the <see cref="Stream"/> the <see cref="HexView"/> is operating on; the stream must support seeking (<see cref="Stream.CanSeek"/> == true).
  59. /// </summary>
  60. /// <value>The source.</value>
  61. public Stream Source {
  62. get => source;
  63. set {
  64. if (value == null)
  65. throw new ArgumentNullException ("source");
  66. if (!value.CanSeek)
  67. throw new ArgumentException ("The source stream must be seekable (CanSeek property)", "source");
  68. source = value;
  69. SetNeedsDisplay ();
  70. }
  71. }
  72. internal void SetDisplayStart (long value)
  73. {
  74. if (value >= source.Length)
  75. displayStart = source.Length - 1;
  76. else if (value < 0)
  77. displayStart = 0;
  78. else
  79. displayStart = value;
  80. SetNeedsDisplay ();
  81. }
  82. /// <summary>
  83. /// Sets or gets the offset into the <see cref="Stream"/> that will displayed at the top of the <see cref="HexView"/>
  84. /// </summary>
  85. /// <value>The display start.</value>
  86. public long DisplayStart {
  87. get => displayStart;
  88. set {
  89. position = value;
  90. SetDisplayStart (value);
  91. }
  92. }
  93. const int displayWidth = 9;
  94. const int bsize = 4;
  95. int bytesPerLine;
  96. /// <inheritdoc/>
  97. public override Rect Frame {
  98. get => base.Frame;
  99. set {
  100. base.Frame = value;
  101. // Small buffers will just show the position, with 4 bytes
  102. bytesPerLine = 4;
  103. if (value.Width - displayWidth > 17)
  104. bytesPerLine = 4 * ((value.Width - displayWidth) / 18);
  105. }
  106. }
  107. //
  108. // This is used to support editing of the buffer on a peer List<>,
  109. // the offset corresponds to an offset relative to DisplayStart, and
  110. // the buffer contains the contents of a screenful of data, so the
  111. // offset is relative to the buffer.
  112. //
  113. //
  114. byte GetData (byte [] buffer, int offset, out bool edited)
  115. {
  116. var pos = DisplayStart + offset;
  117. if (edits.TryGetValue (pos, out byte v)) {
  118. edited = true;
  119. return v;
  120. }
  121. edited = false;
  122. return buffer [offset];
  123. }
  124. ///<inheritdoc/>
  125. public override void Redraw (Rect bounds)
  126. {
  127. Attribute currentAttribute;
  128. var current = ColorScheme.Focus;
  129. Driver.SetAttribute (current);
  130. Move (0, 0);
  131. var frame = Frame;
  132. var nblocks = bytesPerLine / 4;
  133. var data = new byte [nblocks * 4 * frame.Height];
  134. Source.Position = displayStart;
  135. var n = source.Read (data, 0, data.Length);
  136. int activeColor = ColorScheme.HotNormal;
  137. int trackingColor = ColorScheme.HotFocus;
  138. for (int line = 0; line < frame.Height; line++) {
  139. var lineRect = new Rect (0, line, frame.Width, 1);
  140. if (!bounds.Contains (lineRect))
  141. continue;
  142. Move (0, line);
  143. Driver.SetAttribute (ColorScheme.HotNormal);
  144. Driver.AddStr (string.Format ("{0:x8} ", displayStart + line * nblocks * 4));
  145. currentAttribute = ColorScheme.HotNormal;
  146. SetAttribute (ColorScheme.Normal);
  147. for (int block = 0; block < nblocks; block++) {
  148. for (int b = 0; b < 4; b++) {
  149. var offset = (line * nblocks * 4) + block * 4 + b;
  150. bool edited;
  151. var value = GetData (data, offset, out edited);
  152. if (offset + displayStart == position || edited)
  153. SetAttribute (leftSide ? activeColor : trackingColor);
  154. else
  155. SetAttribute (ColorScheme.Normal);
  156. Driver.AddStr (offset >= n ? " " : string.Format ("{0:x2}", value));
  157. SetAttribute (ColorScheme.Normal);
  158. Driver.AddRune (' ');
  159. }
  160. Driver.AddStr (block + 1 == nblocks ? " " : "| ");
  161. }
  162. for (int bitem = 0; bitem < nblocks * 4; bitem++) {
  163. var offset = line * nblocks * 4 + bitem;
  164. bool edited = false;
  165. Rune c = ' ';
  166. if (offset >= n)
  167. c = ' ';
  168. else {
  169. var b = GetData (data, offset, out edited);
  170. if (b < 32)
  171. c = '.';
  172. else if (b > 127)
  173. c = '.';
  174. else
  175. c = b;
  176. }
  177. if (offset + displayStart == position || edited)
  178. SetAttribute (leftSide ? trackingColor : activeColor);
  179. else
  180. SetAttribute (ColorScheme.Normal);
  181. Driver.AddRune (c);
  182. }
  183. }
  184. void SetAttribute (Attribute attribute)
  185. {
  186. if (currentAttribute != attribute) {
  187. currentAttribute = attribute;
  188. Driver.SetAttribute (attribute);
  189. }
  190. }
  191. }
  192. ///<inheritdoc/>
  193. public override void PositionCursor ()
  194. {
  195. var delta = (int)(position - displayStart);
  196. var line = delta / bytesPerLine;
  197. var item = delta % bytesPerLine;
  198. var block = item / 4;
  199. var column = (item % 4) * 3;
  200. if (leftSide)
  201. Move (displayWidth + block * 14 + column + (firstNibble ? 0 : 1), line);
  202. else
  203. Move (displayWidth + (bytesPerLine / 4) * 14 + item - 1, line);
  204. }
  205. void RedisplayLine (long pos)
  206. {
  207. var delta = (int)(pos - DisplayStart);
  208. var line = delta / bytesPerLine;
  209. SetNeedsDisplay (new Rect (0, line, Frame.Width, 1));
  210. }
  211. void CursorRight ()
  212. {
  213. RedisplayLine (position);
  214. if (leftSide) {
  215. if (firstNibble) {
  216. firstNibble = false;
  217. return;
  218. } else
  219. firstNibble = true;
  220. }
  221. if (position < source.Length)
  222. position++;
  223. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  224. SetDisplayStart (DisplayStart + bytesPerLine);
  225. SetNeedsDisplay ();
  226. } else
  227. RedisplayLine (position);
  228. }
  229. void MoveUp (int bytes)
  230. {
  231. RedisplayLine (position);
  232. position -= bytes;
  233. if (position < 0)
  234. position = 0;
  235. if (position < DisplayStart) {
  236. SetDisplayStart (DisplayStart - bytes);
  237. SetNeedsDisplay ();
  238. } else
  239. RedisplayLine (position);
  240. }
  241. void MoveDown (int bytes)
  242. {
  243. RedisplayLine (position);
  244. if (position + bytes < source.Length)
  245. position += bytes;
  246. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  247. SetDisplayStart (DisplayStart + bytes);
  248. SetNeedsDisplay ();
  249. } else
  250. RedisplayLine (position);
  251. }
  252. /// <inheritdoc/>
  253. public override bool ProcessKey (KeyEvent keyEvent)
  254. {
  255. switch (keyEvent.Key) {
  256. case Key.CursorLeft:
  257. RedisplayLine (position);
  258. if (leftSide) {
  259. if (!firstNibble) {
  260. firstNibble = true;
  261. return true;
  262. }
  263. firstNibble = false;
  264. }
  265. if (position == 0)
  266. return true;
  267. if (position - 1 < DisplayStart) {
  268. SetDisplayStart (displayStart - bytesPerLine);
  269. SetNeedsDisplay ();
  270. } else
  271. RedisplayLine (position);
  272. position--;
  273. break;
  274. case Key.CursorRight:
  275. CursorRight ();
  276. break;
  277. case Key.CursorDown:
  278. MoveDown (bytesPerLine);
  279. break;
  280. case Key.CursorUp:
  281. MoveUp (bytesPerLine);
  282. break;
  283. case Key.Enter:
  284. leftSide = !leftSide;
  285. RedisplayLine (position);
  286. firstNibble = true;
  287. break;
  288. case ((int)'v' + Key.AltMask):
  289. case Key.PageUp:
  290. MoveUp (bytesPerLine * Frame.Height);
  291. break;
  292. case Key.V | Key.CtrlMask:
  293. case Key.PageDown:
  294. MoveDown (bytesPerLine * Frame.Height);
  295. break;
  296. case Key.Home:
  297. DisplayStart = 0;
  298. SetNeedsDisplay ();
  299. break;
  300. default:
  301. if (leftSide) {
  302. int value = -1;
  303. var k = (char)keyEvent.Key;
  304. if (k >= 'A' && k <= 'F')
  305. value = k - 'A' + 10;
  306. else if (k >= 'a' && k <= 'f')
  307. value = k - 'a' + 10;
  308. else if (k >= '0' && k <= '9')
  309. value = k - '0';
  310. else
  311. return false;
  312. byte b;
  313. if (!edits.TryGetValue (position, out b)) {
  314. source.Position = position;
  315. b = (byte)source.ReadByte ();
  316. }
  317. RedisplayLine (position);
  318. if (firstNibble) {
  319. firstNibble = false;
  320. b = (byte)(b & 0xf | (value << 4));
  321. edits [position] = b;
  322. } else {
  323. b = (byte)(b & 0xf0 | value);
  324. edits [position] = b;
  325. CursorRight ();
  326. }
  327. return true;
  328. } else
  329. return false;
  330. }
  331. PositionCursor ();
  332. return true;
  333. }
  334. /// <summary>
  335. /// Gets or sets whether this <see cref="HexView"/> allow editing of the <see cref="Stream"/>
  336. /// of the underlying <see cref="Stream"/>.
  337. /// </summary>
  338. /// <value><c>true</c> if allow edits; otherwise, <c>false</c>.</value>
  339. public bool AllowEdits { get; set; }
  340. /// <summary>
  341. /// Gets a <see cref="SortedDictionary{TKey, TValue}"/> describing the edits done to the <see cref="HexView"/>.
  342. /// Each Key indicates an offset where an edit was made and the Value is the changed byte.
  343. /// </summary>
  344. /// <value>The edits.</value>
  345. public IReadOnlyDictionary<long, byte> Edits => edits;
  346. /// <summary>
  347. /// This method applies andy edits made to the <see cref="Stream"/> and resets the
  348. /// contents of the <see cref="Edits"/> property
  349. /// </summary>
  350. public void ApplyEdits ()
  351. {
  352. foreach (var kv in edits) {
  353. source.Position = kv.Key;
  354. source.WriteByte (kv.Value);
  355. }
  356. edits = new SortedDictionary<long, byte> ();
  357. }
  358. }
  359. }