HexView.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 an editor view over a System.IO.Stream
  14. /// </summary>
  15. /// <remarks>
  16. /// <para>
  17. /// This provides a hex editor on top of a seekable stream with the left side showing an hex
  18. /// dump of the values in the 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. /// If you want to enable editing, set the AllowsEdits property, once that is done, the user
  26. /// can make changes to the hexadecimal values of the stream. Any changes done are tracked
  27. /// in the Edits property which is a sorted dictionary indicating the position where the
  28. /// change was made and the new value. A convenience ApplyEdits method can be used to c
  29. /// apply the methods to the underlying stream.
  30. /// </para>
  31. /// <para>
  32. /// It is possible to control the first byte shown by setting the DisplayStart property
  33. /// to the offset that you want to start viewing.
  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. /// Creates and instance of the HexView that will render a seekable stream in hex on the allocated view region.
  43. /// </summary>
  44. /// <param name="source">Source stream, this stream should support seeking, or this will raise an exceotion.</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. /// The source stream to display on the hex view, the stream should support seeking.
  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. /// Configures the initial offset to be displayed at the top
  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 cref="Frame"/>
  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 cref="Redraw"/>
  121. public override void Redraw (Rect region)
  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 (!region.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. /// <summary>
  189. /// Positions the cursor based for the hex view
  190. /// </summary>
  191. public override void PositionCursor ()
  192. {
  193. var delta = (int)(position - displayStart);
  194. var line = delta / bytesPerLine;
  195. var item = delta % bytesPerLine;
  196. var block = item / 4;
  197. var column = (item % 4) * 3;
  198. if (leftSide)
  199. Move (displayWidth + block * 14 + column + (firstNibble ? 0 : 1), line);
  200. else
  201. Move (displayWidth + (bytesPerLine / 4) * 14 + item - 1, line);
  202. }
  203. void RedisplayLine (long pos)
  204. {
  205. var delta = (int) (pos - DisplayStart);
  206. var line = delta / bytesPerLine;
  207. SetNeedsDisplay (new Rect (0, line, Frame.Width, 1));
  208. }
  209. void CursorRight ()
  210. {
  211. RedisplayLine (position);
  212. if (leftSide) {
  213. if (firstNibble) {
  214. firstNibble = false;
  215. return;
  216. } else
  217. firstNibble = true;
  218. }
  219. if (position < source.Length)
  220. position++;
  221. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  222. SetDisplayStart (DisplayStart + bytesPerLine);
  223. SetNeedsDisplay ();
  224. } else
  225. RedisplayLine (position);
  226. }
  227. void MoveUp (int bytes)
  228. {
  229. RedisplayLine (position);
  230. position -= bytes;
  231. if (position < 0)
  232. position = 0;
  233. if (position < DisplayStart) {
  234. SetDisplayStart (DisplayStart - bytes);
  235. SetNeedsDisplay ();
  236. } else
  237. RedisplayLine (position);
  238. }
  239. void MoveDown (int bytes)
  240. {
  241. RedisplayLine (position);
  242. if (position + bytes < source.Length)
  243. position += bytes;
  244. if (position >= (DisplayStart + bytesPerLine * Frame.Height)) {
  245. SetDisplayStart (DisplayStart + bytes);
  246. SetNeedsDisplay ();
  247. } else
  248. RedisplayLine (position);
  249. }
  250. /// <inheritdoc cref="ProcessKey"/>
  251. public override bool ProcessKey (KeyEvent keyEvent)
  252. {
  253. switch (keyEvent.Key) {
  254. case Key.CursorLeft:
  255. RedisplayLine (position);
  256. if (leftSide) {
  257. if (!firstNibble) {
  258. firstNibble = true;
  259. return true;
  260. }
  261. firstNibble = false;
  262. }
  263. if (position == 0)
  264. return true;
  265. if (position - 1 < DisplayStart) {
  266. SetDisplayStart (displayStart - bytesPerLine);
  267. SetNeedsDisplay ();
  268. } else
  269. RedisplayLine (position);
  270. position--;
  271. break;
  272. case Key.CursorRight:
  273. CursorRight ();
  274. break;
  275. case Key.CursorDown:
  276. MoveDown (bytesPerLine);
  277. break;
  278. case Key.CursorUp:
  279. MoveUp (bytesPerLine);
  280. break;
  281. case Key.Tab:
  282. leftSide = !leftSide;
  283. RedisplayLine (position);
  284. firstNibble = true;
  285. break;
  286. case ((int)'v' + Key.AltMask):
  287. case Key.PageUp:
  288. MoveUp (bytesPerLine * Frame.Height);
  289. break;
  290. case Key.ControlV:
  291. case Key.PageDown:
  292. MoveDown (bytesPerLine * Frame.Height);
  293. break;
  294. case Key.Home:
  295. DisplayStart = 0;
  296. SetNeedsDisplay ();
  297. break;
  298. default:
  299. if (leftSide) {
  300. int value = -1;
  301. var k = (char)keyEvent.Key;
  302. if (k >= 'A' && k <= 'F')
  303. value = k - 'A' + 10;
  304. else if (k >= 'a' && k <= 'f')
  305. value = k - 'a' + 10;
  306. else if (k >= '0' && k <= '9')
  307. value = k - '0';
  308. else
  309. return false;
  310. byte b;
  311. if (!edits.TryGetValue (position, out b)) {
  312. source.Position = position;
  313. b = (byte)source.ReadByte ();
  314. }
  315. RedisplayLine (position);
  316. if (firstNibble) {
  317. firstNibble = false;
  318. b = (byte)(b & 0xf | (value << 4));
  319. edits [position] = b;
  320. } else {
  321. b = (byte)(b & 0xf0 | value);
  322. edits [position] = b;
  323. CursorRight ();
  324. }
  325. return true;
  326. } else
  327. return false;
  328. }
  329. PositionCursor ();
  330. return true;
  331. }
  332. /// <summary>
  333. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.HexView"/> allow editing of the contents of the underlying stream.
  334. /// </summary>
  335. /// <value><c>true</c> if allow edits; otherwise, <c>false</c>.</value>
  336. public bool AllowEdits { get; set; }
  337. /// <summary>
  338. /// Gets a list of the edits done to the buffer which is a sorted dictionary with the positions where the edit took place and the value that was set.
  339. /// </summary>
  340. /// <value>The edits.</value>
  341. public IReadOnlyDictionary<long,byte> Edits => edits;
  342. /// <summary>
  343. /// This method applies the edits to the stream and resets the contents of the Edits property
  344. /// </summary>
  345. public void ApplyEdits ()
  346. {
  347. foreach (var kv in edits) {
  348. source.Position = kv.Key;
  349. source.WriteByte (kv.Value);
  350. }
  351. edits = new SortedDictionary<long, byte> ();
  352. }
  353. }
  354. }