Repository navigation
Expand file tree
/
Copy pathBinaryFileViewer.axaml.cs
More file actions
410 lines (341 loc) · 13.4 KB
/
Copy pathBinaryFileViewer.axaml.cs
File metadata and controls
410 lines (341 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
using System;
using System.Globalization;
using System.Text;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace SourceGit.Views
{
public class BinaryFileAddressTextBox : TextBox
{
protected override Type StyleKeyOverride => typeof(TextBox);
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
PastingFromClipboard += OnPastingFromClipboard;
}
protected override void OnUnloaded(RoutedEventArgs e)
{
PastingFromClipboard -= OnPastingFromClipboard;
base.OnUnloaded(e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
if (string.IsNullOrEmpty(e.Text))
return;
var builder = new StringBuilder(e.Text.Length);
var chars = e.Text.ToCharArray();
foreach (var ch in chars)
{
if ((ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'f') ||
(ch >= 'A' && ch <= 'F'))
builder.Append(ch);
if (builder.Length >= 8)
break;
}
e.Text = builder.ToString();
base.OnTextInput(e);
}
private async void OnPastingFromClipboard(object sender, RoutedEventArgs e)
{
e.Handled = true;
try
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard != null)
{
var text = await clipboard.TryGetTextAsync();
if (!string.IsNullOrEmpty(text))
OnTextInput(new TextInputEventArgs() { Text = text });
}
}
catch
{
// Ignore exceptions
}
}
}
public class HexViewer : Control
{
public static readonly DirectProperty<HexViewer, long> OffsetProperty =
AvaloniaProperty.RegisterDirect<HexViewer, long>(
nameof(Offset),
static o => o.Offset,
static (o, v) => o.Offset = v);
public long Offset
{
get => _offset;
set
{
if (SetAndRaise(OffsetProperty, ref _offset, value))
InvalidateVisual();
}
}
public static readonly StyledProperty<IBrush> HeaderForegroundProperty =
AvaloniaProperty.Register<HexViewer, IBrush>(nameof(HeaderForeground), Brushes.White);
public IBrush HeaderForeground
{
get => GetValue(HeaderForegroundProperty);
set => SetValue(HeaderForegroundProperty, value);
}
public static readonly StyledProperty<IBrush> ForegroundProperty =
AvaloniaProperty.Register<HexViewer, IBrush>(nameof(Foreground), Brushes.White);
public IBrush Foreground
{
get => GetValue(ForegroundProperty);
set => SetValue(ForegroundProperty, value);
}
public const double HEADER_HEIGHT = 24.0;
public const double LINE_HEIGHT = 18.0;
public const double BYTE_CELL_WIDTH = 22.0;
public const int BYTES_PER_LINE = 16;
public const int BYTES_PER_LINE_HALF = 8;
public const double FONT_SIZE = 13;
public void SetHighlightedIndex(long idx)
{
if (idx == _highlightedIdx)
return;
_highlightedIdx = idx;
InvalidateVisual();
}
public override void Render(DrawingContext context)
{
base.Render(context);
if (DataContext is not Models.BinaryFile vm)
return;
context.FillRectangle(Brushes.Transparent, new Rect(0, 0, Bounds.Width, Bounds.Height));
var typeface = new Typeface("fonts:SourceGit#JetBrains Mono NL");
var foreground = Foreground;
var headerForeground = HeaderForeground;
var highlightedBackground = new SolidColorBrush(Colors.Red, 0.2);
var highlightedBorder = new Pen(Brushes.Red, 0.5);
var test = new FormattedText(
"F",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FONT_SIZE,
foreground);
var addrColumnWidth = test.Width * 9;
var x = addrColumnWidth + 16.0;
_charWidth = test.Width;
_first8BytesX = x;
_second8BytesX = x + (BYTE_CELL_WIDTH * BYTES_PER_LINE_HALF) + 16.0;
_asciiColumnX = _second8BytesX + (BYTE_CELL_WIDTH * BYTES_PER_LINE_HALF) + 16.0;
for (int i = 0; i < BYTES_PER_LINE; i++)
{
var hexLabel = new FormattedText(
i.ToString("X1"),
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FONT_SIZE,
headerForeground);
var startX = x + (BYTE_CELL_WIDTH - hexLabel.Width) * 0.5;
var startY = (HEADER_HEIGHT - hexLabel.Height) * 0.5;
context.DrawText(hexLabel, new Point(startX, startY));
x += BYTE_CELL_WIDTH;
if (i == 7 || i == 15)
x += 16.0;
}
var dataSize = (long)Math.Ceiling((Bounds.Height - HEADER_HEIGHT) / LINE_HEIGHT) * BYTES_PER_LINE;
var data = vm.Read(_offset, dataSize);
if (data.Count == 0)
return;
x = 0.0;
var y = HEADER_HEIGHT - LINE_HEIGHT;
var columnIdx = 0;
for (var i = 0; i < data.Count; i++)
{
if (i % BYTES_PER_LINE == 0)
{
columnIdx = 0;
x = 0;
y += LINE_HEIGHT;
var addr = new FormattedText(
(_offset + i).ToString("X8") + ":",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FONT_SIZE,
headerForeground);
context.DrawText(addr, new Point(x, y + (LINE_HEIGHT - addr.Height) * 0.5));
x += addrColumnWidth + 16.0;
}
var isHighlighted = (i + _offset) == _highlightedIdx;
var hex = data[i];
var hexLabel = new FormattedText(
hex.ToString("X2"),
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FONT_SIZE,
hex == 0 ? Brushes.Gray : foreground);
var ch = (char)hex;
var isPrintable = (hex >= 0x20 && hex <= 0x7E);
var chLabel = new FormattedText(
isPrintable ? ch.ToString() : ".",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FONT_SIZE,
isPrintable ? Brushes.Green : Brushes.Gray);
var hexX = x + (BYTE_CELL_WIDTH - hexLabel.Width) * 0.5;
var hexY = y + (LINE_HEIGHT - hexLabel.Height) * 0.5;
if (isHighlighted)
context.DrawRectangle(highlightedBackground, highlightedBorder, new Rect(x, y, BYTE_CELL_WIDTH, LINE_HEIGHT), 2, 2);
context.DrawText(hexLabel, new Point(hexX, hexY));
var asciiX = _asciiColumnX + columnIdx * test.Width;
var asciiY = y + (LINE_HEIGHT - chLabel.Height) * 0.5;
if (isHighlighted)
context.DrawRectangle(highlightedBackground, highlightedBorder, new Rect(asciiX, y, test.Width, LINE_HEIGHT), 2, 2);
context.DrawText(chLabel, new Point(asciiX, asciiY));
x += BYTE_CELL_WIDTH;
if (columnIdx == 7 || columnIdx == 15)
x += 16.0;
columnIdx++;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (DataContext is not Models.BinaryFile vm)
return;
var pos = e.GetPosition(this);
var testX = pos.X;
var testY = pos.Y - HEADER_HEIGHT;
if (testX <= _first8BytesX || testY <= 0)
return;
long columnIdx = -1;
if (testX >= _asciiColumnX)
{
var column = (testX - _asciiColumnX) / _charWidth;
if (column < 16)
columnIdx = (long)Math.Floor(column);
}
else if (testX >= _second8BytesX)
{
var column = (testX - _second8BytesX) / BYTE_CELL_WIDTH;
if (column < 8)
columnIdx = (long)Math.Floor(column) + 8;
}
else
{
var column = (testX - _first8BytesX) / BYTE_CELL_WIDTH;
if (column < 8)
columnIdx = (long)Math.Floor(column);
}
if (columnIdx < 0)
return;
var rowIdx = (long)Math.Floor(testY / LINE_HEIGHT);
var idx = _offset + rowIdx * BYTES_PER_LINE + columnIdx;
if (idx >= vm.Size)
return;
SetHighlightedIndex(idx);
}
private long _offset = 0;
private double _charWidth = 0;
private double _first8BytesX = 0;
private double _second8BytesX = 0;
private double _asciiColumnX = 0;
private long _highlightedIdx = -1;
}
public partial class BinaryFileViewer : ChromelessWindow
{
public BinaryFileViewer()
{
CloseOnESC = true;
InitializeComponent();
}
protected override void OnOpened(EventArgs e)
{
base.OnOpened(e);
// Queue loading to the next frame to avoid blocking the window-opening.
Dispatcher.UIThread.Post(async () =>
{
if (DataContext is ViewModels.BinaryFileViewer vm)
await vm.LoadAsync();
});
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (DataContext is ViewModels.BinaryFileViewer vm)
vm.Cleanup();
}
private void OnContentPointerWheelChanged(object sender, PointerWheelEventArgs e)
{
if (sender is not Grid grid)
return;
var scroller = grid.FindDescendantOfType<ScrollBar>();
if (scroller == null || !scroller.IsVisible)
return;
scroller.Value -= e.Delta.Y * HexViewer.LINE_HEIGHT;
}
private void OnContentSizeChanged(object sender, SizeChangedEventArgs e)
{
if (sender is not Grid { DataContext: Models.BinaryFile file } grid)
return;
var scroller = grid.FindDescendantOfType<ScrollBar>();
if (scroller == null)
return;
var viewport = grid.Bounds.Height - HexViewer.HEADER_HEIGHT;
var max = Math.Ceiling(file.Size * 1.0 / HexViewer.BYTES_PER_LINE) * HexViewer.LINE_HEIGHT - viewport;
if (max <= 0)
{
scroller.IsVisible = false;
}
else
{
scroller.IsVisible = true;
scroller.ViewportSize = viewport;
scroller.Maximum = max;
}
}
private void OnScrollBarValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (sender is ScrollBar scroller)
{
var viewer = this.FindDescendantOfType<HexViewer>();
if (viewer != null)
viewer.Offset = (long)(Math.Ceiling(scroller.Value / HexViewer.LINE_HEIGHT) * HexViewer.BYTES_PER_LINE);
}
}
private void OnGotoAddressTextChanged(object sender, TextChangedEventArgs e)
{
if (sender is BinaryFileAddressTextBox textBox &&
DataContext is ViewModels.BinaryFileViewer { Content: { } file })
{
var text = textBox.Text;
if (string.IsNullOrEmpty(text))
return;
long idx = 0;
try
{
idx = Convert.ToInt64(text, 16);
}
catch
{
// Ignore parsing errors
}
if (idx < 0 || idx >= file.Size)
return;
var scroller = ContentPanel.FindDescendantOfType<ScrollBar>();
if (scroller is { IsVisible: true })
{
var offset = Math.Floor(idx * 1.0 / HexViewer.BYTES_PER_LINE) * HexViewer.LINE_HEIGHT - (scroller.ViewportSize * 0.5);
scroller.Value = Math.Max(0, offset);
}
var viewer = this.FindDescendantOfType<HexViewer>(false);
viewer?.SetHighlightedIndex(idx);
}
}
}
}