-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMainForm.cs
3710 lines (3258 loc) · 161 KB
/
MainForm.cs
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// My imported classes
using EditClipboardContents;
using static EditClipboardContents.ClipboardFormats;
using Microsoft.SqlServer.Management.HadrData;
// Disable IDE warnings that showed up after going from C# 7 to C# 9
#pragma warning disable IDE0079 // Disable message about unnecessary suppression
#pragma warning disable IDE1006 // Disable messages about capitalization of control names
#pragma warning disable IDE0063 // Disable messages about Using expression simplification
#pragma warning disable IDE0090 // Disable messages about New expression simplification
#pragma warning disable IDE0028,IDE0300,IDE0305 // Disable message about collection initialization
#pragma warning disable IDE0074 // Disable message about compound assignment for checking if null
#pragma warning disable IDE0066 // Disable message about switch case expression
// Nullable reference types
#nullable enable
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Windows.Forms.VisualStyles;
using System.Drawing.Imaging;
using System.Reflection;
using System.Globalization;
using System.Drawing.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Threading.Tasks;
using System.Data.Common;
using System.Windows.Forms.Automation;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.IO.Compression;
using System.CodeDom.Compiler;
using System.Drawing.Drawing2D;
namespace EditClipboardContents
{
public partial class MainForm : Form
{
private readonly List<ClipboardItem> clipboardItems = new List<ClipboardItem>();
//private List<ClipboardItem> editedClipboardItems = new List<ClipboardItem>();
private SortableBindingList<ClipboardItem> editedClipboardItems = new SortableBindingList<ClipboardItem>();
private RichTextBoxContextMenuManager contextMenuManager;
// Other globals
private readonly bool _debugMode;
public static bool anyPendingChanges = false;
public static bool enableSplitHexView = false;
public ClipboardItem? itemBeforeCellEditClone = null;
public RecentRightClickedCell? recentRightClickedCell;
// Global constants
public const int maxRawSizeDefault = 50000;
// Variables to store info about initial GUI state
public int hexTextBoxTopBuffer { get; init; }
public string defaultLoadingLabelText { get; init; }
public Color defaultCellForeColor { get; init; }
public Size defaultToolstripButtonSize { get; init; }
public Size defaultToolstripButtonImageSize { get; init; }
public Point splitContainerMainDefaultPosition { get; init; }
public Size defaultToolstripSize { get; init; }
public Point splitContainerInnerTextBoxesDefaultLocation { get; init; }
// Store recent GUI states
public int previousWindowHeight = 0;
public int previousSplitterDistance = 0;
public bool isResizing = false;
public int testCounter = 0; // For testing and displaying number of calls of random stuff
// Get version number from assembly
static readonly System.Version versionFull = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
public readonly string versionString = $"{versionFull.Major}.{versionFull.Minor}.{versionFull.Build}";
// Dictionary of formats that can be synthesized from other formats, and which they can be synthesized to
private static readonly Dictionary<uint, List<uint>> SynthesizedFormatsMap = new Dictionary<uint, List<uint>>()
{
{ 2, new List<uint> { 8, 17 } }, // CF_BITMAP -> CF_DIB, CF_DIBV5
{ 8, new List<uint> { 2, 9, 17 } }, // CF_DIB -> CF_BITMAP, CF_PALETTE, CF_DIBV5
{ 17, new List<uint> { 2, 8, 9 } }, // CF_DIBV5 -> CF_BITMAP, CF_DIB, CF_PALETTE
{ 14, new List<uint> { 3 } }, // CF_ENHMETAFILE -> CF_METAFILEPICT
{ 3, new List<uint> { 14 } }, // CF_METAFILEPICT -> CF_ENHMETAFILE
{ 7, new List<uint> { 1, 13 } }, // CF_OEMTEXT -> CF_TEXT, CF_UNICODETEXT
{ 1, new List<uint> { 7, 13 } }, // CF_TEXT -> CF_OEMTEXT, CF_UNICODETEXT
{ 13, new List<uint> { 7, 1 } }, // CF_UNICODETEXT -> CF_OEMTEXT, CF_TEXT
};
// List of format names that are potentially synthesized by Windows and will be re-created if removed
private static readonly List<string> SynthesizedFormatNames = new List<string>
{
"CF_LOCALE", // Not technically synthesized but will be re-created if CF_TEXT is set
"CF_DIB",
"CF_BITMAP",
"CF_DIBV5",
"CF_PALETTE",
"CF_ENHMETAFILE",
"CF_METAFILEPICT",
"CF_OEMTEXT",
"CF_TEXT",
"CF_UNICODETEXT",
};
public MainForm(bool debugMode)
{
_debugMode = debugMode;
isResizing = true; // Set to true so our window resize logic in MainForm_Resize event doesn't trigger until the form is fully initialized
InitializeComponent();
// Manually set certain properties
this.Icon = Properties.Resources.EditClipboardMainIcon;
int initialPanelSize = flowLayoutPanel_HexEditOptions.Width + CompensateDPI(15);
splitterContainer_InnerTextBoxes.Panel2MinSize = initialPanelSize;
splitterContainer_InnerTextBoxes.SplitterDistance = splitterContainer_InnerTextBoxes.Width - initialPanelSize;
// Record initial values for GUI state variables
previousSplitterDistance = splitContainerMain.SplitterDistance;
previousWindowHeight = this.Height;
editedClipboardItems.ListChanged += EditedClipboardItems_ListChanged;
// Initialize context menu manager for rich text boxes
contextMenuManager = new RichTextBoxContextMenuManager();
contextMenuManager.SetSuppressionVariableForParentForm += (sender, suppress) => suppressTextBoxSelectionChange = suppress;
contextMenuManager.AttachToRichTextBox(richTextBoxContents);
contextMenuManager.AttachToRichTextBox(richTextBox_HexPlaintext);
// ----------------- Debugging mode stuff -----------------
// Always show these in DEBUG builds
#if DEBUG
labelTestCount.Visible = true;
menuEdit_RefreshDataTable.Visible = true;
labelTestMiscellaneous.Visible = true;
menuItemDebug.Visible = true;
#endif
// Show these when -debug flag is passed
if (_debugMode)
{
this.Text += " (Debug Mode)";
labelTestCount.Visible = true;
menuEdit_RefreshDataTable.Visible = true;
labelTestMiscellaneous.Visible = true;
menuItemDebug.Visible = true;
}
// -------------------------------------------------------
// Set init only GUI state variables
hexTextBoxTopBuffer = richTextBoxContents.Height - richTextBox_HexPlaintext.Height;
defaultLoadingLabelText = labelLoading.Text;
defaultCellForeColor = dataGridViewClipboard.DefaultCellStyle.ForeColor;
defaultToolstripButtonSize = toolStripButtonRefresh.Size;
defaultToolstripButtonImageSize = toolStripButtonRefresh.Image.Size;
splitContainerMainDefaultPosition = splitContainerMain.Location;
defaultToolstripSize = toolStrip1.Size;
splitContainerInnerTextBoxesDefaultLocation = splitterContainer_InnerTextBoxes.Location;
// Manually set certain button locations because they don't get placed properly on different scalings
//splitterContainer_InnerTextBoxes.SplitterDistance = CompensateDPI(splitterContainer_InnerTextBoxes.SplitterDistance);
//ManuallyPositionCertainControls();
// Early initializations
recentRightClickedCell = new RecentRightClickedCell(rowIndex: -1, columnIndex: -1);
ScaleToolstripButtons();
InitializeDataGridView();
// Initial tool settings
dropdownContentsViewMode.SelectedIndexChanged -= dropdownContentsViewMode_SelectedIndexChanged;
dropdownHexToTextEncoding.SelectedIndexChanged -= dropdownHexToTextEncoding_SelectedIndexChanged;
dropdownContentsViewMode.SelectedIndex = (int)ViewMode.Text; // Default index 0 is "Text" view mode
dropdownHexToTextEncoding.SelectedIndex = (int)EncodingMode.UTF8; // Default index 0 is "UTF-8" encoding
dropdownContentsViewMode.SelectedIndexChanged += dropdownContentsViewMode_SelectedIndexChanged;
dropdownHexToTextEncoding.SelectedIndexChanged += dropdownHexToTextEncoding_SelectedIndexChanged;
// Set color of toolstrip manually because it doesn't set it apparently
toolStrip1.BackColor = SystemColors.Control;
// Other initializations
labelVersion.Text = $"Version {versionString}";
previousWindowHeight = this.Height;
labelTestMiscellaneous.Text = $"Toolstrip size: {toolStrip1.Height.ToString()} | Scaling: {ScaleFactor()} | ImageScale: {toolStrip1.ImageScalingSize}";
isResizing = false; // Set to false so our window resize logic in MainForm_Resize event can trigger
UpdateToolLocations();
}
public int CompensateDPI(int originalValue)
{
float scaleFactor = this.DeviceDpi / 96f; // 96 is the default DPI
return (int)(originalValue * scaleFactor);
}
public int inverseDPI(int originalValue)
{
float scaleFactor = this.DeviceDpi / 96f; // 96 is the default DPI
return (int)(originalValue / scaleFactor);
}
public decimal ScaleFactor()
{
return this.DeviceDpi / 96m;
}
private void ScaleToolstripButtons()
{
// Calculate the relation between default splitter panel location and default toolstrip height
Point containerLocation = splitContainerMainDefaultPosition;
int splitContainerPositionOffset = splitContainerMainDefaultPosition.Y - defaultToolstripSize.Height;
int toolstripHeight = toolStrip1.Height;
Size buttonSize = defaultToolstripButtonSize;
//buttonSize.Width = toolstripHeight;
//buttonSize.Height = toolstripHeight;
buttonSize.Width = CompensateDPI(32);
buttonSize.Height = CompensateDPI(32);
toolStrip1.SuspendLayout();
toolStrip1.AutoSize = true;
foreach (ToolStripItem item in toolStrip1.Items)
{
if (item is ToolStripButton button)
{
button.Size = buttonSize;
button.ImageScaling = ToolStripItemImageScaling.SizeToFit;
//button.Image = ResizeSquareImage(button.Image, buttonSize);
button.AutoSize = true;
}
}
toolStrip1.ImageScalingSize = buttonSize;
toolStrip1.ResumeLayout();
// Finally set the location of the data grid view to be below the toolstrip. All other tools will adjust accordingly
toolStrip1.Height = buttonSize.Height + CompensateDPI(3);
//splitContainerMain.Location = new Point(containerLocation.X, toolStrip1.Height + splitContainerPositionOffset);
labelTestMiscellaneous.Text = $"Toolstrip size: {toolStrip1.Height.ToString()} | Scaling: {ScaleFactor()} | ImageScale: {toolStrip1.ImageScalingSize}";
}
public static int CompensateDPIStatic(int originalValue)
{
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
float dpi = graphics.DpiX;
float scaleFactor = dpi / 96f; // 96 is the default DPI
return (int)(originalValue * scaleFactor);
}
}
private void ShowLoadingIndicator(bool show)
{
// Calculate the position of the loading label based on center of SplitContainerMain Panel 1. Also ensures location uses label center
int x = splitContainerMain.Panel1.Width / 2 - labelLoading.Width / 2;
int y = splitContainerMain.Panel1.Height / 2 - labelLoading.Height / 2;
labelLoading.Location = new Point(x, y);
labelLoading.Visible = show;
// Updates the cursor
this.Cursor = show ? Cursors.WaitCursor : Cursors.Default;
// Force the form to repaint immediately
this.Update();
}
private void InitializeDataGridView()
{
dataGridViewClipboard.AutoGenerateColumns = false;
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = nameof(ClipboardItem.OriginalIndex), Name = colName.Index, HeaderText = "" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = nameof(ClipboardItem.UniqueID), Name = colName.UniqueID, HeaderText = "", Visible = false });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { Name = colName.KnownBinary, HeaderText = "💾" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { Name = colName.KnownStruct, HeaderText = "ℹ️" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = nameof(ClipboardItem.FormatName), Name = colName.FormatName, HeaderText = "Format Name" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = nameof(ClipboardItem.FormatId), Name = colName.FormatId, HeaderText = "Format ID" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = nameof(ClipboardItem.FormatType), Name = colName.FormatType, HeaderText = "Format Type" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = nameof(ClipboardItem.DataSize), Name = colName.DataSize, HeaderText = "Data Size" });
//dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "DataInfoLinesString", Name = colName.DataInfo, HeaderText = "Data Info" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { Name = colName.DataInfo, HeaderText = "Data Info" });
dataGridViewClipboard.Columns.Add(new DataGridViewTextBoxColumn { Name = colName.TextPreview, HeaderText = "Text Preview" });
// Set autosize for all columns to none so we can control individually later
foreach (DataGridViewColumn column in dataGridViewClipboard.Columns)
{
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
}
// Set unique id column to be invisible
//dataGridViewClipboard.Columns[colName.UniqueID].Visible = false;
// Set default AutoSizeMode
//dataGridViewClipboard.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewClipboard.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
// Add padding to the text preview column
// Get the current padding for text preview column
Padding textPreviewPadding = dataGridViewClipboard.Columns[colName.TextPreview].DefaultCellStyle.Padding;
textPreviewPadding.Left = 3;
dataGridViewClipboard.Columns[colName.TextPreview].DefaultCellStyle.Padding = textPreviewPadding;
Padding formatNamePadding = dataGridViewClipboard.Columns[colName.FormatName].DefaultCellStyle.Padding;
formatNamePadding.Left = 3;
dataGridViewClipboard.Columns[colName.FormatName].DefaultCellStyle.Padding = formatNamePadding;
//// Add a tooltip to display on the Known column
dataGridViewClipboard.Columns[colName.KnownBinary].ToolTipText = MyStrings.KnownFileTooltipFull;
dataGridViewClipboard.Columns[colName.KnownStruct].ToolTipText = MyStrings.KnownStructTooltip;
// Hide the row headers (the leftmost column)
dataGridViewClipboard.RowHeadersVisible = false;
// Set miscellaensous properties for specific columns
dataGridViewClipboard.Columns[colName.Index].DefaultCellStyle.ForeColor = Color.Gray;
dataGridViewClipboard.Columns[colName.Index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridViewClipboard.Columns[colName.KnownBinary].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridViewClipboard.Columns[colName.KnownBinary].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridViewClipboard.Columns[colName.KnownStruct].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridViewClipboard.Columns[colName.KnownStruct].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
// Add event handler for scroll wheel
dataGridViewClipboard.MouseWheel += new MouseEventHandler(dataGridViewClipboard_MouseWheel);
// Set the data soure of the clipboard grid view to the editedClipboardItems list
dataGridViewClipboard.DataSource = editedClipboardItems;
}
private void RefreshDataGridViewContents()
{
// Get current conditions so we can restore them after if necessary
Guid? selectedItemGUID = GetSelectedUniqueIDFromDataGridView();
DataGridViewColumn? currentSortColumn = dataGridViewClipboard.SortedColumn;
if (currentSortColumn != null && dataGridViewClipboard.SortOrder != SortOrder.None)
{
ListSortDirection currentSortDirection = dataGridViewClipboard.SortOrder == SortOrder.Ascending ? ListSortDirection.Ascending : ListSortDirection.Descending;
dataGridViewClipboard.Sort(currentSortColumn, currentSortDirection);
}
// Apply new data and sort
dataGridViewClipboard.DataSource = editedClipboardItems;
dataGridViewClipboard.Sort(dataGridViewClipboard.Columns[colName.Index], ListSortDirection.Ascending);
// Restore the selected item if there was one
if (selectedItemGUID != null)
{
SelectRowByUniqueID(selectedItemGUID.Value);
}
// Update cell values for columns that don't draw directly from the data source
foreach (ClipboardItem formatItem in editedClipboardItems)
{
List<string> dataInfo = formatItem.DataInfoList;
Guid uniqueID = formatItem.UniqueID;
string textPreview = TryParseText(formatItem.RawData, maxLength: 200, prefixEncodingType: false);
// The first item in DataInfo will have selected important info, to ensure it's not too long. The rest will show in data box in object/struct view mode
string dataInfoString;
if (dataInfo.Count <= 0 || string.IsNullOrEmpty(dataInfo[0]))
dataInfoString = MyStrings.DataNotApplicable;
else
dataInfoString = dataInfo[0];
// Manually set text preview for certain formats
if (formatItem.FormatName == "CF_LOCALE")
textPreview = "";
// "Known" Column - Display icon if the format can be exported as known binary file
string knownIcon = "";
string knownFileTooltip = "";
if (formatItem.FormatAnalysis?.HasPossibleOrKnownExtensions() == true)
{
knownIcon = "\u2713"; // ✓ (Regular, u2713) -- Also could use: ✔ (Bold, u2714), ✔ (Emoji)
if (formatItem.FormatAnalysis?.ExtensionConfidence == FormatAnalysis.Confidence.Known)
{
knownIcon = "\u2714"; // Bold check
knownFileTooltip = MyStrings.KnownFileTooltip;
}
else
knownFileTooltip = MyStrings.KnownFileTooltipLikely;
}
string knownStructIcon = "";
string knownStructTooltip = "";
if (formatItem.ClipDataObject != null || formatItem.ClipEnumObject != null)
{
knownStructIcon = "\u2713"; // Regular check
knownStructTooltip = MyStrings.KnownStructTooltip;
}
// --- Actually sets the values in the grid ---
DataGridViewRow? matchingRow = dataGridViewClipboard.Rows.Cast<DataGridViewRow?>().FirstOrDefault(r => r?.Cells[colName.UniqueID].Value.ToString() == uniqueID.ToString());
if (matchingRow != null)
{
int rowIndex = matchingRow.Index;
// Take the value variables set within the loop above and finally put them in the grid
dataGridViewClipboard.Rows[rowIndex].Cells[colName.TextPreview].Value = textPreview;
dataGridViewClipboard.Rows[rowIndex].Cells[colName.DataInfo].Value = dataInfoString;
dataGridViewClipboard.Rows[rowIndex].Cells[colName.KnownBinary].Value = knownIcon;
dataGridViewClipboard.Rows[rowIndex].Cells[colName.KnownBinary].ToolTipText = knownFileTooltip;
dataGridViewClipboard.Rows[rowIndex].Cells[colName.KnownStruct].Value = knownStructIcon;
dataGridViewClipboard.Rows[rowIndex].Cells[colName.KnownStruct].ToolTipText = knownStructTooltip;
}
// ---------------------------------------------
}
// Set default forecolor of the index column to gray
dataGridViewClipboard.Columns[colName.Index].DefaultCellStyle.ForeColor = Color.Gray;
// Set sizes of columns
foreach (DataGridViewColumn column in dataGridViewClipboard.Columns)
{
// Manually set width to minimal number to be resized auto later. Apparently autosize will only make columns larger, not smaller
column.Width = CompensateDPI(5);
// Set autosize most for most columns. Next we'll disable it again so they can be resized but start at a good size
if (column.Name != colName.TextPreview)
{
// Use all cells instead of displayed cells, otherwise those scrolled out of view won't count
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
// Disable the autosizing again so they can be resized by user
if (!(column.Name == colName.TextPreview))
{
int originalWidth = column.Width;
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
column.Resizable = DataGridViewTriState.True;
if (column.Name == colName.FormatName)
column.Width = originalWidth + 20; // Add some padding
else if (column.Name == colName.KnownBinary | column.Name == colName.KnownStruct)
column.Width = originalWidth / 2; // Make it a bit smaller
else
column.Width = originalWidth + 0; // For some reason this is necessary after setting resizable and autosize modes
}
}
// Ensure TextPreview fills remaining space
dataGridViewClipboard.Columns[colName.TextPreview].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewClipboard.Columns[colName.TextPreview].Resizable = DataGridViewTriState.True;
// If DataInfo is too long, manually set a max width
if (dataGridViewClipboard.Columns[colName.DataInfo].Width > CompensateDPI(200))
{
dataGridViewClipboard.Columns[colName.DataInfo].Width = CompensateDPI(200);
}
dataGridViewClipboard.PerformLayout();
UpdateEditControlsVisibility_AndPendingGridAppearance();
}
// Function to try and parse the raw data for text if it is text
private string TryParseText(byte[]? rawData, int maxLength = 150, bool prefixEncodingType = false)
{
if (rawData == null || rawData.Length == 0)
{
return "";
}
// Create encodings with desired parameters
var utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
var utf16Encoding = new UnicodeEncoding(bigEndian: false, byteOrderMark: true);
// Clone them to make mutable copies
utf8Encoding = (UTF8Encoding)utf8Encoding.Clone();
utf16Encoding = (UnicodeEncoding)utf16Encoding.Clone();
// Set the custom replacement fallbacks
string customInvalidChar = "[|\uFFFE\uFFFF\uFFFD|]"; // Something unique that won't be in the text
utf8Encoding.DecoderFallback = new DecoderReplacementFallback(customInvalidChar);
utf16Encoding.DecoderFallback = new DecoderReplacementFallback(customInvalidChar);
// Now you can use utf8Encoding and utf16Encoding with the custom replacement characters
string utf8Result = "";
string utf16Result = "";
// Try UTF-8
utf8Result = utf8Encoding.GetString(rawData);
if (utf8Result.Contains(customInvalidChar))
{
utf8Result = "";
}
// Try UTF-16
utf16Result = utf16Encoding.GetString(rawData);
if (utf16Result.Contains(customInvalidChar))
{
utf16Result = "";
}
string result;
bool likelyUTF16 = false;
int nullCount = 0;
double nullRatio = 0;
// Improved UTF-16 detection
if (!string.IsNullOrEmpty(utf16Result))
{
// Count the number of null characters in the UTF-8 result, indicating that it's likely UTF-16
nullCount = utf8Result.Count(c => c == '\0');
nullRatio = (double)nullCount / utf16Result.Length;
// If more than some percentage of characters are null, it's likely UTF-16
if (nullRatio > 0.80)
{
likelyUTF16 = true;
}
}
// Strip out null characters from both results. By now UTF-16 should not have any null characters since it's been decoded
if (!string.IsNullOrEmpty(utf8Result))
{
utf8Result = utf8Result.Replace("\0", "");
}
if (!string.IsNullOrEmpty(utf16Result))
{
utf16Result = utf16Result.Replace("\0", "");
}
if (likelyUTF16 && !string.IsNullOrEmpty(utf16Result))
{
if (prefixEncodingType)
{
result = "[UTF-16] " + utf16Result;
}
else
{
result = utf16Result;
}
}
else if (!string.IsNullOrEmpty(utf8Result))
{
if (prefixEncodingType)
{
result = "[UTF-8] " + utf8Result;
}
else
{
result = utf8Result;
}
}
else
{
result = "";
}
// Truncate if necessary. Can be set to not truncate by setting maxLength to 0 or less
if (maxLength > 0 && result.Length > maxLength)
{
result = result.Substring(0, maxLength) + "...";
}
return result;
}
//Function to fit processedData grid view to the form window
private void UpdateToolLocations(WhichPanelResize splitAnchor = WhichPanelResize.None)
{
//int splitDistancebeforeToolAdjust = splitContainerMain.SplitterDistance;
int splitDistancebeforeToolAdjust = previousSplitterDistance;
// Calculate difference between form height and splitter distance
int splitDistanceBottomBeforeToolAdjust = splitContainerMain.Height - splitDistancebeforeToolAdjust;
// "Anchors" the splitter to prevent either top or bottom panel from resizing based on visibility of data grid view cells
// This only applies if the window is being resized, not if the splitter is being moved manually
if (splitAnchor != WhichPanelResize.None)
{
// Before setting SplitterDistance, ensure the value is valid
int maxSplitterDistance = splitContainerMain.Height - splitContainerMain.Panel2MinSize - CompensateDPI(150);
int minSplitterDistance = splitContainerMain.Panel1MinSize + CompensateDPI(150);
// Position splitter based on anchoring
if ( splitAnchor == WhichPanelResize.Bottom )
{
int desiredSplitterDistance = splitDistancebeforeToolAdjust;
splitContainerMain.SplitterDistance = Math.Max(minSplitterDistance, Math.Min(desiredSplitterDistance, maxSplitterDistance));
}
else if ( splitAnchor == WhichPanelResize.Top )
{
int desiredSplitterDistance = splitContainerMain.Height - splitDistanceBottomBeforeToolAdjust;
desiredSplitterDistance = Math.Max(minSplitterDistance, Math.Min(desiredSplitterDistance, maxSplitterDistance));
splitContainerMain.SplitterDistance = desiredSplitterDistance;
}
} // End of anchoring
// If the hex view is disabled, force the hex panel to zero width
if (!enableSplitHexView)
{
splitterContainer_InnerTextBoxes.Panel2Collapsed = true;
}
//splitterContainer_InnerTextBoxes.SplitterWidth = 10;
previousSplitterDistance = splitContainerMain.SplitterDistance;
}
private void RefreshClipboardItems()
{
// Clear the text boxes
richTextBoxContents.Text = "";
richTextBox_HexPlaintext.Text = "";
ShowLoadingIndicator(true);
// Attempt to open the clipboard, retrying up to 10 times with a 10ms delay
//Console.WriteLine("Attempting to open clipboard");
int retryCount = 10; // Number of retries
int retryDelay = 10; // Delay in milliseconds
bool clipboardOpened = false;
//TestingWinFormsClipboard(); // Debugging
for (int i = 0; i < retryCount; i++)
{
if (NativeMethods.OpenClipboard(this.Handle))
{
clipboardOpened = true;
break;
}
System.Threading.Thread.Sleep(retryDelay);
}
if (!clipboardOpened)
{
//Console.WriteLine("Failed to open clipboard");
MessageBox.Show("Failed to open clipboard.");
return;
}
try
{
CopyClipboardData();
}
catch (Exception ex)
{
Console.WriteLine("Error while copying clipboard: " + ex);
}
finally
{
//Console.WriteLine("Closing clipboard");
NativeMethods.CloseClipboard();
}
DetermineSynthesizedFormats();
ProcessClipboardData();
editedClipboardItems = new SortableBindingList<ClipboardItem>(clipboardItems.Select(item => (ClipboardItem)item.Clone()).ToList());
editedClipboardItems.ListChanged += EditedClipboardItems_ListChanged;
ShowLoadingIndicator(false);
RefreshDataGridViewContents();
UpdateSplitterPosition_FitDataGrid();
UpdateAnyPendingChangesFlag();
//UpdateEditControlsVisibility_AndPendingGridAppearance(); // Occurrs in RefreshDataGridViewContents
}
private void CopyClipboardData()
{
clipboardItems.Clear();
editedClipboardItems.Clear();
int formatCount = NativeMethods.CountClipboardFormats();
uint format = 0;
int actuallyLoadableCount = 0;
List<uint> formatsToRetry = new List<uint>();
while (true)
{
format = NativeMethods.EnumClipboardFormats(format);
if (format == 0)
{
int enumError = Marshal.GetLastWin32Error();
if (enumError == 0) // ERROR_SUCCESS -- No more formats to enumerate
{
// End of enumeration
break;
}
else
{
Console.WriteLine($"EnumClipboardFormats failed. Error code: {enumError}");
MessageBox.Show($"An error occurred trying to retrieve the list of clipboard items:\n Error Code: {enumError}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
actuallyLoadableCount++; // Only increments if the format is successfully enumerated. Not if it reached end, or there was an error
// Update label to show progress
string formatName = Utils.GetClipboardFormatNameFromId(format);
labelLoading.Text = $"{defaultLoadingLabelText}\n\n" + $"Loading: {actuallyLoadableCount} of {formatCount}...\n{formatName}";
// Update the form to show the new label
this.Update();
// -------- Start / Continue Enumeration ------------
bool successResutl = CopyIndividualClipboardFormat(formatId: format, formatName: formatName,loadedFormatCount: actuallyLoadableCount);
if (!successResutl)
{
formatsToRetry.Add(format);
}
}
//Console.WriteLine($"Checked {actuallyLoadableCount} formats out of {formatCount} reported formats.");
if (actuallyLoadableCount < formatCount)
{
Console.WriteLine("Warning: Not all reported formats were enumerated.");
}
if (formatsToRetry.Count > 0 && menuOptions_RetryMode.Checked == true)
{
// Retry any formats that failed
int retryCount = 1;
foreach (uint formatId in formatsToRetry)
{
labelLoading.Text = $"{defaultLoadingLabelText}\n\n" + $"Retrying: {retryCount} of {formatsToRetry.Count}...";
this.Update();
RetryCopyClipboardFormat(formatId);
retryCount++;
}
}
}
private void RetryCopyClipboardFormat(uint formatId)
{
bool successResult = false;
// First open the clipboard
if (NativeMethods.OpenClipboard(this.Handle))
{
// Try the normal way again first
ClipboardItem item;
try
{
CopyIndividualClipboardFormat(formatId, retryMode: true);
}
finally
{
NativeMethods.CloseClipboard();
// Wait a short time
System.Threading.Thread.Sleep(25);
}
// If the clipboard item is still null, it might be delayed render. Send request to the application to render the data
item = clipboardItems.FirstOrDefault(item => item.FormatId == formatId);
if (item != null && item.RawData == null)
{
IntPtr windowHandle;
// Send a delayed rendering request to the application. The window handle should be available in the diagnostics report
if (item.LoadErrorDiagnosisReport != null && item.LoadErrorDiagnosisReport.OwnerWindowHandle != null)
{
windowHandle = item.LoadErrorDiagnosisReport.OwnerWindowHandle;
}
else
{
windowHandle = IntPtr.Zero;
}
bool result = RequestDelayedRendering(windowHandle, formatId);
if (result == true)
{
// If the delayed rendering was successful, retry the format
try
{
NativeMethods.OpenClipboard(this.Handle);
successResult = CopyIndividualClipboardFormat(formatId, retryMode: true);
}
finally
{
NativeMethods.CloseClipboard();
}
}
}
}
}
private (bool,bool) ManuallyCopySpecifiedClipboardFormat(uint formatId = 0, string? formatName = null, bool silent = false)
{
bool successResult = false;
bool existingItem = false;
ClipboardItem item;
// Check if the format is already in the list, to know whether to use retry mode or not
if (formatName != null)
{
// Look for exact match first
item = clipboardItems.FirstOrDefault(item => item.FormatName == formatName);
// Look for non-case sensitive match
if (item == null)
{
item = clipboardItems.FirstOrDefault(item => item.FormatName.ToLower().Contains(formatName.ToLower()));
}
}
else if (formatId != 0)
{
item = clipboardItems.FirstOrDefault(item => item.FormatId == formatId);
}
else
{
if (!silent)
{
MessageBox.Show("No format ID or name specified", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return (successResult, existingItem);
}
// If the item was not found and only the format name is provided, we can compare it against known and registered formats to find the ID
if (item == null && formatId == 0 && formatName != null)
{
formatId = Utils.GetClipboardFormatIdFromName(formatName, caseSensitive: false);
}
// We need a format ID at least
if (formatId == 0)
{
if (formatName != null)
{
if (!silent)
{
MessageBox.Show("Error: Format name does not appear to match any standard or currently registered formats on the system.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
if (!silent)
{
MessageBox.Show("Error: No valid format ID given.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return (successResult, existingItem);
}
bool retryMode;
if (item == null)
{
retryMode = false;
}
else
{
retryMode = true;
existingItem = true;
}
if (NativeMethods.OpenClipboard(this.Handle))
{
try
{
successResult = CopyIndividualClipboardFormat(formatId, retryMode: retryMode);
}
finally
{
NativeMethods.CloseClipboard();
}
}
return (successResult, existingItem);
}
private bool CopyIndividualClipboardFormat(uint formatId, string? formatName = null, int loadedFormatCount = -1, bool retryMode = false)
{
if (formatName == null || string.IsNullOrEmpty(formatName))
{
formatName = Utils.GetClipboardFormatNameFromId(formatId);
}
ulong dataSize = 0;
byte[]? rawData = null;
int? error; // Initializes as null anyway
string? errorString = null;
DiagnosticsInfo? diagnosisReport = null;
int originalIndex = loadedFormatCount - 1; // Stored for reference of clipboard order. If loadCount is -1, it means it's a retry
bool copySuccess = true;
//Console.WriteLine($"Checking Format {actuallyLoadableCount}: {formatName} ({format})"); // Debugging
IntPtr hData = NativeMethods.GetClipboardData(formatId);
if (hData == IntPtr.Zero)
{
copySuccess = false;
error = Marshal.GetLastWin32Error();
string errorMessage = Utils.GetWin32ErrorMessage(error);
Console.WriteLine($"GetClipboardData returned null for format {formatId}. Error: {error} | Message: {errorMessage}");
if (!string.IsNullOrEmpty(formatName))
{
diagnosisReport = (DiagnoseClipboardState(formatId, formatName));
}
else
{
diagnosisReport = DiagnoseClipboardState(formatId);
}
if (error == null)
{
errorString = "[Unknown Error]";
}
else if (error == 5)
{
errorString = "[Error : Access Denied]";
}
else if (error == 0)
{
errorString = null;
}
else
{
errorString = $"[Error {error}]";
}
}
try
{
// First need to specially handle certain formats that don't use HGlobal
switch (formatId)
{
case 2: // CF_BITMAP
rawData = FormatConverters.CF_BITMAP_RawData_FromHandle(hData);
dataSize = (ulong)(rawData?.Length ?? 0);
break;
case 3: // CF_METAFILEPICT
rawData = FormatConverters.MetafilePict_RawData_FromHandle(hData);
dataSize = (ulong)(rawData?.Length ?? 0);
break;
case 9: // CF_PALETTE
rawData = FormatConverters.CF_PALETTE_RawData_FromHandle(hData);
dataSize = (ulong)(rawData?.Length ?? 0);
break;
case 14: // CF_ENHMETAFILE
rawData = FormatConverters.EnhMetafile_RawData_FromHandle(hData);
dataSize = (ulong)(rawData?.Length ?? 0);
break;
case 15: // CF_HDROP
rawData = FormatConverters.CF_HDROP_RawData_FromHandle(hData);
dataSize = (ulong)(rawData?.Length ?? 0);
break;
// All other formats that use Hglobal
default:
IntPtr pData = NativeMethods.GlobalLock(hData);
if (pData != IntPtr.Zero)
{
try
{
dataSize = (ulong)NativeMethods.GlobalSize(hData).ToUInt64();
rawData = new byte[dataSize];
Marshal.Copy(pData, rawData, 0, (int)dataSize);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing format {formatId}: {ex.Message}");
}
finally
{
NativeMethods.GlobalUnlock(hData);
}
}
else
{
Console.WriteLine($"GlobalLock returned null for format {formatId}");
}
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error processing format {formatId}: {ex.Message}");
copySuccess = false;
}
if (retryMode == false)
{
var item = new ClipboardItem
{
FormatName = formatName,
FormatId = formatId,
Handle = hData,
DataSize = dataSize,
RawData = rawData,
ProcessedData = null,
LoadErrorReason = errorString,
LoadErrorDiagnosisReport = diagnosisReport,
OriginalIndex = originalIndex
};
clipboardItems.Add(item);