2
0

HexView.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. public override Rect Frame {
  93. get => base.Frame;
  94. set {
  95. base.Frame = value;
  96. // Small buffers will just show the position, with 4 bytes
  97. bytesPerLine = 4;
  98. if (value.Width - displayWidth > 17)
  99. bytesPerLine = 4 * ((value.Width - displayWidth) / 18);
  100. }
  101. }
  102. //
  103. // This is used to support editing of the buffer on a peer List<>,
  104. // the offset corresponds to an offset relative to DisplayStart, and
  105. // the buffer contains the contents of a screenful of data, so the
  106. // offset is relative to the buffer.
  107. //
  108. //
  109. byte GetData (byte [] buffer, int offset, out bool edited)
  110. {
  111. var pos = DisplayStart + offset;
  112. if (edits.TryGetValue (pos, out byte v)) {
  113. edited = true;
  114. return v;
  115. }
  116. edited = false;
  117. return buffer [offset];
  118. }
  119. public override void Redraw (Rect region)
  120. {
  121. Attribute currentAttribute;
  122. var current = ColorScheme.Focus;
  123. Driver.SetAttribute (current);
  124. Move (0, 0);
  125. var frame = Frame;
  126. var nblocks = bytesPerLine / 4;
  127. var data = new byte [nblocks * 4 * frame.Height];
  128. Source.Position = displayStart;
  129. var n = source.Read (data, 0, data.Length);
  130. int activeColor = ColorScheme.HotNormal;
  131. int trackingColor = ColorScheme.HotFocus;
  132. for (int line = 0; line < frame.Height; line++) {
  133. var lineRect = new Rect (0, line, frame.Width, 1);
  134. if (!region.Contains (lineRect))
  135. continue;
  136. Move (0, line);
  137. Driver.SetAttribute (ColorScheme.HotNormal);
  138. Driver.AddStr (string.Format ("{0:x8} ", displayStart + line * nblocks * 4));
  139. currentAttribute = ColorScheme.HotNormal;
  140. SetAttribute (ColorScheme.Normal);
  141. for (int block = 0; block < nblocks; block++) {
  142. for (int b = 0; b < 4; b++) {
  143. var offset = (line * nblocks * 4) + block * 4 + b;
  144. bool edited;
  145. var value = GetData (data, offset, out edited);
  146. if (offset + displayStart == position || edited)
  147. SetAttribute (leftSide ? activeColor : trackingColor);
  148. else
  149. SetAttribute (ColorScheme.Normal);
  150. Driver.AddStr (offset >= n ? " " : string.Format ("{0:x2}", value));
  151. SetAttribute (ColorScheme.Normal);
  152. Driver.AddRune (' ');
  153. }
  154. Driver.AddStr (block + 1 == nblocks ? " " : "| ");
  155. }
  156. for (int bitem = 0; bitem < nblocks * 4; bitem++) {
  157. var offset = line * nblocks * 4 + bitem;
  158. bool edited = false;
  159. Rune c = ' ';
  160. if (offset >= n)
  161. c = ' ';
  162. else {
  163. var b = GetData (data, offset, out edited);
  164. if (b < 32)
  165. c = '.';
  166. else if (b > 127)
  167. c = '.';
  168. else
  169. c = b;
  170. }
  171. if (offset + displayStart == position || edited)
  172. SetAttribute (leftSide ? trackingColor : activeColor);
  173. else
  174. SetAttribute (ColorScheme.Normal);
  175. Driver.AddRune (c);
  176. }
  177. }
  178. void SetAttribute (Attribute attribute)
  179. {
  180. if (currentAttribute != attribute) {
  181. currentAttribute = attribute;
  182. Driver.SetAttribute (attribute);
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// Positions the cursor based for the hex view
  188. /// </summary>
  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. public override bool ProcessKey (KeyEvent keyEvent)
  249. {
  250. switch (keyEvent.Key) {
  251. case Key.CursorLeft:
  252. RedisplayLine (position);
  253. if (leftSide) {
  254. if (!firstNibble) {
  255. firstNibble = true;
  256. return true;
  257. }
  258. firstNibble = false;
  259. }
  260. if (position == 0)
  261. return true;
  262. if (position - 1 < DisplayStart) {
  263. SetDisplayStart (displayStart - bytesPerLine);
  264. SetNeedsDisplay ();
  265. } else
  266. RedisplayLine (position);
  267. position--;
  268. break;
  269. case Key.CursorRight:
  270. CursorRight ();
  271. break;
  272. case Key.CursorDown:
  273. MoveDown (bytesPerLine);
  274. break;
  275. case Key.CursorUp:
  276. MoveUp (bytesPerLine);
  277. break;
  278. case Key.Tab:
  279. leftSide = !leftSide;
  280. RedisplayLine (position);
  281. firstNibble = true;
  282. break;
  283. case ((int)'v' + Key.AltMask):
  284. case Key.PageUp:
  285. MoveUp (bytesPerLine * Frame.Height);
  286. break;
  287. case Key.ControlV:
  288. case Key.PageDown:
  289. MoveDown (bytesPerLine * Frame.Height);
  290. break;
  291. case Key.Home:
  292. DisplayStart = 0;
  293. SetNeedsDisplay ();
  294. break;
  295. default:
  296. if (leftSide) {
  297. int value = -1;
  298. var k = (char)keyEvent.Key;
  299. if (k >= 'A' && k <= 'F')
  300. value = k - 'A' + 10;
  301. else if (k >= 'a' && k <= 'f')
  302. value = k - 'a' + 10;
  303. else if (k >= '0' && k <= '9')
  304. value = k - '0';
  305. else
  306. return false;
  307. byte b;
  308. if (!edits.TryGetValue (position, out b)) {
  309. source.Position = position;
  310. b = (byte)source.ReadByte ();
  311. }
  312. RedisplayLine (position);
  313. if (firstNibble) {
  314. firstNibble = false;
  315. b = (byte)(b & 0xf | (value << 4));
  316. edits [position] = b;
  317. } else {
  318. b = (byte)(b & 0xf0 | value);
  319. edits [position] = b;
  320. CursorRight ();
  321. }
  322. return true;
  323. } else
  324. return false;
  325. }
  326. PositionCursor ();
  327. return true;
  328. }
  329. /// <summary>
  330. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.HexView"/> allow editing of the contents of the underlying stream.
  331. /// </summary>
  332. /// <value><c>true</c> if allow edits; otherwise, <c>false</c>.</value>
  333. public bool AllowEdits { get; set; }
  334. /// <summary>
  335. /// 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.
  336. /// </summary>
  337. /// <value>The edits.</value>
  338. public IReadOnlyDictionary<long,byte> Edits => edits;
  339. /// <summary>
  340. /// This method applies the edits to the stream and resets the contents of the Edits property
  341. /// </summary>
  342. public void ApplyEdits ()
  343. {
  344. foreach (var kv in edits) {
  345. source.Position = kv.Key;
  346. source.WriteByte (kv.Value);
  347. }
  348. edits = new SortedDictionary<long, byte> ();
  349. }
  350. }
  351. }