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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
//! Module for implementing extcap config (also known as `arg`), which are UI
//! elements shown in Wireshark that allows the user to customize the capture.
//!
//! Each interface can have custom options that are valid for this interface
//! only. Those config options are specified on the command line when running
//! the actual capture.

use std::any::Any;
use std::fmt::Debug;
use std::ops::RangeInclusive;
use typed_builder::TypedBuilder;

pub use crate::{ExtcapFormatter, PrintSentence};

macro_rules! generate_config_ext {
    ($config_type:ty) => {
        impl ConfigTrait for $config_type {
            fn call(&self) -> &str {
                &self.call
            }

            fn as_any(&self) -> &dyn Any {
                self
            }
        }
    };
}

/// Defines a reload operation for [`SelectorConfig`].
pub struct Reload {
    /// The label for the reload button displayed next to the selector config.
    pub label: String,
    /// The reload function executed when the reload button is pressed. Note
    /// that this reload operation is run in a separate invocation of the
    /// program, meaning it should not rely on any in-memory state.
    pub reload_fn: fn() -> Vec<ConfigOptionValue>,
}

impl std::fmt::Debug for Reload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Reload(label={})", self.label)
    }
}

/// A selector config UI element that allows the user to select an option from a
/// drop-down list. The list of options should have default=true on exactly one
/// item.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let selector = SelectorConfig::builder()
///     .config_number(3)
///     .call("remote")
///     .display("Remote Channel")
///     .tooltip("Remote Channel Selector")
///     .default_options([
///         ConfigOptionValue::builder().value("if1").display("Remote1").default(true).build(),
///         ConfigOptionValue::builder().value("if2").display("Remote2").build(),
///     ])
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&selector)),
///     concat!(
///         "arg {number=3}{call=--remote}{display=Remote Channel}{tooltip=Remote Channel Selector}{type=selector}\n",
///         "value {arg=3}{value=if1}{display=Remote1}{default=true}\n",
///         "value {arg=3}{value=if2}{display=Remote2}{default=false}\n"
///     )
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct SelectorConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the selector.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// If this is `Some`, a refresh button will be shown next to the selector,
    /// allowing the user to refresh the list of available options to the return
    /// value of this function. The first element of the pair is the label of
    /// the button, and the second element is the function that will be invoked
    /// on click.
    ///
    /// Note: In extcap, the key for the button label is called `placeholder`,
    /// for some reason.
    #[builder(default, setter(strip_option))]
    pub reload: Option<Reload>,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
    /// The default list of options presented by this selector.
    #[builder(setter(into))]
    pub default_options: Vec<ConfigOptionValue>,
}

impl PrintSentence for SelectorConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        write!(f, "{{type=selector}}")?;
        if let Some(Reload { label, .. }) = &self.reload {
            write!(f, "{{reload=true}}")?;
            write!(f, "{{placeholder={label}}}")?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        writeln!(f)?;
        for opt in self.default_options.iter() {
            write!(f, "{}", ExtcapFormatter(&(opt, self.config_number)))?;
        }
        Ok(())
    }
}

generate_config_ext!(SelectorConfig);

/// A list of radio buttons for the user to choose one value from. The list of
/// options should have exactly one item with default=true.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let radio = RadioConfig::builder()
///     .config_number(3)
///     .call("remote")
///     .display("Remote Channel")
///     .tooltip("Remote Channel Selector")
///     .options([
///         ConfigOptionValue::builder().value("if1").display("Remote1").default(true).build(),
///         ConfigOptionValue::builder().value("if2").display("Remote2").build(),
///     ])
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&radio)),
///     concat!(
///         "arg {number=3}{call=--remote}{display=Remote Channel}{tooltip=Remote Channel Selector}{type=radio}\n",
///         "value {arg=3}{value=if1}{display=Remote1}{default=true}\n",
///         "value {arg=3}{value=if2}{display=Remote2}{default=false}\n"
///     )
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct RadioConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the radio button.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
    /// The default list of options presented by this config.
    #[builder(setter(into))]
    pub options: Vec<ConfigOptionValue>,
}

impl PrintSentence for RadioConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={}}}", group)?;
        }
        write!(f, "{{type=radio}}")?;
        writeln!(f)?;
        for opt in self.options.iter() {
            write!(f, "{}", ExtcapFormatter(&(opt, self.config_number)))?;
        }
        Ok(())
    }
}

generate_config_ext!(RadioConfig);

