-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.linq
1207 lines (979 loc) · 38.7 KB
/
generator.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="Program">
<Namespace>LC = LINQPad.Controls</Namespace>
<Namespace>System.ComponentModel</Namespace>
<Namespace>System.Drawing</Namespace>
<Namespace>System.Numerics</Namespace>
<Namespace>System.Runtime.InteropServices</Namespace>
<Namespace>System.Security.Cryptography</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
<Namespace>WF = System.Windows.Forms</Namespace>
</Query>
// Copyright (C) 2020 Eliah Kagan <[email protected]>
//
// 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.
#load "./helpers.linq"
#nullable enable
/// <summary>Extensions for clearer and more compact regex usage.</summary>
internal static class MatchExtensions {
internal static string Group(this Match match, int index)
=> match.Groups[index].ToString();
}
/// <summary>
/// An inclusive range represented by a pair of integer endpoints.
/// </summary>
/// <remarks>
/// This differs from <see cref="System.Range"/> by being closed and not
/// supporting <c>FromEnd</c> (endpoints are absolute, i.e., from start).
/// </remarks>
internal readonly struct ClosedInterval {
internal static ClosedInterval? Parse(string text)
=> SplitParse(text, MaybeNegativeIntervalSplitter);
internal static ClosedInterval? ParseNonNegative(string text)
=> SplitParse(text, NonNegativeIntervalSplitter);
internal ClosedInterval(int min, int max) => (Min, Max) = (min, max);
public override string ToString() => $"{Min}-{Max}";
internal int Min { get; }
internal int Max { get; }
internal long Count => Max < Min ? 0L : (long)Max - (long)Min + 1L;
private static ClosedInterval? SplitParse(string text, Regex splitter)
{
var match = splitter.Match(text);
if (match.Success && int.TryParse(match.Group(1), out var start)
&& int.TryParse(match.Group(2), out var end))
return new ClosedInterval(start, end);
return null;
}
private static readonly Regex MaybeNegativeIntervalSplitter =
new Regex(@"^\s*(-?[^-\s]+)\s*-\s*(-?[^-\s]+)\s*$",
RegexOptions.Compiled);
// int.Parse tolerates whitespace, no need to parse around it.
private static readonly Regex NonNegativeIntervalSplitter =
new Regex(@"^([^-]+)-([^-]+)$", RegexOptions.Compiled);
}
/// <summary>
/// Random number generator of <see cref="System.UInt64"/> values.
/// </summary>
/// <remarks>
/// Supports sampling from arbitrary large closed intervals, including the
/// while range of <c>ulong</c>.
/// </remarks>
internal abstract class LongRandom {
static LongRandom()
=> Debug.Assert(1 << ShiftCount == BufferSize * BitsPerByte);
internal virtual ulong Next(ulong max)
{
var mask = Mask(max);
for (; ; ) {
NextBytes(_buffer);
var result = BitConverter.ToUInt64(_buffer, 0) & mask;
if (result <= max) return result;
}
}
private protected abstract void NextBytes(byte[] buffer);
private const int BitsPerByte = 8;
private const int BufferSize = sizeof(ulong); // 8
private const int ShiftCount = 6;
private static ulong Mask(ulong max)
{
var mask = max;
for (var i = 0; i != ShiftCount; ++i) mask |= mask >> (1 << i);
return mask;
}
private readonly byte[] _buffer = new byte[BufferSize];
}
/// <summary>
/// <see cref="System.Random"/>-based random number generator of
/// <see cref="System.UInt64"/> values.
/// </summary>
internal sealed class FastLongRandom : LongRandom {
internal FastLongRandom()
: this(RandomNumberGenerator.GetInt32(int.MaxValue)) { }
internal FastLongRandom(int seed) => _random = new Random(seed);
internal override ulong Next(ulong max)
=> max < int.MaxValue ? (ulong)_random.Next((int)max + 1)
: base.Next(max);
private protected override void NextBytes(byte[] buffer)
=> _random.NextBytes(buffer);
private readonly Random _random;
}
/// <summary>
/// <see cref="System.Security.Cryptography.RandomNumberGenerator"/>-based
/// random number generator of <see cref="System.UInt64"/> values.
/// </summary>
internal sealed class GoodLongRandom : LongRandom {
private protected override void NextBytes(byte[] buffer)
=> _random.GetBytes(buffer);
private readonly RandomNumberGenerator _random =
RandomNumberGenerator.Create();
}
/// <summary>Extension methods for <see cref="LongRandom"/>.</summary>
internal static class LongRandomExtensions {
internal static int NextInt32(this LongRandom prng, int min, int max)
{
if (max < min) {
throw new ArgumentOutOfRangeException(
paramName: nameof(min),
message: "can't sample from empty range");
}
var zeroBasedMax = (ulong)((long)max - (long)min);
var value = (long)min + (long)prng.Next(zeroBasedMax);
return (int)value;
}
}
internal sealed class DistinctSampler {
internal DistinctSampler(LongRandom prng, ulong upperExclusive)
=> (_prng, _size) = (prng, upperExclusive);
internal ulong Next()
{
if (_size == 0)
throw new InvalidOperationException("sample space exhausted");
var key = _prng.Next(max: --_size);
var value = _remap.GetValueOrDefault(key, key);
_remap[key] = _remap.GetValueOrDefault(_size, _size);
return value;
}
private readonly LongRandom _prng;
private readonly Dictionary<ulong, ulong> _remap =
new Dictionary<ulong, ulong>();
/// <summary>The number of values remaining to hand out.</summary>
private ulong _size;
}
/// <summary></summary>
internal readonly struct EdgeList {
internal EdgeList(int order, int size, IEnumerable<Edge> edges)
=> (Order, Size, Edges) = (order, size, edges);
internal void Deconstruct(out int order, out int size,
out IEnumerable<Edge> edges)
=> (order, size, edges) = (Order, Size, Edges);
internal int Order { get; }
// TODO: Should giant graphs, of over int.MaxValue edges, be supported?
internal int Size { get; }
internal IEnumerable<Edge> Edges { get; }
private object ToDump() => new { Order, Size, Edges };
}
/// <summary>
/// Randomly generates a graph description from specified constraints.
/// </summary>
internal sealed class GraphGenerator {
internal GraphGenerator(ClosedInterval orders,
ClosedInterval sizes,
ClosedInterval weights,
bool allowLoops,
bool allowParallelEdges,
bool uniqueWeights,
bool allowNegativeWeights,
LongRandom prng)
{
_orders = orders;
_sizes = sizes;
_weights = weights;
_allowLoops = allowLoops;
_allowParallelEdges = allowParallelEdges;
_uniqueWeights = uniqueWeights;
_allowNegativeWeights = allowNegativeWeights;
_prng = prng;
Error = CheckEachInterval()
?? CheckEachCardinality()
?? CheckSizeAgainstOrder()
?? CheckWeightRange();
}
internal string? Error { get; }
// TODO: Figure out if this should use IObservable instead.
internal EdgeList Generate()
{
if (Error != null) throw new InvalidOperationException(Error);
var order = _prng.NextInt32(_orders.Min, _orders.Max);
var size = _prng.NextInt32(_sizes.Min, ComputeMaxSize(order));
return new EdgeList(order, size, EmitEdges(order, size));
}
private IEnumerable<Edge> EmitEdges(int order, int size)
{
Debug.Assert(order >= 0 && size >= 0);
var nextEndpoints = CreateEndpointsGenerator(order);
var nextWeight = CreateWeightGenerator();
for (var i = 0; i < size; ++i) {
var (src, dest) = nextEndpoints();
yield return new Edge(src, dest, nextWeight());
}
}
private Func<(int src, int dest)> CreateEndpointsGenerator(int order)
{
var decode = CreateEndpointsDecoder(order);
var next = CreateEncodedEndpointsGenerator(order);
return () => decode(next());
}
private Func<ulong> CreateEncodedEndpointsGenerator(int order)
{
var cardinality = (ulong)ComputeCompleteSize(order);
if (_allowParallelEdges)
return () => _prng.Next(max: cardinality - 1);
return new DistinctSampler(_prng, upperExclusive: cardinality).Next;
}
private Func<ulong, (int src, int dest)>
CreateEndpointsDecoder(int order)
{
var longOrder = (ulong)order;
if (_allowLoops) {
return encodedEndpoints => {
var src = encodedEndpoints / longOrder;
var dest = encodedEndpoints % longOrder;
return (src: (int)src, dest: (int)dest);
};
}
return encodedEndpoints => {
var src = encodedEndpoints / (longOrder - 1);
var dest = encodedEndpoints % (longOrder - 1);
if (src <= dest) ++dest;
return (src: (int)src, dest: (int)dest);
};
}
private Func<int> CreateWeightGenerator()
{
var count = (ulong)_weights.Count;
int Bias(ulong zeroBasedWeight)
=> (int)(_weights.Min + (long)zeroBasedWeight);
if (_uniqueWeights) {
var sampler = new DistinctSampler(_prng, upperExclusive: count);
return () => Bias(sampler.Next());
}
return () => Bias(_prng.Next(max: count - 1));
}
private string? CheckEachInterval()
{
if (_orders.Count == 0)
return "Range of orders contains no values";
if (_sizes.Count == 0)
return "Range of sizes contains no values";
if (_weights.Count == 0)
return "Range of weights contains no values";
return null;
}
private string? CheckEachCardinality()
{
if (_orders.Min < 0) return "Order (vertex count) can't be negative";
if (_sizes.Min < 0) return "Size (edge count) can't be negative";
return null;
}
private string? CheckSizeAgainstOrder()
{
var order = _orders.Min;
var size = ComputeMaxSize(order);
if (_sizes.Min <= size) return null;
return (order, size) switch {
(1, 1) => $"1 vertex allows only 1 edge",
(1, _) => $"1 vertex allows only {size} edges",
(_, 1) => $"{order} vertices allow only 1 edge", // Unused.
(_, _) => $"{order} vertices allow only {size} edges"
};
}
private string? CheckWeightRange()
{
if (!_allowNegativeWeights && _weights.Min < 0)
return "Negative edge weights not supported";
// If weights must be unique, ensure the *whole* size range is okay.
if (_uniqueWeights && _weights.Count < _sizes.Max) {
return (_sizes.Max, _weights.Count) switch {
(1, 1) => $"1 edge but only 1 weight", // Unused.
(1, var w) => $"1 edge but only {w} weights", // Unused.
(var n, 1) => $"{n} edges but only 1 weight",
(var n, var w) => $"{n} edges but only {w} weights"
};
}
return null;
}
private int ComputeMaxSize(int order)
{
Debug.Assert(order >= 0);
if (order == 0 || (order == 1 && !_allowLoops)) return 0;
if (_allowParallelEdges) return _sizes.Max;
return (int)Math.Min(_sizes.Max, ComputeCompleteSize(order));
}
private long ComputeCompleteSize(long order)
=> order * (_allowLoops ? order : order - 1);
private readonly ClosedInterval _orders;
private readonly ClosedInterval _sizes;
private readonly ClosedInterval _weights;
private readonly bool _allowLoops;
private readonly bool _allowParallelEdges;
private readonly bool _uniqueWeights;
private readonly bool _allowNegativeWeights;
private readonly LongRandom _prng;
}
/// <summary></summary>
internal sealed class GraphGeneratingEventArgs : EventArgs {
internal GraphGeneratingEventArgs(int order, int size)
=> (Order, Size) = (order, size);
internal int Order { get; }
internal int Size { get; }
}
/// <summary></summary>
internal sealed class GraphGeneratedEventArgs : EventArgs {
internal GraphGeneratedEventArgs(int order, int size,
IReadOnlyList<Edge> edges)
=> (Order, Size, Edges) = (order, size, edges);
internal int Order { get; }
internal int Size { get; }
internal IReadOnlyList<Edge> Edges { get; }
}
/// <summary></summary>
internal delegate void
GraphGeneratingEventHandler(object sender, GraphGeneratingEventArgs e);
/// <summary></summary>
internal delegate void
GraphGeneratedEventHandler(object sender, GraphGeneratedEventArgs e);
/// <summary>Graphical frontend for GraphGenerator.</summary>
internal sealed class GraphGeneratorDialog : WF.Form {
internal GraphGeneratorDialog()
{
SuspendLayout();
SetFormProperties();
SubscribeFormEvents();
SubscribeChildControlEvents();
SetAllToolTips();
AddChildControls();
ResumeLayout();
}
internal void DisplayDialog()
=> RunOrBeginInvoke(delegate {
if (Visible) Hide();
Show();
WindowState = WF.FormWindowState.Normal;
});
internal event GraphGeneratingEventHandler? Generating = null;
internal event GraphGeneratedEventHandler Generated
{
add {
if (value == null)
throw new ArgumentNullException(paramName: nameof(value));
bool wasNull;
lock (_sinksLocker) {
wasNull = _sinks == null;
_sinks += value;
}
if (wasNull) RunOrBeginInvoke(InvalidateGenerator);
}
remove {
bool becameNull;
lock (_sinksLocker) {
var wasNull = _sinks == null;
_sinks -= value;
becameNull = !wasNull && _sinks == null;
}
if (becameNull) RunOrBeginInvoke(InvalidateGenerator);
}
}
protected override void WndProc(ref WF.Message m)
{
// If the message is WM_SYSCOMMAND *and* it is one of our system-menu
// customizations, handle it here rather than passing it upward.
if ((WindowMessage)m.Msg == WindowMessage.WM_SYSCOMMAND) {
switch ((MyMenuItemId)m.WParam) {
case MyMenuItemId.KeepOnTop:
ToggleTopMost();
return;
case MyMenuItemId.Translucent:
ToggleTranslucence();
return;
case MyMenuItemId.StatusCaret:
ToggleStatusCaretPreference();
return;
case MyMenuItemId.CopyStatusToClipboard:
CopyStatus();
return;
default:
break; // Others are possible but shouldn't be handled here.
}
}
// Otherwise, the message MUST be passed upward.
base.WndProc(ref m);
}
private const double FullOpacity = 1.0;
private const double ActiveOpacity = 0.9;
private const double InactiveOpacity = 0.8;
private const double MovingOpacity = 0.6;
[Flags]
private enum MenuFlags : uint {
MF_UNCHECKED = 0x0,
MF_CHECKED = 0x8,
MF_BYCOMMAND = 0x0,
MF_BYPOSITION = 0x400,
MF_STRING = 0x0,
MF_SEPARATOR = 0x800,
}
private enum MyMenuItemId : uint {
UnusedId, // For clarity, pass this when the ID will be ignored.
KeepOnTop,
Translucent,
StatusCaret,
CopyStatusToClipboard,
}
private enum WindowMessage : uint {
WM_SYSCOMMAND = 0x112,
}
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool AppendMenu(IntPtr hMenu,
MenuFlags uFlags,
MyMenuItemId uIDNewItem,
string? lpNewItem);
[DllImport("user32.dll")]
private static extern uint CheckMenuItem(IntPtr hMenu,
MyMenuItemId uIDCheckItem,
MenuFlags uCheck);
[DllImport("user32.dll")]
private static extern bool HideCaret(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowCaret(IntPtr hWnd);
private static void SubscribeNormalizer(WF.TextBox textBox,
Func<string, string> normalizer)
=> textBox.LostFocus += delegate {
var normalized = normalizer(textBox.Text);
if (textBox.Text != normalized) textBox.Text = normalized;
};
private static string NormalizeAsValueOrClosedInterval(string text)
{
if (ParseValue(text) is int value) return value.ToString();
if (ClosedInterval.ParseNonNegative(text) is ClosedInterval interval) {
return interval.Min == interval.Max
? interval.Min.ToString() // Collapse n-n to n.
: interval.ToString();
}
return text;
}
private static string NormalizeAsClosedInterval(string text)
{
if (ClosedInterval.ParseNonNegative(text) is ClosedInterval interval)
return interval.ToString();
if (ParseValue(text) is int value)
return new ClosedInterval(value, value).ToString();
return text;
}
private static int? ParseValue(string text)
=> int.TryParse(text, out var value) ? value : default(int?);
private static MenuFlags CheckedFlag(bool @checked)
=> @checked ? MenuFlags.MF_CHECKED : MenuFlags.MF_UNCHECKED;
private IntPtr MenuHandle => GetSystemMenu(Handle, bRevert: false);
private void AddMenuSeparator()
=> AppendMenu(MenuHandle,
MenuFlags.MF_SEPARATOR,
MyMenuItemId.UnusedId,
null);
private void AddMenuItem(MyMenuItemId uIDNewItem, string lpNewItem,
bool @checked = false)
=> AppendMenu(MenuHandle,
MenuFlags.MF_STRING | CheckedFlag(@checked),
uIDNewItem,
lpNewItem);
private void SetMenuItemCheck(MyMenuItemId id, bool @checked)
=> CheckMenuItem(MenuHandle, id, CheckedFlag(@checked));
private void SetFormProperties()
{
AutoScaleDimensions = new SizeF(7f, 15f);
AutoScaleMode = WF.AutoScaleMode.Font;
AutoSize = true;
Text = "Graph Generator";
Size = new Size(width: 300, height: 210);
FormBorderStyle = WF.FormBorderStyle.Fixed3D;
MaximizeBox = false;
KeyPreview = true;
}
private void SubscribeFormEvents()
{
HandleCreated += GraphGeneratorDialog_HandleCreated;
Shown += GraphGeneratorDialog_FormShown;
FormClosing += GraphGeneratorDialog_FormClosing;
Activated += GetOpacitySetter(ActiveOpacity);
Deactivate += GetOpacitySetter(InactiveOpacity);
Move += GetOpacitySetter(MovingOpacity);
Resize += GetOpacitySetter(ActiveOpacity);
ResizeEnd += GetOpacitySetter(ActiveOpacity);
KeyDown += GraphGeneratorDialog_KeyDown;
}
private void SubscribeChildControlEvents()
{
_order.TextChanged += InvalidateGenerator;
_size.TextChanged += InvalidateGenerator;
_weights.TextChanged += InvalidateGenerator;
_allowLoops.CheckedChanged += InvalidateGenerator;
_allowParallelEdges.CheckedChanged += InvalidateGenerator;
_uniqueEdgeWeights.CheckedChanged += InvalidateGenerator;
_highQualityPrng.CheckedChanged += InvalidateGenerator;
SubscribeNormalizer(_order, NormalizeAsValueOrClosedInterval);
SubscribeNormalizer(_size, NormalizeAsValueOrClosedInterval);
SubscribeNormalizer(_weights, NormalizeAsClosedInterval);
_status.GotFocus += status_GotFocus;
_generate.Click += generate_Click;
_cancel.Click += cancel_Click;
_close.Click += delegate { Hide(); };
}
private void SetAllToolTips()
{
SetToolTips("number of vertices", _orderLabel, _order);
SetToolTips("number of edges", _sizeLabel, _size);
SetToolTips("range of possible edge weights", _weightsLabel, _weights);
SetToolTip(_allowLoops,
"May the graph have self-edges, i.e., loops?\n"
+ "A self-edge is an edge from a vertex to itself.");
SetToolTip(_allowParallelEdges,
"May the graph have parallel edges?\n"
+ "These are multiple edges from the same source\n"
+ "vertex to the same destination vertex. Note that\n"
+ "edges in opposite directions between the same\n"
+ "vertices are always permitted.");
SetToolTip(_uniqueEdgeWeights,
"Must no two edges have the same weight?");
SetToolTip(_highQualityPrng,
"slower but higher quality pseudorandom number generation");
SetToolTip(_status, "status");
SetToolTip(_generate,
"generate a random graph meeting these parameters");
SetToolTip(_cancel, "cancel the current graph generation operation");
SetToolTip(_close, "dismiss this dialog");
}
private void AddChildControls()
{
Controls.Add(_orderLabel);
Controls.Add(_order);
Controls.Add(_sizeLabel);
Controls.Add(_size);
Controls.Add(_weightsLabel);
Controls.Add(_weights);
Controls.Add(_allowLoops);
Controls.Add(_allowParallelEdges);
Controls.Add(_uniqueEdgeWeights);
Controls.Add(_highQualityPrng);
Controls.Add(_status);
Controls.Add(_generate);
Controls.Add(_cancel);
Controls.Add(_close);
}
private EventHandler GetOpacitySetter(double opacity)
=> delegate { if (_translucent) Opacity = opacity; };
private void GraphGeneratorDialog_HandleCreated(object? sender,
EventArgs e)
{
AddMenuSeparator();
AddMenuItem(MyMenuItemId.KeepOnTop,
"&Keep on top\tAlt+K", @checked: false);
// "T" in "Alt+T" was cut off on the right. "\r" fixes this, somehow.
AddMenuItem(MyMenuItemId.Translucent,
$"&Translucent\tAlt+T\r", @checked: _translucent);
AddMenuItem(MyMenuItemId.StatusCaret,
"Stat&us caret\tF7", @checked: false);
AddMenuItem(MyMenuItemId.CopyStatusToClipboard,
"Copy status to clip&board\tCtrl+F7");
}
private void GraphGeneratorDialog_FormShown(object? sender, EventArgs e)
{
if (!_formShownBefore) {
_formShownBefore = true;
ReadState();
}
}
private void GraphGeneratorDialog_FormClosing(object sender,
WF.FormClosingEventArgs e)
{
if (e.CloseReason == WF.CloseReason.UserClosing) {
Hide();
e.Cancel = true;
}
}
private void GraphGeneratorDialog_KeyDown(object sender, WF.KeyEventArgs e)
{
switch (e) {
case { KeyCode: WF.Keys.K, Modifiers: WF.Keys.Alt }:
ToggleTopMost();
break;
case { KeyCode: WF.Keys.T, Modifiers: WF.Keys.Alt }:
ToggleTranslucence();
break;
case { KeyCode: WF.Keys.F7, Modifiers: WF.Keys.Control }:
CopyStatus();
break;
case { KeyCode: WF.Keys.F7 }:
ToggleStatusCaretPreference();
break;
default:
break;
}
}
private void status_GotFocus(object? sender, EventArgs e)
=> ApplyStatusCaretPreference();
// TODO: Maybe break up this method somehow.
private async void generate_Click(object? sender, EventArgs e)
{
ReadState(); // Use latest input even if it was given very strangely.
var generator = _generator;
if (generator == null || generator.Error != null) {
Warn("Bug? \"Generate\" button enabled with unusable parameters.");
return;
}
var sinks = _sinks;
if (sinks == null) {
Warn("Bug? \"Generate\" button enabled with no data sink.");
return;
}
_working = true;
KnobsEnabled = false;
_generate.Text = "Working...";
_generate.Enabled = false;
var (order, size, edges) = generator.Generate();
StatusWaiting($"Generating {order} vertices, {size} edges");
_cancel.Enabled = true;
try {
await Task.Run(() => {
Generating?.Invoke(this,
new GraphGeneratingEventArgs(order, size));
sinks(this, new GraphGeneratedEventArgs(order, size,
edges.ToList()));
});
} finally {
_cancel.Text = "Cancel";
_cancel.Enabled = false;
_generate.Text = "Generate";
KnobsEnabled = true;
_working = false;
ReadState();
}
}
private void cancel_Click(object? sender, EventArgs e)
{
_cancel.Text = "Cancelling...";
_cancel.Enabled = false;
// FIXME: implement the actual cancellation logic!
WF.MessageBox.Show(text: "Cancellation is not yet implemented. Sorry!",
caption: "Sorry!");
}
private void SetToolTip(WF.Control control, string text)
=> _toolTip.SetToolTip(control,
text.Replace("\n", Environment.NewLine));
private void SetToolTips(string text, params WF.Control[] controls)
=> Array.ForEach(controls, control => SetToolTip(control, text));
private void InvalidateGenerator(object? sender, EventArgs e)
{
if (_formShownBefore) ReadState();
}
private void ReadState()
{
const string intOrRange = "must be an integer (or range)";
const string rangeOrInt = "must be a range (or integer)";
if (_working ||
!(ReadClosedInterval(_order, _orderLabel, intOrRange)
is ClosedInterval orders
&& ReadClosedInterval(_size, _sizeLabel, intOrRange)
is ClosedInterval sizes
&& ReadClosedInterval(_weights, _weightsLabel, rangeOrInt)
is ClosedInterval weights)) {
_generator = null;
return;
}
_generator = new GraphGenerator(
orders: orders,
sizes: sizes,
weights: weights,
allowLoops: _allowLoops.Checked,
allowParallelEdges: _allowParallelEdges.Checked,
uniqueWeights: _uniqueEdgeWeights.Checked,
allowNegativeWeights: false,
prng: _highQualityPrng.Checked ? _goodPrng : _fastPrng);
if (_generator.Error != null)
StatusError(_generator.Error);
else if (_sinks == null)
StatusWaiting("Data sink busy/unavailable");
else
StatusOk();
}
private ClosedInterval? ReadClosedInterval(WF.TextBox textBox,
WF.Label label,
string requirement)
{
var input = textBox.Text;
if (ParseValue(input) is int value)
return new ClosedInterval(value, value);
if (ClosedInterval.Parse(input) is ClosedInterval interval)
return interval;
// FIXME: Interval notation with out-of-range numbers should also
// probably report errors like "... cannot exceed ...".
if (string.IsNullOrWhiteSpace(input))
StatusError($"{label.Text} not specified");
else if (!BigInteger.TryParse(input, out var bigValue))
StatusError($"{label.Text} {requirement}");
else if (bigValue.Sign == -1)
StatusError($"{label.Text} is a huge negative number!");
else
StatusError($"{label.Text} cannot exceed {int.MaxValue}");
return null;
}
private void StatusOk()
{
_status.ForeColor = Color.Green;
_status.Text = "OK";
SetStatusToolTip();
_generate.Enabled = true;
}
private void StatusWaiting(string message)
{
_status.ForeColor = Color.Brown;
_status.Text = message;
SetStatusToolTip();
_generate.Enabled = false;
}
private void StatusError(string message)
{
_status.ForeColor = Color.Red;
_status.Text = message;
SetStatusToolTip();
_generate.Enabled = false;
}
private void SetStatusToolTip()
=> SetToolTip(_status, $"status: {_status.Text}\n({StatusCaretHelp})");
private void ToggleTopMost()
{
TopMost = !TopMost;
SetMenuItemCheck(MyMenuItemId.KeepOnTop, TopMost);
}
private void ToggleTranslucence()
{
_translucent = !_translucent;
SetMenuItemCheck(MyMenuItemId.Translucent, _translucent);
if (_translucent) {
// Support even inactive translucence changes to avoid brittleness.
Opacity = (ActiveForm == this ? ActiveOpacity : InactiveOpacity);
} else {
Opacity = FullOpacity;
}
}
private void ToggleStatusCaretPreference()
{
_wantStatusCaret = !_wantStatusCaret;
SetMenuItemCheck(MyMenuItemId.StatusCaret, _wantStatusCaret);
SetStatusToolTip();
_status.Cursor = (_wantStatusCaret ? WF.Cursors.IBeam
: WF.Cursors.Arrow);
if (_status.ContainsFocus) ApplyStatusCaretPreference();
}
private void ApplyStatusCaretPreference()
{
if (_wantStatusCaret) {
if (!ShowCaret(_status.Handle))
Warn("Failure showing generator status caret");
} else {
if (!HideCaret(_status.Handle))
Warn("Failure hiding generator status caret");
}
}
private string StatusCaretHelp
=> _wantStatusCaret ? "Press F7 to disable caret."
: "Press F7 to enable caret.";
private void CopyStatus() => WF.Clipboard.SetText(_status.Text);
private IEnumerable<WF.Control> Knobs
{
get {
yield return _order;
yield return _size;
yield return _weights;
yield return _allowLoops;
yield return _allowParallelEdges;
yield return _uniqueEdgeWeights;
yield return _highQualityPrng;
}
}
private bool KnobsEnabled
{
set {
foreach (var control in Knobs) control.Enabled = value;
}
}
private static void Warn(string message)
=> message.Dump($"Warning ({nameof(GraphGeneratorDialog)})");
private void RunOrBeginInvoke(EventHandler method)
{
// TODO: Investigate if our use cases ever trigger the race condition.
if (IsHandleCreated)
BeginInvoke(method);
else
method(this, EventArgs.Empty);
}
private readonly WF.Label _orderLabel = new WF.Label {
Text = "Order",
Location = new Point(x: 5, y: 17),