Repository navigation
Expand file tree
/
Copy pathRSFind.cs
More file actions
1406 lines (1250 loc) · 57 KB
/
Copy pathRSFind.cs
File metadata and controls
1406 lines (1250 loc) · 57 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
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
// RSFind - a manual text search over a folder.
//
// The window is one screen: where to look, what to find, how to narrow it, and
// the results. No index, no service, no background watcher. It runs when you
// run it and it stops when you close it, which is the entire point - it is the
// tool you reach for precisely because the indexer did not have the answer.
//
// C# 5 only (in-box csc).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
namespace RSFind
{
public class MainForm : Form
{
Settings _settings;
TextBox _folder, _query, _include, _exclude, _replace;
InputHost _folderHost, _queryHost, _includeHost, _excludeHost, _replaceHost;
ThemedButton _browse, _find, _cancel, _menuButton, _preview;
ThemedCheck _matchCase, _wholeWord, _regex, _subfolders, _skipBinary, _stripAnsi;
ThemedCheck _preserveCase;
Label _replaceLabel;
SpinBox _maxMb, _before, _after;
Label _folderLabel, _queryLabel, _maskLabel, _excludeLabel, _mbLabel, _contextLabel, _summary;
Label _sortLabel;
ThemedDropdown _sortBy, _sortOrder;
// Same order as the ResultSort enum, so the dropdown index is the key
// and neither list can be reordered without the other noticing.
static readonly string[] SortLabels =
{ "Name", "Modified", "Created", "Size", "Hit Count" };
Panel _top;
Panel _resultsHost, _filterBar;
TextBox _filter;
InputHost _filterHost;
Label _filterLabel, _filterCount;
ResultsView _results;
ContextMenuStrip _menu;
ToolStripMenuItem _explorerItem;
CancellationTokenSource _cts;
System.Windows.Forms.Timer _pump;
readonly List<FileHits> _pending = new List<FileHits>();
readonly List<string> _errors = new List<string>();
readonly object _pendingLock = new object();
SearchProgress _progress;
string _activeQuery = "";
// The matcher that produced the results on screen, kept so a Replace
// uses the pattern the hits came from rather than whatever is in the
// search box by the time the person gets round to replacing.
Matcher _activeMatcher;
readonly List<FileHits> _found = new List<FileHits>();
bool _running;
IntPtr _iconHandle;
const string RegistryKeyName = "RSFind";
const string ExplorerVerbLabel = "Find Text with RSFind";
public MainForm(string startFolder)
{
_settings = Settings.Load();
Th.Set(_settings.Theme);
Text = "RSFind";
StartPosition = FormStartPosition.CenterScreen;
Font = new Font("Segoe UI", 9f);
MinimumSize = new Size(Dpi.S(760), Dpi.S(420));
ClientSize = FitToScreen(
_settings.WindowWidth > 0 ? _settings.WindowWidth : DefaultWidth,
_settings.WindowHeight > 0 ? _settings.WindowHeight : Dpi.S(620));
if (_settings.WindowMaximized) WindowState = FormWindowState.Maximized;
BuildControls();
BuildMenu();
ApplyTheme();
LoadSettingsIntoControls();
string folder = startFolder;
if (string.IsNullOrEmpty(folder)) folder = _settings.LastFolder;
if (!string.IsNullOrEmpty(folder)) _folder.Text = folder;
// Also at startup, not only after a replace: a folder that grew
// before there was a retention rule would otherwise sit there until
// the next replace happened to trim it.
Replacer.PruneUndo(UndoRoot, Replacer.MaxUndoRuns);
_pump = new System.Windows.Forms.Timer();
_pump.Interval = 150;
_pump.Tick += OnPump;
// The window sees keys before the focused control, so Ctrl+F works
// wherever the caret happens to be.
KeyPreview = true;
KeyDown += OnFormKeyDown;
Resize += delegate { LayoutTop(); };
FormClosing += OnFormClosing;
Shown += delegate { _query.Focus(); };
}
// ---- construction --------------------------------------------------
// Wide enough that the sort controls sit on the options row instead of
// wrapping to one of their own.
//
// Measured rather than guessed. The options row ends at 830 logical
// pixels and the label plus two dropdowns need 1133, so the old 1000
// put them on their own line on any machine with no saved size - which
// is every fresh install. The remaining slack is for a font that
// renders "Sort by" a shade wider than this one does.
static int DefaultWidth { get { return Dpi.S(1160); } }
// Keeps the opening size inside the display. The rule itself is in
// ViewRules.ClampToWorkArea, where it can be tested without a screen.
static Size FitToScreen(int width, int height)
{
Screen screen = Screen.PrimaryScreen;
if (screen == null) return new Size(width, height);
Rectangle work = screen.WorkingArea;
int margin = Dpi.S(60);
return new Size(
ViewRules.ClampToWorkArea(width, work.Width, margin, Dpi.S(760)),
ViewRules.ClampToWorkArea(height, work.Height, margin, Dpi.S(420)));
}
void BuildControls()
{
_top = new Panel();
_top.Dock = DockStyle.Top;
_top.Height = Dpi.S(150);
Controls.Add(_top);
_results = new ResultsView();
_results.Dock = DockStyle.Fill;
_results.OpenRequested += OnOpenRequested;
_results.FindRequested += delegate { ShowFilter(); };
_results.SortChanged += OnSortChanged;
BuildFilterBar();
// The filter bar belongs to the results, not to the search chrome,
// so it lives in the same container and appears directly above
// them. Within a container the last child docks first, so the bar
// is added after the list it sits on top of.
_resultsHost = new Panel();
_resultsHost.Dock = DockStyle.Fill;
_resultsHost.Controls.Add(_results);
_resultsHost.Controls.Add(_filterBar);
Controls.Add(_resultsHost);
Controls.SetChildIndex(_resultsHost, 0); // Fill must sit under the docked Top
_folderLabel = NewLabel("Search in");
_folder = NewBox();
_folder.KeyDown += OnEnterStarts;
_folderHost = new InputHost(_folder, Dpi.S(6), Dpi.S(4));
_browse = NewButton("Browse", false);
_browse.Click += OnBrowse;
_menuButton = NewButton("Menu", false);
_menuButton.Click += delegate
{
MenuTheme.Apply(_menu);
_menu.Show(_menuButton, new Point(0, _menuButton.Height));
};
_queryLabel = NewLabel("Find what");
_query = NewBox();
_query.KeyDown += OnEnterStarts;
_queryHost = new InputHost(_query, Dpi.S(6), Dpi.S(4));
_find = NewButton("Find", true);
_find.Click += delegate { StartSearch(); };
_cancel = NewButton("Cancel", false);
_cancel.TakesFocus = false;
_cancel.Enabled = false;
_cancel.Click += delegate { if (_cts != null) _cts.Cancel(); };
_replaceLabel = NewLabel("Replace with");
_replace = NewBox();
_replaceHost = new InputHost(_replace, Dpi.S(6), Dpi.S(4));
_preserveCase = NewCheck("Preserve case");
_preserveCase.Checked = true;
// "Replace..." rather than "Preview".
//
// Someone who has just typed a replacement goes looking for the
// verb they are about to perform, and a button labeled Preview
// reads as an optional extra sitting beside the real one - so they
// hunt for a Replace button that does not exist. The ellipsis is
// the standard promise that it opens something rather than acting,
// and what it opens is unmistakably a preview: the window is
// titled Preview Replace and its button says Apply.
_preview = NewButton("Replace...", false);
_preview.Enabled = false;
_preview.Click += delegate { PreviewReplace(); };
ToolTip tips = new ToolTip();
tips.SetToolTip(_preview, "Shows exactly what would change before anything is written");
_matchCase = NewCheck("Match case");
_wholeWord = NewCheck("Match whole word");
_regex = NewCheck("Use regex");
_subfolders = NewCheck("Include subfolders");
_skipBinary = NewCheck("Exclude binary files");
_stripAnsi = NewCheck("Strip ANSI escapes");
_maskLabel = NewLabel("File mask");
_include = NewBox();
_include.KeyDown += OnEnterStarts;
_includeHost = new InputHost(_include, Dpi.S(6), Dpi.S(4));
_excludeLabel = NewLabel("Exclude");
_exclude = NewBox();
_exclude.KeyDown += OnEnterStarts;
_excludeHost = new InputHost(_exclude, Dpi.S(6), Dpi.S(4));
_mbLabel = NewLabel("Skip over");
_maxMb = new SpinBox(0, 4096, 50);
_top.Controls.Add(_maxMb);
_contextLabel = NewLabel("Context lines");
_before = new SpinBox(0, 20, 0);
_after = new SpinBox(0, 20, 0);
_top.Controls.Add(_before);
_top.Controls.Add(_after);
_sortLabel = NewLabel("Sort by");
_sortBy = new ThemedDropdown();
_sortBy.SetItems(SortLabels);
_sortBy.SelectedIndexChanged += OnSortPicked;
_sortOrder = new ThemedDropdown();
_sortOrder.SetItems(new string[] { "Ascending", "Descending" });
_sortOrder.SelectedIndexChanged += OnSortPicked;
_top.Controls.Add(_sortBy);
_top.Controls.Add(_sortOrder);
_summary = NewLabel("Ready.");
_summary.AutoSize = false;
_top.Controls.Add(_folderHost);
_top.Controls.Add(_queryHost);
_top.Controls.Add(_replaceHost);
_top.Controls.Add(_includeHost);
_top.Controls.Add(_excludeHost);
}
// Ctrl+F narrows what is on screen rather than stepping through it.
//
// Find-next would match the muscle memory, but not the job. The
// question that raises this bar is "which of these thousand hits was
// on LAB4", and a host appears on dozens of rows - so find-next means
// pressing it dozens of times, while a filter answers in one go and
// leaves a short list to double-click. Escape puts everything back.
void BuildFilterBar()
{
_filterBar = new Panel();
_filterBar.Dock = DockStyle.Top;
_filterBar.Height = Dpi.S(34);
_filterBar.Visible = false;
_filterBar.BackColor = Th.T.Panel;
_filterLabel = new Label();
_filterLabel.Text = "Find in results";
_filterLabel.AutoSize = true;
_filterLabel.BackColor = Th.T.Panel;
_filterLabel.ForeColor = Th.T.Txt;
_filterBar.Controls.Add(_filterLabel);
_filter = new TextBox();
_filter.BorderStyle = BorderStyle.None;
_filter.TextChanged += delegate
{
_results.SetFilter(_filter.Text);
UpdateFilterCount();
};
_filter.KeyDown += delegate(object s, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape) { HideFilter(); e.SuppressKeyPress = true; }
// Enter moves to the list, because the next thing anyone does
// after narrowing is open one of the rows.
else if (e.KeyCode == Keys.Enter)
{
_results.Focus();
_results.SelectFirst();
e.SuppressKeyPress = true;
}
};
_filterHost = new InputHost(_filter, Dpi.S(6), Dpi.S(4));
_filterBar.Controls.Add(_filterHost);
_filterCount = new Label();
_filterCount.AutoSize = false;
_filterCount.BackColor = Th.T.Panel;
_filterCount.ForeColor = Th.T.TxtDim;
_filterCount.TextAlign = ContentAlignment.MiddleLeft;
_filterBar.Controls.Add(_filterCount);
_filterBar.Resize += delegate { LayoutFilterBar(); };
}
void LayoutFilterBar()
{
if (_filterBar == null) return;
int pad = Dpi.S(10);
int rowH = Dpi.S(24);
int y = (_filterBar.Height - rowH) / 2;
_filterLabel.SetBounds(pad, y + (rowH - _filterLabel.Height) / 2,
_filterLabel.Width, _filterLabel.Height);
int x = pad + _filterLabel.Width + Dpi.S(10);
int countW = Dpi.S(260);
int boxW = Math.Max(Dpi.S(80),
_filterBar.ClientSize.Width - pad - countW - Dpi.S(10) - x);
_filterHost.SetBounds(x, y, boxW, rowH);
_filterCount.SetBounds(_filterHost.Right + Dpi.S(10), y, countW, rowH);
}
void ShowFilter()
{
if (_results.FileCount == 0)
{
SetSummary("Search something first, then Ctrl+F narrows the results.", true);
return;
}
_filterBar.Visible = true;
LayoutFilterBar();
UpdateFilterCount();
_filter.Focus();
_filter.SelectAll();
}
void HideFilter()
{
if (!_filterBar.Visible) return;
// Clearing on the way out, because a hidden filter still hiding
// results is the same trap as a scroll position past the end.
_filter.Text = "";
_results.SetFilter("");
_filterBar.Visible = false;
_results.Focus();
}
void UpdateFilterCount()
{
if (_filterCount == null) return;
int shown = _results.VisibleHits;
int total = _results.TotalHits;
_filterCount.Text = _filter.Text.Length == 0
? "Escape closes this"
: "Showing " + shown.ToString("N0", CultureInfo.InvariantCulture)
+ " of " + total.ToString("N0", CultureInfo.InvariantCulture)
+ (total == 1 ? " hit" : " hits");
_filterCount.ForeColor = _filter.Text.Length > 0 && shown == 0 ? Th.T.Warn : Th.T.TxtDim;
}
Label NewLabel(string text)
{
Label l = new Label();
l.Text = text;
l.AutoSize = true;
l.TextAlign = ContentAlignment.MiddleLeft;
_top.Controls.Add(l);
return l;
}
TextBox NewBox()
{
TextBox b = new TextBox();
b.BorderStyle = BorderStyle.None;
return b;
}
ThemedButton NewButton(string text, bool primary)
{
ThemedButton b = new ThemedButton();
b.Text = text;
b.Primary = primary;
_top.Controls.Add(b);
return b;
}
ThemedCheck NewCheck(string text)
{
ThemedCheck c = new ThemedCheck();
c.Text = text;
_top.Controls.Add(c);
return c;
}
void BuildMenu()
{
_menu = new ContextMenuStrip();
_menu.Renderer = new ToolStripProfessionalRenderer(new ThemeColorTable());
_menu.ShowImageMargin = false;
ToolStripMenuItem themes = new ToolStripMenuItem("Themes");
ToolStripMenuItem group = null;
foreach (Theme t in Themes.All)
{
ToolStripMenuItem item = new ToolStripMenuItem(t.Label);
item.Tag = t.Key;
item.Click += OnThemePicked;
if (t.Group == null) themes.DropDownItems.Add(item);
else
{
if (group == null || group.Text != t.Group)
{
group = new ToolStripMenuItem(t.Group);
themes.DropDownItems.Add(group);
}
group.DropDownItems.Add(item);
}
}
_menu.Items.Add(themes);
_explorerItem = new ToolStripMenuItem("Add to Explorer Right-Click Menu");
_explorerItem.Click += OnToggleExplorerEntry;
_menu.Items.Add(_explorerItem);
ToolStripMenuItem editor = new ToolStripMenuItem("Editor Command...");
editor.Click += OnEditorCommand;
_menu.Items.Add(editor);
_menu.Items.Add(new ToolStripSeparator());
ToolStripMenuItem undo = new ToolStripMenuItem("Undo Last Replace");
undo.Click += OnUndoReplace;
_menu.Items.Add(undo);
ToolStripMenuItem export = new ToolStripMenuItem("Export Results...");
export.Click += OnExport;
_menu.Items.Add(export);
ToolStripMenuItem about = new ToolStripMenuItem("About RSFind");
about.Click += OnAbout;
_menu.Items.Add(about);
_menu.Opening += delegate
{
MarkActiveTheme(themes);
_explorerItem.Checked = ExplorerEntryPresent();
};
}
// ---- layout ----------------------------------------------------------
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
OsChrome.ApplyTitleBar(this);
LayoutTop();
}
void LayoutTop()
{
if (_top == null || _folderHost == null) return;
int pad = Dpi.S(10);
int gap = Dpi.S(8);
int rowH = Dpi.S(26);
int labelW = Dpi.S(74);
int buttonW = Dpi.S(84);
int y = pad;
int right = _top.ClientSize.Width - pad;
// Row 1: the folder, Browse, and the menu.
Place(_folderLabel, pad, y, rowH);
_menuButton.SetBounds(right - buttonW, y, buttonW, rowH);
_browse.SetBounds(_menuButton.Left - gap - buttonW, y, buttonW, rowH);
_folderHost.SetBounds(pad + labelW, y,
Math.Max(Dpi.S(80), _browse.Left - gap - pad - labelW), rowH);
y += rowH + gap;
// Row 2: the query, Find, and Cancel.
Place(_queryLabel, pad, y, rowH);
_cancel.SetBounds(right - buttonW, y, buttonW, rowH);
_find.SetBounds(_cancel.Left - gap - buttonW, y, buttonW, rowH);
_queryHost.SetBounds(pad + labelW, y,
Math.Max(Dpi.S(80), _find.Left - gap - pad - labelW), rowH);
y += rowH + gap;
// Row 3: replace. Always visible rather than behind a toggle - a
// destructive control that appears and disappears is harder to
// reason about than one that is simply inert until a search has
// produced something to act on.
Place(_replaceLabel, pad, y, rowH);
// Directly under Find, not under Cancel. These are the two verbs
// the window offers and they belong in one column; Cancel belongs
// to the search that is running, and lining Replace up beneath it
// put the row's action in the row above's afterthought column.
_preview.SetBounds(_find.Left, y, buttonW, rowH);
_preserveCase.SizeToText();
_preserveCase.SetBounds(_preview.Left - gap - _preserveCase.Width, y,
_preserveCase.Width, rowH);
_replaceHost.SetBounds(pad + labelW, y,
Math.Max(Dpi.S(80), _preserveCase.Left - gap - pad - labelW), rowH);
y += rowH + gap;
// Row 3: the toggles, wrapping if the window is narrow.
int x = pad + labelW;
int rowTop = y;
ThemedCheck[] checks = new ThemedCheck[]
{ _matchCase, _wholeWord, _regex, _subfolders, _skipBinary, _stripAnsi };
foreach (ThemedCheck c in checks)
{
c.SizeToText();
if (x + c.Width > right && x > pad + labelW)
{
x = pad + labelW;
rowTop += rowH;
}
c.SetBounds(x, rowTop + (rowH - c.Height) / 2, c.Width, c.Height);
x += c.Width + Dpi.S(14);
}
y = rowTop + rowH + gap;
// Row 4: the narrowing fields.
Place(_maskLabel, pad, y, rowH);
int fieldW = Dpi.S(150);
_includeHost.SetBounds(pad + labelW, y, fieldW, rowH);
int ex = _includeHost.Right + Dpi.S(16);
Place(_excludeLabel, ex, y, rowH);
_excludeHost.SetBounds(ex + Dpi.S(56), y, fieldW, rowH);
int mb = _excludeHost.Right + Dpi.S(16);
Place(_mbLabel, mb, y, rowH);
_maxMb.SetBounds(mb + Dpi.S(62), y, Dpi.S(72), rowH);
int cx = _maxMb.Right + Dpi.S(16);
Place(_contextLabel, cx, y, rowH);
_before.SetBounds(cx + Dpi.S(82), y, Dpi.S(60), rowH);
_after.SetBounds(_before.Right + Dpi.S(6), y, Dpi.S(60), rowH);
// The sort controls, on the end of the same row when there is room
// and on a row of their own when there is not. Row 4 already runs
// wider than the minimum window, so "there is room" is a real
// question rather than a formality.
int sortW = Dpi.S(104);
int orderW = Dpi.S(116);
int sortRow = y;
int sx = _after.Right + Dpi.S(16);
if (sx + _sortLabel.Width + Dpi.S(8) + sortW + Dpi.S(6) + orderW > right)
{
sortRow += rowH + gap;
sx = pad + labelW;
}
Place(_sortLabel, sx, sortRow, rowH);
_sortBy.SetBounds(sx + _sortLabel.Width + Dpi.S(8), sortRow, sortW, rowH);
_sortOrder.SetBounds(_sortBy.Right + Dpi.S(6), sortRow, orderW, rowH);
y = sortRow + rowH + gap;
// Row 5: the summary line, which is the only place the caps and
// the cancellations get to speak.
_summary.SetBounds(pad, y, Math.Max(Dpi.S(100), right - pad), rowH);
y += rowH + Dpi.S(4);
_top.Height = y;
}
static void Place(Label l, int x, int rowTop, int rowH)
{
l.SetBounds(x, rowTop + (rowH - l.Height) / 2, l.Width, l.Height);
}
// ---- theme -----------------------------------------------------------
void ApplyTheme()
{
Theme t = Th.T;
BackColor = t.Panel;
ForeColor = t.Txt;
_top.BackColor = t.Panel;
foreach (Control c in _top.Controls)
{
Label l = c as Label;
if (l != null) { l.BackColor = t.Panel; l.ForeColor = t.Txt; }
ThemedCheck ck = c as ThemedCheck;
if (ck != null) ck.BackColor = t.Panel;
}
_summary.ForeColor = t.TxtDim;
if (_filterBar != null)
{
_filterBar.BackColor = t.Panel;
_filterLabel.BackColor = t.Panel;
_filterLabel.ForeColor = t.Txt;
_filterCount.BackColor = t.Panel;
UpdateFilterCount();
}
IntPtr old = _iconHandle;
Icon = Brand.CreateIcon(Dpi.S(32), out _iconHandle);
if (old != IntPtr.Zero) Native.DestroyIcon(old);
OsChrome.ApplyTitleBar(this);
Invalidate(true);
}
void OnThemePicked(object sender, EventArgs e)
{
ToolStripMenuItem item = (ToolStripMenuItem)sender;
Th.Set((string)item.Tag);
ApplyTheme();
SaveSettings();
}
void MarkActiveTheme(ToolStripMenuItem themes)
{
foreach (ToolStripItem raw in themes.DropDownItems)
{
ToolStripMenuItem item = raw as ToolStripMenuItem;
if (item == null) continue;
if (item.HasDropDownItems)
{
foreach (ToolStripItem sub in item.DropDownItems)
{
ToolStripMenuItem s = sub as ToolStripMenuItem;
if (s != null) s.Checked = Equals(s.Tag, Th.T.Key);
}
}
else item.Checked = Equals(item.Tag, Th.T.Key);
}
}
// ---- settings ---------------------------------------------------------
void LoadSettingsIntoControls()
{
_include.Text = _settings.IncludeMasks;
_exclude.Text = _settings.ExcludeMasks;
_matchCase.Checked = _settings.MatchCase;
_wholeWord.Checked = _settings.WholeWord;
_regex.Checked = _settings.UseRegex;
_subfolders.Checked = _settings.IncludeSubfolders;
_skipBinary.Checked = _settings.ExcludeBinary;
_stripAnsi.Checked = _settings.StripAnsi;
_maxMb.Value = _settings.MaxFileMegabytes;
_before.Value = _settings.ContextBefore;
_after.Value = _settings.ContextAfter;
_results.SetSort(ViewRules.ParseSort(_settings.SortKey, ResultSort.Name),
_settings.SortDescending, false);
ShowSortInControls();
}
// The dropdowns and the results right-click menu are two ways into the
// same setting, so whichever one is used, the other has to follow. The
// menu marks itself when it opens; these have to be told.
void ShowSortInControls()
{
_sortBy.SetSelectedIndex((int)_results.SortKey, false);
_sortOrder.SetSelectedIndex(_results.SortDescending ? 1 : 0, false);
}
void OnSortPicked(object sender, EventArgs e)
{
_results.SetSort((ResultSort)_sortBy.SelectedIndex,
_sortOrder.SelectedIndex == 1, true);
}
void OnSortChanged(object sender, EventArgs e)
{
ShowSortInControls();
SaveSettings();
}
void SaveSettings()
{
_settings.Theme = Th.T.Key;
_settings.LastFolder = _folder.Text.Trim();
_settings.IncludeMasks = _include.Text.Trim();
_settings.ExcludeMasks = _exclude.Text.Trim();
_settings.MatchCase = _matchCase.Checked;
_settings.WholeWord = _wholeWord.Checked;
_settings.UseRegex = _regex.Checked;
_settings.IncludeSubfolders = _subfolders.Checked;
_settings.ExcludeBinary = _skipBinary.Checked;
_settings.StripAnsi = _stripAnsi.Checked;
_settings.MaxFileMegabytes = _maxMb.Value;
_settings.ContextBefore = _before.Value;
_settings.ContextAfter = _after.Value;
_settings.SortKey = ViewRules.SortName(_results.SortKey);
_settings.SortDescending = _results.SortDescending;
_settings.WindowMaximized = WindowState == FormWindowState.Maximized;
if (WindowState == FormWindowState.Normal)
{
_settings.WindowWidth = ClientSize.Width;
_settings.WindowHeight = ClientSize.Height;
}
_settings.Save();
}
void OnFormClosing(object sender, FormClosingEventArgs e)
{
if (_cts != null) _cts.Cancel();
SaveSettings();
if (_iconHandle != IntPtr.Zero) Native.DestroyIcon(_iconHandle);
}
// ---- the search --------------------------------------------------------
void OnFormKeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.F)
{
ShowFilter();
e.Handled = true;
e.SuppressKeyPress = true;
return;
}
if (e.KeyCode == Keys.Escape && _filterBar.Visible)
{
HideFilter();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
void OnEnterStarts(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Enter) return;
e.SuppressKeyPress = true; // or the text box beeps
StartSearch();
}
void StartSearch()
{
if (_running) return;
string root = _folder.Text.Trim();
if (root.Length == 0 || !Directory.Exists(root))
{
SetSummary("That folder does not exist.", true);
_folder.Focus();
return;
}
if (_query.Text.Length == 0)
{
SetSummary("Type something to search for.", true);
_query.Focus();
return;
}
SearchOptions o = new SearchOptions();
o.Root = root;
o.Query = _query.Text;
o.MatchCase = _matchCase.Checked;
o.WholeWord = _wholeWord.Checked;
o.UseRegex = _regex.Checked;
o.IncludeSubfolders = _subfolders.Checked;
o.IncludeMasks = _include.Text;
o.ExcludeMasks = _exclude.Text;
o.ExcludeBinary = _skipBinary.Checked;
o.StripAnsi = _stripAnsi.Checked;
o.MaxFileMegabytes = _maxMb.Value;
o.ContextBefore = _before.Value;
o.ContextAfter = _after.Value;
SearchEngine engine;
try
{
engine = new SearchEngine(o);
}
catch (PatternError ex)
{
// A half-typed regex is the normal state of a search box, so it
// reports itself on the summary line rather than in a dialog.
SetSummary("Bad pattern: " + ex.Message, true);
_query.Focus();
return;
}
// A filter from the previous result set would hide the new one,
// which is the same "it found nothing" trap as a stale scroll
// position. A new search starts unfiltered.
HideFilter();
_results.ClearResults();
lock (_pendingLock) { _pending.Clear(); }
_errors.Clear();
_found.Clear();
_preview.Enabled = false;
_progress = null;
_activeQuery = o.Query;
_activeMatcher = new Matcher(o.Query, o.MatchCase, o.WholeWord, o.UseRegex);
_running = true;
_find.Enabled = false;
_cancel.Enabled = true;
SetSummary("Searching...", false);
SaveSettings();
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
_pump.Start();
Task.Factory.StartNew(delegate
{
try
{
RunSearch(engine, token);
}
catch (Exception ex)
{
// The window leaves the running state whatever happened.
//
// Without this the task faults, nobody observes it - .NET
// swallows an unobserved Task exception - _progress never
// reaches a finished snapshot, and the pump runs forever
// with Find disabled and Cancel useless, because the task
// it would cancel is already dead. Only killing the process
// recovered it.
SearchProgress failed = new SearchProgress();
failed.Finished = true;
failed.Fault = ex.GetType().Name + ": " + ex.Message;
_progress = failed;
}
});
}
void RunSearch(SearchEngine engine, CancellationToken token)
{
SearchProgress final = engine.Run(token,
delegate(FileHits fh) { lock (_pendingLock) { _pending.Add(fh); } },
delegate(SearchProgress p) { _progress = p; },
delegate(string path, string message)
{
lock (_pendingLock)
{
// One line per unreadable place, capped: a scan
// pointed at a system folder can produce thousands
// and none of them are worth the memory.
if (_errors.Count < 200) _errors.Add(path + ": " + message);
}
});
_progress = final;
}
// Drains what the worker produced onto the UI thread. One timer rather
// than an Invoke per file: the engine reports from every core at once,
// and marshalling each one separately makes the scan slower than the
// disk it is reading.
void OnPump(object sender, EventArgs e)
{
List<FileHits> batch = null;
lock (_pendingLock)
{
if (_pending.Count > 0)
{
batch = new List<FileHits>(_pending);
_pending.Clear();
}
}
if (batch != null)
{
_results.AddFiles(batch);
_found.AddRange(batch);
}
SearchProgress p = _progress;
if (p == null) return;
SetSummary(Describe(p), p.Fault != null);
if (!p.Finished) return;
_pump.Stop();
_running = false;
_find.Enabled = true;
_cancel.Enabled = false;
// One last drain: a file that arrived between the batch above and
// the engine finishing would otherwise never be shown.
lock (_pendingLock)
{
if (_pending.Count > 0)
{
List<FileHits> last = new List<FileHits>(_pending);
_results.AddFiles(last);
_found.AddRange(last);
_pending.Clear();
}
}
// The order is applied once, here, rather than on every batch.
// Files arrive in whatever sequence the workers finish them, and
// re-sorting mid-scan would shuffle rows under whoever is reading
// the ones already on screen. Completion is a boundary they can
// feel, because the summary line stops moving at the same moment.
_results.ApplySort();
SetSummary(Describe(p), false);
_preview.Enabled = _found.Count > 0;
}
string Describe(SearchProgress p)
{
StringBuilder sb = new StringBuilder();
sb.Append("Search \"").Append(_activeQuery).Append("\" (");
sb.Append(p.Hits.ToString("N0", CultureInfo.InvariantCulture));
sb.Append(p.Hits == 1 ? " hit in " : " hits in ");
sb.Append(p.FilesMatched.ToString("N0", CultureInfo.InvariantCulture));
sb.Append(p.FilesMatched == 1 ? " file of " : " files of ");
sb.Append(p.FilesScanned.ToString("N0", CultureInfo.InvariantCulture));
sb.Append(" searched)");
// The timing belongs to the count, so it goes immediately after it.
// Everything below is a caveat, and caveats read as sentences.
if (p.Finished)
{
sb.Append(" in ").Append(((int)p.Elapsed.TotalMilliseconds)
.ToString("N0", CultureInfo.InvariantCulture)).Append(" ms");
}
if (p.FilesSkipped > 0)
{
sb.Append(". ").Append(p.FilesSkipped.ToString("N0", CultureInfo.InvariantCulture));
sb.Append(p.FilesSkipped == 1 ? " file skipped" : " files skipped");
}
// Named, not folded into the skip count. A folder of PDFs that
// answers "no hits" is not an answer; it is a missing capability
// wearing one.
if (p.FilesUnsupported > 0)
{
sb.Append(". ").Append(p.FilesUnsupported.ToString("N0", CultureInfo.InvariantCulture));
sb.Append(p.FilesUnsupported == 1 ? " file is in a format" : " files are in formats");
sb.Append(" RSFind cannot read");
if (p.UnsupportedKinds.Length > 0) sb.Append(" (").Append(p.UnsupportedKinds).Append(")");
}
// Both of these change what the numbers above mean, so neither is
// allowed to be silent. A short list that does not say it is short
// reads as "that is all there is".
if (p.Fault != null)
sb.Append(". The search stopped early (").Append(p.Fault)
.Append("), so this is a partial result");
if (p.Cancelled) sb.Append(". Cancelled - this is a partial result");
if (p.Truncated) sb.Append(". Hit cap reached - there are more matches than are listed");
lock (_pendingLock)
{
if (_errors.Count > 0)
{
sb.Append(". ").Append(_errors.Count.ToString(CultureInfo.InvariantCulture));
sb.Append(_errors.Count == 1 ? " place could not be read" : " places could not be read");
}
}
return sb.ToString();
}
void SetSummary(string text, bool warn)
{
_summary.Text = text;
_summary.ForeColor = warn ? Th.T.Warn : Th.T.TxtDim;
}
// ---- replace ---------------------------------------------------------------
static string UndoRoot { get { return Path.Combine(Settings.Dir, "undo"); } }
void PreviewReplace()
{
if (_running || _found.Count == 0 || _activeMatcher == null) return;
if (_replace.Text.Length == 0)
{
SetSummary("Type what to replace the matches with.", true);
_replace.Focus();
return;
}
try
{
_activeMatcher.ValidateReplacement(_replace.Text);
}
catch (PatternError ex)
{
SetSummary("Bad replacement: " + ex.Message, true);
_replace.Focus();
return;
}
// Refuse before planning rather than after. Planning re-reads every
// matched file, and a run this size is one the person should narrow
// regardless of what the preview would have shown.
int total = 0;
for (int i = 0; i < _found.Count; i++) total += _found[i].Hits.Count;
if (total > ReplaceDialog.MaxPreviewChanges)
{
SetSummary("That would change " + total.ToString("N0", CultureInfo.InvariantCulture)