/// A tree of hierarchical check boxes that the user can select.
///
/// The values are passed comma-separated into the extcap command line. For
/// example, if the check boxes for `if1`, `if2a`, and `if2b` are checked in the
/// example below, then `--multi if1,if2a,if2b` will be passed in the command
/// line.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = MultiCheckConfig::builder()
///     .config_number(3)
///     .call("multi")
///     .display("Remote Channel")
///     .tooltip("Remote Channel Selector")
///     .options([
///         MultiCheckValue::builder().value("if1").display("Remote1").default_value(true).build(),
///         MultiCheckValue::builder().value("if2").display("Remote2").children([
///             MultiCheckValue::builder().value("if2a").display("Remote2A").default_value(true).build(),
///             MultiCheckValue::builder().value("if2b").display("Remote2B").default_value(true).build(),
///         ]).build(),
///     ])
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     concat!(
///         "arg {number=3}{call=--multi}{display=Remote Channel}{tooltip=Remote Channel Selector}{type=multicheck}\n",
///         "value {arg=3}{value=if1}{display=Remote1}{default=true}{enabled=true}\n",
///         "value {arg=3}{value=if2}{display=Remote2}{default=false}{enabled=true}\n",
///         "value {arg=3}{value=if2a}{display=Remote2A}{default=true}{enabled=true}{parent=if2}\n",
///         "value {arg=3}{value=if2b}{display=Remote2B}{default=true}{enabled=true}{parent=if2}\n"
///     )
/// );
/// ```
///
/// To parse those values as a `vec`, you can use the `value_delimiter` option
/// in `clap`.
///
/// ```ignore
/// #[arg(long, value_delimiter = ',')]
/// multi: Vec<String>,
/// ```
#[derive(Debug, TypedBuilder)]
pub struct MultiCheckConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the tree of checkboxes.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
    /// The default list of options presented by this config. This can be refreshed by the user using via the `reload` field.
    #[builder(setter(into))]
    pub options: Vec<MultiCheckValue>,
}

impl PrintSentence for MultiCheckConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={}}}", group)?;
        }
        write!(f, "{{type=multicheck}}")?;
        writeln!(f)?;
        for opt in self.options.iter() {
            write!(f, "{}", ExtcapFormatter(&(opt, self.config_number, None)))?;
        }
        Ok(())
    }
}

generate_config_ext!(MultiCheckConfig);

/// Represents a checkbox in a [`MultiCheckConfig`]. Each value is a checkbox in
/// the UI that can be nested into a hierarchy using the `children` field. See
/// the docs for [`MultiCheckConfig`] for usage details.
#[derive(Debug, Clone, TypedBuilder)]
pub struct MultiCheckValue {
    /// The value for this option, which is the value that will be passed to the
    /// extcap command line. For example, if `MultiCheckConfig.call` is `foo`,
    /// and this field is `bar`, then `--foo bar` will be passed to this extcap
    /// program during capturing.
    #[builder(setter(into))]
    pub value: String,
    /// The user-friendly label for this check box.
    #[builder(setter(into))]
    pub display: String,
    /// The default value for this check box, whether it is checked or not.
    #[builder(default = false)]
    pub default_value: bool,
    /// Whether this checkbox is enabled or not.
    #[builder(default = true)]
    pub enabled: bool,
    /// The list of children checkboxes. Children check boxes will be indented
    /// under this check box in the UI, but does not change how the value gets
    /// sent to the extcap program.
    #[builder(default, setter(into))]
    pub children: Vec<MultiCheckValue>,
}

impl PrintSentence for (&MultiCheckValue, u8, Option<&MultiCheckValue>) {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let (config, config_number, parent) = self;
        write!(f, "value {{arg={}}}", config_number)?;
        write!(f, "{{value={}}}", config.value)?;
        write!(f, "{{display={}}}", config.display)?;
        write!(f, "{{default={}}}", config.default_value)?;
        write!(f, "{{enabled={}}}", config.enabled)?;
        if let Some(parent) = parent {
            write!(f, "{{parent={}}}", parent.value)?;
        }
        writeln!(f)?;
        for c in config.children.iter() {
            write!(
                f,
                "{}",
                ExtcapFormatter(&(c, *config_number, Some(*config)))
            )?;
        }
        Ok(())
    }
}

