-
Notifications
You must be signed in to change notification settings - Fork 0
/
flood.linq
3591 lines (2877 loc) · 116 KB
/
flood.linq
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
<Query Kind="Statements">
<NuGetReference Version="1.0.902.49">Microsoft.Web.WebView2</NuGetReference>
<NuGetReference Version="3.3.2">morelinq</NuGetReference>
<NuGetReference Version="1.1.0">Nito.Collections.Deque</NuGetReference>
<Namespace>Cursor = System.Windows.Forms.Cursor</Namespace>
<Namespace>Key = System.Windows.Input.Key</Namespace>
<Namespace>Keyboard = System.Windows.Input.Keyboard</Namespace>
<Namespace>LC = LINQPad.Controls</Namespace>
<Namespace>Microsoft.Web.WebView2.Core</Namespace>
<Namespace>Microsoft.Web.WebView2.WinForms</Namespace>
<Namespace>Microsoft.Win32</Namespace>
<Namespace>Nito.Collections</Namespace>
<Namespace>static LINQPad.Controls.ControlExtensions</Namespace>
<Namespace>static MoreLinq.Extensions.PairwiseExtension</Namespace>
<Namespace>System.ComponentModel</Namespace>
<Namespace>System.Drawing</Namespace>
<Namespace>System.Drawing.Imaging</Namespace>
<Namespace>System.Runtime.InteropServices</Namespace>
<Namespace>System.Security</Namespace>
<Namespace>System.Security.Cryptography</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
<Namespace>System.Windows.Forms</Namespace>
<Namespace>System.Windows.Forms.DataVisualization.Charting</Namespace>
<Namespace>Timer = System.Windows.Forms.Timer</Namespace>
<RuntimeVersion>5.0</RuntimeVersion>
</Query>
// flood.linq - Entry point and main source code file.
// This file is part of Flood, an interactive flood-fill visualizer.
//
// Copyright (C) 2020, 2021 Eliah Kagan <degeneracypressure@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#LINQPad optimize+
#nullable enable
const float defaultScreenFractionForCanvas = 5.0f / 9.0f;
var devmode = GotKey.Shift || Files.QueryBaseName.Equals(
"devmode",
StringComparison.InvariantCultureIgnoreCase);
// Make dump headings bigger. (See Launcher.Display for further customization.)
Util.RawHtml("<style>h1.headingpresenter { font-size: 1rem }</style>").Dump();
if (devmode) {
// Use the launcher ("developer mode").
var launcher = new Launcher(SuggestCanvasSize());
launcher.Launch += launcher_Launch;
launcher.Display();
} else {
// Proceed immediately with the automatically suggested size.
new MainPanel(SuggestCanvasSize(), GetBestHelpViewerAsync).Display();
}
static Size SuggestCanvasSize()
{
var (screenWidth, screenHeight) = GetBestScreen().Bounds.Size;
var sideLength = (int)(Math.Min(screenWidth, screenHeight)
* defaultScreenFractionForCanvas);
return new(width: sideLength, height: sideLength);
}
static Screen GetBestScreen()
{
// We want the screen that (most of) the LINQPad window is on.
var screen = Screen.FromHandle(Util.HostWindowHandle);
// But fall back to the primary screen if we couldn't find that.
return screen.WorkingArea.IsEmpty ? Screen.PrimaryScreen : screen;
}
static Task<HelpViewer> GetOldHelpViewerAsync()
=> Task.FromResult<HelpViewer>(WebBrowserHelpViewer.Create());
static async Task<HelpViewer> GetBestHelpViewerAsync()
{
try {
return await WebView2HelpViewer.CreateAsync();
} catch (WebView2RuntimeNotFoundException) {
return WebBrowserHelpViewer.Create();
}
}
static void launcher_Launch(Launcher sender, LauncherEventArgs e)
{
HelpViewerSupplier supplier =
(e.UseOldWebBrowser ? GetOldHelpViewerAsync : GetBestHelpViewerAsync);
var ui = new MainPanel(e.Size, supplier) {
DelayInMilliseconds = sender.DelayInMilliseconds,
ShowParentInTaskbar = sender.ShowPluginFormInTaskbar,
ExpireAlerts = sender.ExpireAlerts,
MagnifierButtonVisible = sender.ShowMagnifierButton,
StopButtonVisible = sender.ShowStopButton,
ChartingButtonVisible = sender.ShowChartButton,
};
ui.Activated += delegate { sender.PauseUpdates(); };
ui.Deactivate += delegate { sender.ResumeUpdates(); };
ui.Display();
}
/// <summary>
/// Provides a canvas size for the <see cref="Launcher.Launch"/> event.
/// </summary>
internal sealed class LauncherEventArgs : EventArgs {
internal LauncherEventArgs(Size size, bool useOldWebBrowser)
=> (Size, UseOldWebBrowser) = (size, useOldWebBrowser);
internal Size Size { get; }
internal bool UseOldWebBrowser { get; }
};
/// <summary>
/// Represents a method that will handle the <see cref="Launcher.Launch"/>
/// event.
/// </summary>
internal delegate void LauncherEventHandler(Launcher sender,
LauncherEventArgs e);
/// <summary>
/// "Developer mode" launcher allowing the user to specify a canvas size and
/// other advanced configuration.
/// </summary>
internal sealed class Launcher {
internal Launcher(Size defaultSize)
{
_width = defaultSize.Width;
_height = defaultSize.Height;
_widthBox = CreateNumberBox(_width);
_heightBox = CreateNumberBox(_height);
_delayBox = CreateNumberBox(_delay);
_panel = new(horizontal: false,
new LC.FieldSet("Custom Canvas Size", CreateSizeTable()),
new LC.FieldSet("Asynchronous Delay Behavior", CreateDelayPanel()),
new LC.FieldSet("Screen Capture Hack", _showPluginFormInTaskbar),
new LC.FieldSet("Help Browser", _useOldWebBrowser),
new LC.FieldSet("Features", CreateFeaturesPanel()),
new LC.WrapPanel(_launch, _postLaunch));
SubscribePrivateHandlers();
}
internal event LauncherEventHandler? Launch = null;
internal int DelayInMilliseconds
=> _delay is int delay
? delay
: throw new NotSupportedException(
"Bug: Launch button enabled without delay set.");
internal bool ShowPluginFormInTaskbar => _showPluginFormInTaskbar.Checked;
internal bool ExpireAlerts => _alertExpiration.Checked;
internal bool ShowMagnifierButton => _magnifier.Checked;
internal bool ShowStopButton => _stopButton.Checked;
internal bool ShowChartButton => _charting.Checked;
internal void Display()
{
// Make launcher text 12.5% bigger than with LINQPad's default CSS.
// Do it here instead of globally so debugging dumps have normal size.
Util.WithStyle(_panel, "font-size: .9rem")
.Dump("Developer Mode Launcher");
ResumeUpdates();
}
internal void PauseUpdates() => _metatimer.Stop();
internal void ResumeUpdates() => _metatimer.Start();
private const string NumberBoxWidth = "5em";
private const int MetaTimerInterval = 150; // See _metatimer.
private static string FormatTimerResolution(uint ticks)
=> $"{ticks / NtDll.HundredNanosecondsPerMillisecond}{Ch.Nbsp}ms";
private static LC.TextBox CreateNumberBox(int? initialValue)
=> new(initialValue.ToString()) { Width = NumberBoxWidth };
private static LC.Table MakeEmptyTable()
=> new(noBorders: true,
cellPaddingStyle: ".3em .3em",
cellVerticalAlign: "middle");
private static void Disable(params LC.Control[] controls)
{
foreach (var control in controls) control.Enabled = false;
}
private LC.Table CreateSizeTable()
{
var table = MakeEmptyTable();
table.Rows.Add(new LC.Label("Width"), _widthBox);
table.Rows.Add(new LC.Label("Height"), _heightBox);
return table;
}
private LC.StackPanel CreateDelayPanel()
{
var table = MakeEmptyTable();
table.Rows.Add(new LC.Label("Delay (ms)"), _delayBox);
var description = new LC.Label(
"This is the requested minimum delay between frames.");
UpdateTimingNote();
return new(horizontal: false, table, description, _timingNote);
}
private LC.StackPanel CreateFeaturesPanel()
=> new(horizontal: false,
_alertExpiration,
_magnifier,
_stopButton,
_charting);
private void SubscribePrivateHandlers()
{
Util.Cleanup += delegate { _metatimer.Dispose(); };
_metatimer.Tick += delegate { UpdateTimingNote(); };
_widthBox.TextInput += widthBox_TextInput;
_heightBox.TextInput += heightBox_TextInput;
_delayBox.TextInput += delayBox_TextInput;
_launch.Click += launch_Click;
}
private void widthBox_TextInput(object? sender, EventArgs e)
=> HandleNumberInput(_widthBox, ref _width);
private void heightBox_TextInput(object? sender, EventArgs e)
=> HandleNumberInput(_heightBox, ref _height);
private void delayBox_TextInput(object? sender, EventArgs e)
=> HandleNumberInput(_delayBox, ref _delay);
private void launch_Click(object? sender, EventArgs e)
{
if (_width is not int width || _height is not int height) {
throw new NotSupportedException(
"Bug: Launch button enabled without width and height set.");
}
DisableInteractiveControls();
_postLaunch.Text = "(Launched. You can re-run the LINQPad query to"
+ " re-enable the launcher.)";
var size = new Size(width: width, height: height);
var eLauncher = new LauncherEventArgs(size, _useOldWebBrowser.Checked);
Launch?.Invoke(this, eLauncher);
}
private void HandleNumberInput(LC.TextBox sender, ref int? sink)
{
sink = int.TryParse(sender.Text, out var value) && value > 0
? value
: null;
UpdateLaunchButton();
}
private void UpdateLaunchButton()
=> _launch.Enabled = _width is int && _height is int && _delay is int;
private void UpdateTimingNote()
=> _timingNote.Text =
$"Note that the system timer{Ch.Rsquo}s resolution affects"
+ $" accuracy. {Environment.NewLine}({GetTimingNoteDetail()})";
private string GetTimingNoteDetail()
{
var result =
NtDll.NtQueryTimerResolution(out var worst, out _, out var actual);
if (result >= 0) {
_oldWorstTimerResolution = worst;
} else if (_oldWorstTimerResolution is uint oldWorst) {
worst = oldWorst;
} else {
return "I couldn't determine your system timer resolution.";
}
var worstStr = FormatTimerResolution(worst);
if (result >= 0) {
var actualStr = FormatTimerResolution(actual);
return $"Your system timer resolution is {worstStr} at worst,"
+ $" {actualStr} now.";
}
return $"Your system timer resolution is {worstStr} at worst.";
}
private void DisableInteractiveControls()
=> Disable(_widthBox,
_heightBox,
_delayBox,
_showPluginFormInTaskbar,
_useOldWebBrowser,
_alertExpiration,
_magnifier,
_stopButton,
_charting,
_launch);
// Timer for polling the system timer's timings. Not the system timer.
private readonly Timer _metatimer = new() { Interval = MetaTimerInterval };
private readonly LC.TextBox _widthBox;
private readonly LC.TextBox _heightBox;
private readonly LC.TextBox _delayBox;
private readonly LC.Label _timingNote = new();
private readonly LC.CheckBox _showPluginFormInTaskbar =
new("Show PluginForm in Taskbar");
private readonly LC.CheckBox _useOldWebBrowser =
new("Use old WebBrowser control even if WebView2 is available");
private readonly LC.CheckBox _alertExpiration =
new("Amend/remove expired alerts", isChecked: true);
private readonly LC.CheckBox _magnifier =
new("Magnifier", isChecked: true);
private readonly LC.CheckBox _stopButton =
new("Stop button", isChecked: true);
private readonly LC.CheckBox _charting = new("Charting", isChecked: true);
private readonly LC.Button _launch = new("Launch!");
private readonly LC.Label _postLaunch = new();
private readonly LC.StackPanel _panel;
private int? _width;
private int? _height;
private int? _delay = MainPanel.DefaultDelayInMilliseconds;
private uint? _oldWorstTimerResolution = null;
}
/// <summary>
/// Represents a helper for creating and switching output panels.
/// </summary>
/// <remarks>
/// See <see cref="PanelSwitcher"/>. Although it would make sense to have
/// different implementations for different policies, the main purpose of this
/// interface is to distinguish non-owning <see cref="PanelSwitcher"/>
/// references.
/// </remarks>
internal interface IPanelSwitcher {
/// <summary>Switches to a LINQPad panel, if it is open.</summary>
/// <param name="panel">
/// The <see cref="LINQPad.OutputPanel"/> to switch to, or <c>null</c> to
/// switch to the "Results" panel.
/// </param>
/// <returns><c>true</c> on success, <c>false</c> on failure.</returns>
bool TrySwitch(OutputPanel? panel);
/// <summary>
/// Switches to a LINQPad if it is open. Throws an exception otherwise.
/// </summary>
/// <param name="panel">
/// The <see cref="LINQPad.OutputPanel"/> to switch to, or <c>null</c> to
/// switch to the "Results" panel.
/// </param>
/// <remarks>See <see cref="TrySwitch"/>.</remarks>
void Switch(OutputPanel? panel);
/// <summary>
/// Opens an output panel for a control and switches to it.
/// </summary>
/// <param name="control">The control to display in the panel.</param>
/// <param name="panelTitle">The panel's title in the toolstrip.</param>
/// <returns>The panel that was created.</returns>
OutputPanel DisplayForeground(Control control, string panelTitle);
/// <summary>
/// Opens an output panel for a control. Tries not to switch to it.
/// </summary>
/// <param name="control">The control to display in the panel.</param>
/// <param name="panelTitle">The panel's title in the toolstrip.</param>
/// <returns>The panel that was created.</returns>
OutputPanel DisplayBackground(Control control, string panelTitle);
}
/// <summary>Default implementation of <see cref="IPanelSwitcher"/>.</summary>
internal sealed class PanelSwitcher : Component, IPanelSwitcher {
internal PanelSwitcher(IContainer components) : this()
=> components.Add(this);
internal PanelSwitcher() => _timer.Tick += timer_Tick;
// FIXME: Since I'm using this for important UI features--switching to the
// open help panel when Help is clicked again, and to a chart when its
// notification is clicked--it's very bad that I'm violating encapsulation.
// OutputPanel.Activate has the "internal" acccess modifier; queries aren't
// expected to use it, and it may be removed (or worse, change) at any
// time. Unfortunately, there doesn't seem to be another way to do this.
//
// PanelManager.GetOutputPanels() returns an array of output panels, and
// writing to Util.SelectedOutputPanelIndex switches panels. When output
// panels are created in such a way as to be listed from left to right in
// the order of creation--such as when they are created sequentially by
// interacting with LINQPad controls in the Results panel--they are indexed
// in the same order and it is sufficient to add and subtract 1 [since
// Util.SelectedOutputPanelIndex is 0 for the Results panel, which is not
// actually an OutputPanel object and thus doesn't appear in
// PanelManager.GetOutputPanels()]. The order needn't otherwise agree, I
// believe because new panels are not necessarily added to the very end of
// the strip, but are instead usually added just to the right of the panel
// from which they're displayed.
//
// I don't think it's reasonable to attempt to maintain a correspondence
// between the two orders. Besides writing to Util.SelectOutputPanelIndex,
// it is also possible to read from it, but indices aren't stable as other
// panels open and close; caching an index to get back to it does not seem
// to work either (aside from 0 for getting back to the Results panel or
// checking if we are there). What I need to do is investigate a bit
// futher; produce simple, reproducible examples; and inquire on the
// LINQPad forums and/or request a feature.
/// <inheritdoc/>
public bool TrySwitch(OutputPanel? panel)
{
ThrowIfDisposed();
if (panel is null) {
Util.SelectedOutputPanelIndex = 0;
} else if (PanelManager.GetOutputPanels().Contains(panel)) {
panel.Uncapsulate().Activate();
} else {
return false;
}
_sticky = panel;
return true;
}
/// <inheritdoc/>
public void Switch(OutputPanel? panel)
{
if (!TrySwitch(panel)) {
throw new InvalidOperationException(
"Bug: The panel is closed or otherwise unavailable.");
}
}
/// <inheritdoc/>
public OutputPanel DisplayForeground(Control control, string panelTitle)
{
ThrowIfDisposed();
var panel = PanelManager.DisplayControl(control, panelTitle);
_sticky = panel;
return panel;
}
/// <inheritdoc/>
/// <remarks>
/// LINQPad doesn't support opening a new <see cref="OutputPanel"/> without
/// activating it. So this opens the panel and then, on a best-effort
/// basis, tries to switch back to the panel that is would next be active.
/// </remarks>
public OutputPanel DisplayBackground(Control control, string panelTitle)
{
var foreground = ForegroundPanel;
var background = PanelManager.DisplayControl(control, panelTitle);
TrySwitch(foreground);
return background;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed) {
_disposed = true;
_timer.Dispose();
}
base.Dispose(disposing);
}
private const int ForegroundSnapshotInterval = 180;
private static OutputPanel? CurrentVisiblePanel
=> PanelManager.GetOutputPanels()
.SingleOrDefault(panel => panel.IsVisible);
private OutputPanel? ForegroundPanel
=> (_sticky is null || (_oldest == _older && _older == _old))
? _old
: _sticky;
private void ThrowIfDisposed()
{
if (_disposed) {
throw new ObjectDisposedException(
objectName: nameof(PanelSwitcher),
message: "Can't switch panels with disposed switcher.");
}
}
private void timer_Tick(object? sender, EventArgs e)
{
var last = (Util.SelectedOutputPanelIndex == 0
? null
: CurrentVisiblePanel ?? _old);
(_oldest, _older, _old) = (_older, _old, last);
}
private readonly Timer _timer = new() {
Interval = ForegroundSnapshotInterval,
Enabled = true,
};
private OutputPanel? _sticky = null;
private OutputPanel? _oldest = null;
private OutputPanel? _older = null;
private OutputPanel? _old = null;
private bool _disposed = false;
}
/// <summary>
/// The main user interface, containing an interactive canvas, an info bar, and
/// expandable/collapsible tips.
/// </summary>
internal sealed class MainPanel : TableLayoutPanel {
internal static int DefaultDelayInMilliseconds { get; } = 10;
internal MainPanel(Size canvasSize, HelpViewerSupplier supplier)
{
_nonessentialTimer = new(_components) { Interval = NonessentialDelay };
_toolTip = new(_components) { ShowAlways = true };
_switcher = new PanelSwitcher(_components);
_rect = new(Point.Empty, canvasSize);
_bmp = new(width: _rect.Width, height: _rect.Height);
_graphics = CreateCanvasGraphics();
_canvas = CreateCanvas();
_alert = CreateAlertBar();
_help = new(supplier, _switcher, _toolTip);
_helpButtons = CreateHelpButtons();
_magnify = new MagnifyButton(_showHideTips.Height, _alert, _toolTip);
_stop = CreateStop();
_stopHost = new(_stop, _toolTip);
_charting = CreateCharting();
_infoBar = CreateInfoBar();
_neighborEnumerationStrategies = CreateNeighborEnumerationStrategies();
InitializeMainPanel();
PerformInitialUpdates();
SubscribePrivateHandlers();
}
internal int DelayInMilliseconds { get; init; } =
DefaultDelayInMilliseconds;
internal bool ShowParentInTaskbar { get; init; } = false;
internal bool ExpireAlerts { get; init; } = true;
internal bool MagnifierButtonVisible
{
get => _magnify.Visible;
set => _magnify.Visible = value;
}
internal bool StopButtonVisible
{
get => _stopHost.Visible;
set => _stopHost.Visible = value;
}
internal bool ChartingButtonVisible
{
get => _charting.Visible;
set => _charting.Visible = value;
}
internal event EventHandler? Activated;
internal event EventHandler? Deactivate;
internal void Display()
=> _switcher.DisplayForeground(this, "Flood Fill Visualization");
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
var pluginForm = (Form)Parent;
if (ShowParentInTaskbar) pluginForm.ShowInTaskbar = true;
// Update "Speed" in status from modifier keys, crisply when
// reasonable. Unlike with an ordinary form, users can't readily see if
// a PluginForm is active, and it starts inactive. So update it, albeit
// slower, even when not. (These are two of the three cases. The other
// is when _tips is focused. See MainPanel.SubscribePrivateHandlers.)
pluginForm.KeyPreview = true;
pluginForm.KeyDown += delegate { PropagateStatus(); };
pluginForm.KeyUp += delegate { PropagateStatus(); };
pluginForm.Activated += Parent_Activated;
pluginForm.Deactivate += Parent_Deactivate;
_nonessentialTimer.Start();
}
protected override async void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (_shownBefore || !Visible) return;
_shownBefore = true;
// When the launcher is used, even without changing anything, VScroll
// is always true here, which caused "Low vertical space" to always
// appear. Processing enqueued window messages first works around it. I
// don't know why. I suspect this is too early and should be a handler
// for another event (maybe on the PluginForm). I haven't encountered
// cases without the launcher but I suspect there may be others, and
// since the user can't interact much with the panel in that time, this
// seems harmless.
//
// TODO: Figure out what's going on and if there's a better fix.
await Task.Yield();
if (VScroll) {
_alert.Show(
"Low vertical space. Rearranging panels (Ctrl+F8) may help.");
VerticalScroll.Value = 0; // Also needed when the launcher is used.
}
}
protected override void WndProc(ref Message m)
{
// If the user pressed a Windows key (Super key) as a modifier for a
// canvas command (successful or not), avoid activating the Start Menu.
if ((User32.WM)m.Msg is User32.WM.KEYUP
&& (User32.VK)m.WParam is User32.VK.LWIN or User32.VK.RWIN
&& _suppressStartMenu) {
_suppressStartMenu = false;
if (Focused) {
// Simulate concurrent input to prevent the Windows key from
// opening the Start Menu. Don't use anything this program or
// LINQPad treats specially.
//
// TODO: Decide if this is really less bad than a manual hook.
SendKeys.Send(KeystrokeProbablyNotInShortcutsOrAccelerators);
}
}
base.WndProc(ref m);
}
protected override void Dispose(bool disposing)
{
if (disposing) {
StopAllFills();
_components.Dispose();
_bmp.Dispose();
_graphics.Dispose();
_pen.Dispose();
}
base.Dispose(disposing);
}
private const int UnknownCount = -1;
private const int NonessentialDelay = 90; // See _nonessentialTimer.
private const int StatusFontSize = 10;
private const int Pad = 2;
private static Padding CanvasMargin { get; } =
new(left: Pad, top: Pad, right: 0, bottom: 0);
private static string
KeystrokeProbablyNotInShortcutsOrAccelerators { get; } =
Ch.UumlWedge.ToString();
private static int DecideSpeed()
=> (ModifierKeys & (Keys.Shift | Keys.Control)) switch {
Keys.Shift => 1,
Keys.Control => 20,
Keys.Shift | Keys.Control => 10,
_ => 5
};
private static bool StoppingIsImmediate => GotKey.Ctrl;
private static string EnabledStopButtonToolTip
=> StoppingIsImmediate
? $"Stop running fills!{Environment.NewLine}"
+ "(No confirmation, even for multiple fills.)"
: "Stop running fills";
private static string StopOfferToolTip { get; } =
"Click here to confirm you want to stop all running fills."
+ Environment.NewLine
+ "(To not be prompted, you can Ctrl+click the Stop button.)";
private Graphics CreateCanvasGraphics()
{
var graphics = Graphics.FromImage(_bmp);
graphics.FillRectangle(Brushes.White, _rect);
return graphics;
}
private PictureBox CreateCanvas() => new() {
Image = _bmp,
SizeMode = PictureBoxSizeMode.AutoSize,
Margin = CanvasMargin,
};
private AlertBar CreateAlertBar() => new(_toolTip) {
Width = _rect.Width,
Margin = CanvasMargin,
};
private TableLayoutPanel CreateHelpButtons()
{
var toggles = new TableLayoutPanel {
RowCount = 1,
ColumnCount = 2,
GrowStyle = TableLayoutPanelGrowStyle.FixedSize,
AutoSize = true,
Anchor = AnchorStyles.Top | AnchorStyles.Right,
Margin = Padding.Empty,
};
toggles.Controls.Add(_showHideTips);
toggles.Controls.Add(_help);
return toggles;
}
private Button CreateStop()
=> new BitmapButton(enabledBitmapFilename: "stop.bmp",
disabledBitmapFilename: "stop-faded.bmp",
_showHideTips.Height);
private AnimatedBitmapCheckBox CreateCharting()
=> new(from i in Enumerable.Range(1, 6)
select new CheckBoxBitmapFilenamePair($"chart{i}.bmp",
$"chart{i}-gray.bmp"),
_showHideTips.Height,
FrameSequence.Oscillating);
private TableLayoutPanel CreateInfoBar()
{
var infoBar = new TableLayoutPanel {
RowCount = 1,
ColumnCount = 5,
GrowStyle = TableLayoutPanelGrowStyle.FixedSize,
Width = _rect.Width,
};
infoBar.Controls.Add(_status, column: 3, row: 0);
infoBar.Controls.Add(_helpButtons, column: 4, row: 0);
// Must be after adding _helpButtons.
infoBar.Height = _helpButtons.Height;
infoBar.Controls.Add(_magnify, column: 0, row: 0);
infoBar.Controls.Add(_stopHost, column: 1, row: 0);
infoBar.Controls.Add(_charting, column: 2, row: 0);
return infoBar;
}
private Carousel<NeighborEnumerationStrategy>
CreateNeighborEnumerationStrategies()
=> new(new UniformStrategy(),
new RandomPerFillStrategy(_generator),
new RandomEachTimeStrategy(_generator),
new RandomPerPixelStrategy(_rect.Size, _generator));
private void InitializeMainPanel()
{
RowCount = 4;
ColumnCount = 1;
GrowStyle = TableLayoutPanelGrowStyle.FixedSize;
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
AutoScroll = true;
Controls.Add(_alert);
Controls.Add(_canvas);
Controls.Add(_infoBar);
Controls.Add(_tips);
}
private void PerformInitialUpdates()
{
UpdateStopButtonState();
UpdateCharting();
PropagateStatus();
UpdateShowHideTips();
}
/// <remarks>
/// Separate from <see cref="PropagateStatus"/> so the tooltip does not
/// become incorrect if a lag spike occurs while stopping all fills.
/// </remarks>
private void UpdateStopButtonState()
{
if (_jobs == 0) {
_stopHost.DisabledToolTip = "No running fills to stop";
_stop.Enabled = false;
} else {
_stop.Enabled = true;
}
}
private void UpdateCharting()
{
_charting.Animated = _jobsCharting != 0;
var (lede, comment) =
_charting.Checked
? ("Click to NOT chart newly started fills.",
"As of now, newly started fills will chart.")
: ("Click to chart newly started fills.",
"As of now, newly started fills will not chart.");
var detail = (_jobsCharting, _charting.Checked) switch {
(0, false) =>
"Also, no currently running fills are charting.",
(0, true) =>
"But no currently running fills are charting.",
(1, false) =>
$"But {_jobsCharting} currently running fill is charting.",
(1, true) =>
$"Also, {_jobsCharting} currently running fill is charting.",
(_, false) =>
$"But {_jobsCharting} currently running fills are charting.",
(_, true) =>
$"Also, {_jobsCharting} currently running fills are charting.",
};
var report = string.Join(Environment.NewLine, lede, comment, detail);
_toolTip.SetToolTip(_charting, report);
}
private void PropagateStatus()
{
var strategy = _neighborEnumerationStrategies.Current.ToString();
var speed = DecideSpeed();
if (strategy.Equals(_oldStrategy, StringComparison.Ordinal)
&& speed == _oldSpeed && _jobs == _oldJobs)
return;
UpdateStopOffer();
UpdateStatusText(strategy, speed, _jobs);
UpdateStatusToolTip(strategy, speed, _jobs);
_magnify.UpdateToolTip();
_stopHost.EnabledToolTip = EnabledStopButtonToolTip;
_help.UpdateToolTip();
(_oldStrategy, _oldSpeed, _oldJobs) = (strategy, speed, _jobs);
}
private void UpdateStopOffer()
{
if (_stopCookie is null || _jobs == _oldJobs) return;
if (_stopCookie.IsCurrent && _alert.Visible) {
if (_jobs != 0) {
OfferStopDetailed();
return;
}
_alert.Hide();
}
_stopCookie = null;
}
private void UpdateStatusText(string strategy, int speed, int jobs)
{
const string spacer = " ";
var speedSummary = $"{speed}{Ch.Times}";
var jobsSummary = (jobs == 1 ? $"{jobs} job" : $"{jobs} jobs");
_status.Text =
string.Join(spacer, strategy, speedSummary, jobsSummary);
}
private void UpdateStatusToolTip(string strategy, int speed, int jobs)
{
var strategyDetail = $"New fills{Ch.Rsquo} neighbor enumeration"
+ $" strategy is {Ch.Ldquo}{strategy}.{Ch.Rdquo}";
var speedQuantity = (speed == 1 ? $"{speed} pixel per frame"
: $"{speed} pixels per frame");
var speedDetail =
$"New fills{Ch.Rsquo} drawing speed is {speedQuantity}.";
var jobsDetail = jobs switch {
0 => "No fills are currently running.",
1 => $"{jobs} fill is currently running.",
_ => $"{jobs} fills are currently running.",
};
var details = string.Join(Environment.NewLine,
strategyDetail, speedDetail, jobsDetail);
_toolTip.SetToolTip(_status, details);
}
private void UpdateShowHideTips()
{
if (_tips.Visible) {
_showHideTips.Text = "Hide Tips";
_toolTip.SetToolTip(_showHideTips, "Collapse brief help below");
} else {
_showHideTips.Text = "Show Tips";
_toolTip.SetToolTip(_showHideTips, "Expand brief help below");
}
}
private void SubscribePrivateHandlers()
{
Util.Cleanup += delegate { Dispose(); };
_nonessentialTimer.Tick += delegate { PropagateStatus(); };
_canvas.MouseMove += canvas_MouseMove;
_canvas.MouseDown += canvas_MouseDown;
_canvas.MouseClick += canvas_MouseClick;
_canvas.MouseWheel += canvas_MouseWheel;
_stop.Click += stop_Click;
_stop.LostFocus += stop_LostFocus;
_charting.CheckedChanged += delegate { UpdateCharting(); };
_showHideTips.Click += showHideTips_Click;
// Update the UI (especially the status bar) from modifier keys pressed
// or released while _tips has focus. This must be covered separately
// because keypresses sent to a WebBrowser control are not previewed by
// the containing form, notwithstanding KeyPreview. (This is one of
// three cases; see MainPanel.OnHandleCreated for the other two.)
_tips.PreviewKeyDown += delegate { PropagateStatus(); };
_tips.PreviewKeyUp += delegate { PropagateStatus(); };
_tips.HelpRequest += tips_HelpRequest;
}
private void Parent_Activated(object? sender, EventArgs e)
{
// If the parent is detached, don't respond to its activation.