HexView.cs 10 KB

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