/// This provides a field for entering a numeric value of the given data type. A
/// default value may be provided, as well as a range.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = LongConfig::builder()
///     .config_number(0)
///     .call("delay")
///     .display("Time delay")
///     .tooltip("Time delay between packages")
///     .range(-2..=15)
///     .default_value(0)
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=0}{call=--delay}{display=Time delay}{tooltip=Time delay between packages}{range=-2,15}{default=0}{type=long}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct LongConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the numeric field.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The valid range of values for this config.
    #[builder(default, setter(strip_option))]
    pub range: Option<RangeInclusive<i64>>,
    /// The default value for this config.
    pub default_value: i64,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
}

impl PrintSentence for LongConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(range) = &self.range {
            write!(f, "{{range={},{}}}", range.start(), range.end())?;
        }
        write!(f, "{{default={}}}", self.default_value)?;
        write!(f, "{{type=long}}")?;
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(LongConfig);

/// This provides a field for entering a numeric value of the given data type. A
/// default value may be provided, as well as a range.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = IntegerConfig::builder()
///     .config_number(0)
///     .call("delay")
///     .display("Time delay")
///     .tooltip("Time delay between packages")
///     .range(-10..=15)
///     .default_value(0)
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=0}{call=--delay}{display=Time delay}{tooltip=Time delay between packages}{range=-10,15}{default=0}{type=integer}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct IntegerConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the numeric field.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The valid range of values for this config.
    #[builder(default, setter(strip_option))]
    pub range: Option<RangeInclusive<i32>>,
    /// The default value for this config.
    pub default_value: i32,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
}

impl PrintSentence for IntegerConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(range) = &self.range {
            write!(f, "{{range={},{}}}", range.start(), range.end())?;
        }
        write!(f, "{{default={}}}", self.default_value)?;
        write!(f, "{{type=integer}}")?;
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(IntegerConfig);

/// This provides a field for entering a numeric value of the given data type. A
/// default value may be provided, as well as a range.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = UnsignedConfig::builder()
///     .config_number(0)
///     .call("delay")
///     .display("Time delay")
///     .tooltip("Time delay between packages")
///     .range(1..=15)
///     .default_value(0)
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=0}{call=--delay}{display=Time delay}{tooltip=Time delay between packages}{range=1,15}{default=0}{type=unsigned}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct UnsignedConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the numeric field.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The valid range of values for this config.
    #[builder(default, setter(strip_option, into))]
    pub range: Option<RangeInclusive<u32>>,
    /// The default value for this config.
    pub default_value: u32,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
}

impl PrintSentence for UnsignedConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(range) = &self.range {
            write!(f, "{{range={},{}}}", range.start(), range.end())?;
        }
        write!(f, "{{default={}}}", self.default_value)?;
        write!(f, "{{type=unsigned}}")?;
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(UnsignedConfig);

/// This provides a field for entering a numeric value of the given data type. A
/// default value may be provided, as well as a range.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = DoubleConfig::builder()
///     .config_number(0)
///     .call("delay")
///     .display("Time delay")
///     .tooltip("Time delay between packages")
///     .range(-2.6..=8.2)
///     .default_value(3.3)
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=0}{call=--delay}{display=Time delay}{tooltip=Time delay between packages}{range=-2.6,8.2}{default=3.3}{type=double}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct DoubleConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the numeric field.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The valid range of values for this config.
    #[builder(default, setter(strip_option))]
    pub range: Option<RangeInclusive<f64>>,
    /// The default value for this config.
    pub default_value: f64,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
}

impl PrintSentence for DoubleConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(range) = &self.range {
            write!(f, "{{range={},{}}}", range.start(), range.end())?;
        }
        write!(f, "{{default={}}}", self.default_value)?;
        write!(f, "{{type=double}}")?;
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(DoubleConfig);

/// A field for entering a text value.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = StringConfig::builder()
///     .config_number(1)
///     .call("server")
///     .display("IP Address")
///     .tooltip("IP Address for log server")
///     .validation(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     concat!(
///         r"arg {number=1}{call=--server}{display=IP Address}{tooltip=IP Address for log server}{validation=\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b}{type=string}",
///         "\n"
///     )
/// );
/// ```
#[allow(deprecated)]
#[derive(Debug, TypedBuilder)]
pub struct StringConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the text field.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The placeholder string displayed if there is no value in the text field.
    #[builder(default, setter(strip_option, into))]
    pub placeholder: Option<String>,
    /// Whether a value is required for this config.
    #[builder(default = false)]
    pub required: bool,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
    /// A regular expression string used to check the user input for validity.
    /// Despite what the Wireshark documentation says, back-slashes in this
    /// string do not need to be escaped. Just remember to use a Rust raw string
    /// (e.g. `r"\d\d\d\d"`).
    #[builder(default, setter(strip_option, into))]
    pub validation: Option<String>,
    /// Whether to save the value of this config. If true, the value will be
    /// saved by Wireshark, and will be automatically populated next time that
    /// interface is selected by the user.
    ///
    /// Note: This option is undocumented in the Wireshark documentation, but
    /// the functionality was added in
    /// <https://gitlab.com/wireshark/wireshark/-/commit/97a1a50e200a6c50e0014dde7e8ec932c30190a1>.
    ///
    /// It does not behave correctly in some versions of Wireshark, with the
    /// same symptoms described in
    /// <https://gitlab.com/wireshark/wireshark/-/issues/18487>.
    #[builder(default = true)]
    pub save: bool,
}

impl PrintSentence for StringConfig {
    #[allow(deprecated)]
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(placeholder) = &self.placeholder {
            write!(f, "{{placeholder={}}}", placeholder)?;
        }
        if self.required {
            write!(f, "{{required=true}}")?;
        }
        if let Some(validation) = &self.validation {
            write!(f, "{{validation={}}}", validation)?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        if !self.save {
            write!(f, "{{save=false}}")?;
        }
        write!(f, "{{type=string}}")?;
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(StringConfig);

/// A field for entering text value, but with its value masked in the user
/// interface. The value of a password field is not saved by Wireshark.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = PasswordConfig::builder()
///     .config_number(0)
///     .call("password")
///     .display("The user password")
///     .tooltip("The password for the connection")
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=0}{call=--password}{display=The user password}{tooltip=The password for the connection}{type=password}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct PasswordConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the password field.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The placeholder string displayed if there is no value in the text field.
    #[builder(default, setter(strip_option, into))]
    pub placeholder: Option<String>,
    /// Whether a value is required for this config.
    #[builder(default = false)]
    pub required: bool,
    /// A regular expression string used to check the user input for validity.
    /// Despite what the Wireshark documentation says, back-slashes in this
    /// string do not need to be escaped. Just remember to use a Rust raw string
    /// (e.g. `r"\d\d\d\d"`).
    #[builder(default, setter(strip_option, into))]
    pub validation: Option<String>,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
}

impl PrintSentence for PasswordConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(placeholder) = &self.placeholder {
            write!(f, "{{placeholder={}}}", placeholder)?;
        }
        if self.required {
            write!(f, "{{required=true}}")?;
        }
        if let Some(validation) = &self.validation {
            write!(f, "{{validation={}}}", validation)?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        write!(f, "{{type=password}}")?;
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(PasswordConfig);

/// A config that is displayed as a date/time editor.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = TimestampConfig::builder()
///     .config_number(9)
///     .call("ts")
///     .display("Start Time")
///     .tooltip("Capture start time")
///     .group("Time / Log")
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=9}{call=--ts}{display=Start Time}{tooltip=Capture start time}{group=Time / Log}{type=timestamp}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct TimestampConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the config.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
}

impl PrintSentence for TimestampConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        write!(f, "{{type=timestamp}}")?;
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(TimestampConfig);

/// Lets the user provide a file path.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = FileSelectConfig::builder()
///     .config_number(3)
///     .call("logfile")
///     .display("Logfile")
///     .tooltip("A file for log messages")
///     .must_exist(false)
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=3}{call=--logfile}{display=Logfile}{tooltip=A file for log messages}{type=fileselect}{mustexist=false}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct FileSelectConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the file selector.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
    /// If true is provided, the GUI shows the user a dialog for selecting an
    /// existing file. If false, the GUI shows a file dialog for saving a file.
    #[builder(default = true)]
    pub must_exist: bool,
    /// If set, provide a filter for the file extension selectable by this
    /// config. The format of the filter string is the same as qt's
    /// [`QFileDialog`](https://doc.qt.io/qt-6/qfiledialog.html).
    ///
    /// For example, the filter `Text files (*.txt);;XML files (*.xml)` will
    /// limit to `.txt` and `.xml` files:
    ///
    /// If `None`, any file can be selected (equivalent to `All Files (*)`).
    ///
    /// This feature is currnetly not documented in the Wireshark docs, but a
    /// high level detail can be found in this commit:
    /// <https://gitlab.com/wireshark/wireshark/-/commit/0d47113ddc53714ecd6d3c1b58b694321649d89e>
    #[builder(default, setter(into, strip_option))]
    pub file_extension_filter: Option<String>,
}

impl PrintSentence for FileSelectConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        write!(f, "{{type=fileselect}}")?;
        write!(f, "{{mustexist={}}}", self.must_exist)?;
        if let Some(file_extension_filter) = &self.file_extension_filter {
            write!(f, "{{fileext={}}}", file_extension_filter)?;
        }
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(FileSelectConfig);

/// A checkbox configuration with a true/false value.
///
/// Typically, these configs are created in a `lazy_static`, and passed to
/// [`ConfigStep::list_configs`][crate::ConfigStep::list_configs].
///
/// ## Example
/// ```
/// use r_extcap::config::*;
///
/// let config = BooleanConfig::builder()
///     .config_number(2)
///     .call("verify")
///     .display("Verify")
///     .tooltip("Verify package content")
///     .build();
/// assert_eq!(
///     format!("{}", ExtcapFormatter(&config)),
///     "arg {number=2}{call=--verify}{display=Verify}{tooltip=Verify package content}{type=boolflag}\n"
/// );
/// ```
#[derive(Debug, TypedBuilder)]
pub struct BooleanConfig {
    /// The config number, a unique identifier for this config.
    pub config_number: u8,
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    #[builder(setter(into))]
    pub call: String,
    /// The user-friendly label for the check box.
    #[builder(setter(into))]
    pub display: String,
    /// The tooltip shown on when hovering over the UI element.
    #[builder(default, setter(strip_option, into))]
    pub tooltip: Option<String>,
    /// The default value for this config.
    #[builder(default = false)]
    pub default_value: bool,
    /// The (user-visible) name of the tab which this config belongs to. If this
    /// is `None`, the config will be placed in a tab called "Default".
    #[builder(default, setter(strip_option, into))]
    pub group: Option<String>,
    /// If true, always include the command line flag (e.g. either `--foo true`
    /// or `--foo false`). If false (the default), the flag is provided to the
    /// command without a value if this is checked (`--foo`), or omitted from
    /// the command line arguments if unchecked.
    #[builder(default = false)]
    pub always_include_option: bool,
}

impl PrintSentence for BooleanConfig {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "arg {{number={}}}", self.config_number)?;
        write!(f, "{{call=--{}}}", self.call)?;
        write!(f, "{{display={}}}", self.display)?;
        if let Some(tooltip) = &self.tooltip {
            write!(f, "{{tooltip={tooltip}}}")?;
        }
        if self.default_value {
            write!(f, "{{default=true}}")?;
        }
        if self.always_include_option {
            write!(f, "{{type=boolean}}")?;
        } else {
            write!(f, "{{type=boolflag}}")?;
        }
        if let Some(group) = &self.group {
            write!(f, "{{group={group}}}")?;
        }
        writeln!(f)?;
        Ok(())
    }
}

generate_config_ext!(BooleanConfig);

/// An option for [`SelectorConfig`] and [`RadioConfig`].
#[derive(Clone, Debug, TypedBuilder)]
pub struct ConfigOptionValue {
    /// The value of this option. If this option is selected, the value will be
    /// passed to the command line. For example, if [`SelectorConfig.call`] is
    /// `foo`, and this field is `bar`, then `--foo bar` will be passed to this
    /// extcap program.
    #[builder(setter(into))]
    value: String,
    /// The user-friendly label for this option.
    #[builder(setter(into))]
    display: String,
    /// Whether this option is selected as the default. For each config there
    /// should only be one selected default.
    #[builder(default = false)]
    default: bool,
}

impl ConfigOptionValue {
    /// Prints out the extcap sentence to stdout for Wireshark's consumption.
    pub fn print_sentence(&self, number: u8) {
        (self, number).print_sentence()
    }
}

impl PrintSentence for (&ConfigOptionValue, u8) {
    fn format_sentence(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let (config, arg_number) = self;
        write!(f, "value {{arg={}}}", arg_number)?;
        write!(f, "{{value={}}}", config.value)?;
        write!(f, "{{display={}}}", config.display)?;
        write!(f, "{{default={}}}", config.default)?;
        writeln!(f)?;
        Ok(())
    }
}

/// Represents a config, also known as `arg` in an extcap sentence`, which is a
/// UI element shown in Wireshark that allows the user to customize the capture.
pub trait ConfigTrait: PrintSentence + Any {
    /// The command line option that will be sent to this extcap program. For
    /// example, if this field is `foobar`, and the corresponding value is `42`,
    /// then `--foobar 42` will be sent to this program during the extcap
    /// capture.
    fn call(&self) -> &str;

    /// Returns this trait as an `Any` type.
    fn as_any(&self) -> &dyn Any;
}