File: prefsdlg.cpp

package info (click to toggle)
poedit 3.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,592 kB
  • sloc: cpp: 64,977; sh: 4,404; makefile: 241; xml: 46
file content (1230 lines) | stat: -rw-r--r-- 46,974 bytes parent folder | download
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
/*
 *  This file is part of Poedit (https://poedit.net)
 *
 *  Copyright (C) 2000-2026 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "prefsdlg.h"

#include <fstream>
#include <memory>

#include <wx/editlbox.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/config.h>
#include <wx/choicdlg.h>
#include <wx/checkbox.h>
#include <wx/choice.h>
#include <wx/checklst.h>
#include <wx/notebook.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/fontutil.h>
#include <wx/fontpicker.h>
#include <wx/filename.h>
#include <wx/filedlg.h>
#include <wx/windowptr.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/spinctrl.h>
#include <wx/textwrapper.h>
#include <wx/progdlg.h>
#include <wx/xrc/xmlres.h>
#include <wx/numformatter.h>

#ifdef __WXOSX__
    #include <wx/private/bmpbndl.h>
#endif

#include "app_updates.h"
#include "edapp.h"
#include "edframe.h"
#include "catalog.h"
#include "cloud_accounts_ui.h"
#include "colorscheme.h"
#include "configuration.h"
#include "crowdin_gui.h"
#include "hidpi.h"
#include "menus.h"
#include "tm/transmem.h"
#include "tm/tmx_io.h"
#include "uilang.h"
#include "errors.h"
#include "extractors/extractor_legacy.h"
#include "progress_ui.h"
#include "spellchecking.h"
#include "str_helpers.h"
#include "utility.h"
#include "customcontrols.h"
#include "layout_helpers.h"
#include "unicode_helpers.h"

namespace
{

#ifdef __WXOSX__
inline wxBitmapBundle MacPageIcon(const char *symbol)
{
    return wxOSXMakeBundleFromImage([NSImage imageWithSystemSymbolName:str::to_NS(symbol) accessibilityDescription:nil]);
}
#else
inline wxBitmap MacPageIcon(const char*) { return wxNullBitmap; }
#endif


class PrefsPanel : public WindowWith2DSizingConstraints<StandardLayout<wxPanel>>
{
public:
    PrefsPanel(wxWindow *parent)
        : WindowWith2DSizingConstraints<StandardLayout<wxPanel>>(parent), m_suppressDataTransfer(0)
    {
#ifdef __WXOSX__
        // Refresh the content of prefs panels when re-opening it.
        // TODO: Use proper config settings notifications or user defaults bindings instead
        parent->Bind(wxEVT_ACTIVATE, [=](wxActivateEvent& e){
            e.Skip();
            if (e.GetActive())
                TransferDataToWindow();
        });
        Bind(wxEVT_SHOW, [=](wxShowEvent& e){
            e.Skip();
            if (e.IsShown())
                TransferDataToWindow();
        });
#endif // __WXOSX__
    }

    bool TransferDataToWindow() override
    {
        if (m_suppressDataTransfer)
            return false;
        m_suppressDataTransfer++;
        InitValues(*wxConfig::Get());
        m_suppressDataTransfer--;

        // This is a "bit" of a hack: we take advantage of being in the last point before
        // showing the window and re-layout it on the off chance that some data transferred
        // into the window affected its size. And, currently more importantly, to reflect
        // ExplanationLabel instances' rewrapping.
        Fit();
#ifndef __WXOSX__
        GetParent()->GetParent()->Fit();
#endif
        return true;
    }

    bool TransferDataFromWindow() override
    {
        if (m_suppressDataTransfer)
            return false;
        m_suppressDataTransfer++;
        SaveValues(*wxConfig::Get());
        m_suppressDataTransfer--;
        return true;
    }

protected:
    void TransferDataFromWindowAndUpdateUI(wxCommandEvent&)
    {
        TransferDataFromWindow();
        PoeditFrame::UpdateAllAfterPreferencesChange();
    }

    virtual void InitValues(const wxConfigBase& cfg) = 0;
    virtual void SaveValues(wxConfigBase& cfg) = 0;

    int m_suppressDataTransfer;
};



class GeneralPageWindow : public PrefsPanel
{
public:
    GeneralPageWindow(wxWindow *parent) : PrefsPanel(parent)
    {
        auto sizer = ContentSizer();
        sizer->SetMinSize(PX(400), -1);

        sizer->Add(new HeadingLabel(this, _("Information about the translator")));
        sizer->AddSpacer(PX(10));

        auto translator = new wxFlexGridSizer(2, wxSize(5,6));
        translator->AddGrowableCol(1);
        sizer->Add(translator, wxSizerFlags().Expand());

        auto nameLabel = new wxStaticText(this, wxID_ANY, _("Name:"));
        translator->Add(nameLabel, wxSizerFlags().CenterVertical().Right().BORDER_MACOS(wxTOP, 1));
        m_userName = new wxTextCtrl(this, wxID_ANY);
        m_userName->SetHint(_("Your Name"));
        translator->Add(m_userName, wxSizerFlags(1).Expand().CenterVertical());
        auto emailLabel = new wxStaticText(this, wxID_ANY, _("Email:"));
        translator->Add(emailLabel, wxSizerFlags().CenterVertical().Right().BORDER_MACOS(wxTOP, 1));
        m_userEmail = new wxTextCtrl(this, wxID_ANY);
        m_userEmail->SetHint(_("you@example.com"));
        translator->Add(m_userEmail, wxSizerFlags(1).Expand().CenterVertical());
        translator->AddSpacer(PX(1));
        translator->Add(new ExplanationLabel(this, _("Your name and email address are only used to set the Last-Translator header of GNU gettext files.")), wxSizerFlags(1).Expand().PXBorder(wxRIGHT));
#ifdef __WXOSX__
        nameLabel->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
        emailLabel->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
        m_userName->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
        m_userEmail->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif

        sizer->AddSpacer(PX(10));
        sizer->Add(new HeadingLabel(this, _("Editing")));
        sizer->AddSpacer(PX(10));

        m_compileMo = new wxCheckBox(this, wxID_ANY, _("Automatically compile MO file when saving"));
        sizer->Add(m_compileMo);

        sizer->AddSpacer(PX(10));

        m_spellchecking = new wxCheckBox(this, wxID_ANY, _("Check spelling"));
        sizer->Add(m_spellchecking, wxSizerFlags().PXBorder(wxTOP));
        m_focusToText = new wxCheckBox(this, wxID_ANY, _("Always change focus to text input field"));
        sizer->Add(m_focusToText, wxSizerFlags().PXBorder(wxTOP));
        wxString explainFocus(_("Never let the list of strings take focus. If enabled, you must use Ctrl-arrows for keyboard navigation but you can also type text immediately, without having to press Tab to change focus."));
#ifdef __WXOSX__
        explainFocus.Replace("Ctrl", "Cmd");
#endif
        sizer->AddSpacer(PX(5));
        sizer->Add(new ExplanationLabel(this, explainFocus), wxSizerFlags().Expand().Border(wxLEFT, UnderCheckboxIndent()));

        sizer->AddSpacer(PX(10));
        sizer->Add(new HeadingLabel(this, _("Appearance")));
        sizer->AddSpacer(PX(4));

        auto appearance = new wxFlexGridSizer(2, wxSize(5,1));
        appearance->AddGrowableCol(1);
        sizer->Add(appearance, wxSizerFlags().Expand());

        m_useFontList = new wxCheckBox(this, wxID_ANY, _("Use custom list font:"));
        m_fontList = new wxFontPickerCtrl(this, wxID_ANY);
        m_fontList->SetMinSize(wxSize(PX(120), -1));
        m_useFontText = new wxCheckBox(this, wxID_ANY, _("Use custom text fields font:"));
        m_fontText = new wxFontPickerCtrl(this, wxID_ANY);
        m_fontText->SetMinSize(wxSize(PX(120), -1));

        appearance->Add(m_useFontList, wxSizerFlags().CenterVertical().Left());
        appearance->Add(m_fontList, wxSizerFlags().CenterVertical().Expand());
        appearance->Add(m_useFontText, wxSizerFlags().CenterVertical().Left());
        appearance->Add(m_fontText, wxSizerFlags().CenterVertical().Expand());

#if NEED_CHOOSELANG_UI 
        m_uiLanguage = new wxButton(this, wxID_ANY, _("Change UI language"));
        sizer->Add(m_uiLanguage, wxSizerFlags().PXBorder(wxTOP));
#endif

#ifdef __WXMSW__
        if (!IsSpellcheckingAvailable())
        {
            m_spellchecking->Disable();
            m_spellchecking->SetValue(false);
            // TRANSLATORS: This is a note appended to "Check spelling" when running on older Windows versions
            m_spellchecking->SetLabel(m_spellchecking->GetLabel() + " " + _("(requires Windows 8 or newer)"));
        }
#endif

        Fit();

        if (wxPreferencesEditor::ShouldApplyChangesImmediately())
        {
            Bind(wxEVT_CHECKBOX, [=](wxCommandEvent&){ TransferDataFromWindow(); });
            Bind(wxEVT_TEXT, [=](wxCommandEvent&){ TransferDataFromWindow(); });

            // Some settings directly affect the UI, so need a more expensive handler:
            m_useFontList->Bind(wxEVT_CHECKBOX, &GeneralPageWindow::TransferDataFromWindowAndUpdateUI, this);
            m_useFontText->Bind(wxEVT_CHECKBOX, &GeneralPageWindow::TransferDataFromWindowAndUpdateUI, this);
            Bind(wxEVT_FONTPICKER_CHANGED, &GeneralPageWindow::TransferDataFromWindowAndUpdateUI, this);
            m_focusToText->Bind(wxEVT_CHECKBOX, &GeneralPageWindow::TransferDataFromWindowAndUpdateUI, this);
            m_spellchecking->Bind(wxEVT_CHECKBOX, &GeneralPageWindow::TransferDataFromWindowAndUpdateUI, this);
        }

        // handle UI updates:
        m_fontList->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e){ e.Enable(m_useFontList->GetValue()); });
        m_fontText->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e){ e.Enable(m_useFontText->GetValue()); });

#if NEED_CHOOSELANG_UI
        m_uiLanguage->Bind(wxEVT_BUTTON, [=](wxCommandEvent&){ ChangeUILanguage(); });
#endif
    }

    void InitValues(const wxConfigBase& cfg) override
    {
        m_userName->SetValue(cfg.Read("translator_name", wxEmptyString));
        m_userEmail->SetValue(cfg.Read("translator_email", wxEmptyString));
        m_compileMo->SetValue(cfg.ReadBool("compile_mo", true));
        m_focusToText->SetValue(cfg.ReadBool("focus_to_text", false));

        if (IsSpellcheckingAvailable())
        {
            m_spellchecking->SetValue(cfg.ReadBool("enable_spellchecking", true));
        }

        m_useFontList->SetValue(cfg.ReadBool("custom_font_list_use", false));
        m_useFontText->SetValue(cfg.ReadBool("custom_font_text_use", false));

        #if defined(__WXOSX__)
            #define DEFAULT_FONT "Helvetica Neue"
        #elif defined(__WXMSW__)
            #define DEFAULT_FONT "Arial"
        #elif defined(__WXGTK__)
            #define DEFAULT_FONT "sans serif"
        #endif
        auto listFont = wxFont(cfg.Read("custom_font_list_name", ""));
        if (!listFont.IsOk())
            listFont = wxFont(11, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, DEFAULT_FONT);
        auto textFont = wxFont(cfg.Read("custom_font_text_name", ""));
        if (!textFont.IsOk())
            textFont = wxFont(11, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, DEFAULT_FONT);
        m_fontList->SetSelectedFont(listFont);
        m_fontText->SetSelectedFont(textFont);
    }

    void SaveValues(wxConfigBase& cfg) override
    {
        cfg.Write("translator_name", m_userName->GetValue());
        cfg.Write("translator_email", m_userEmail->GetValue());
        cfg.Write("compile_mo", m_compileMo->GetValue());
        cfg.Write("focus_to_text", m_focusToText->GetValue());

        if (IsSpellcheckingAvailable())
        {
            cfg.Write("enable_spellchecking", m_spellchecking->GetValue());
        }
       
        wxFont listFont = m_fontList->GetSelectedFont();
        wxFont textFont = m_fontText->GetSelectedFont();

        cfg.Write("custom_font_list_use", m_useFontList->GetValue());
        cfg.Write("custom_font_text_use", m_useFontText->GetValue());
        if ( listFont.IsOk() )
            cfg.Write("custom_font_list_name", listFont.GetNativeFontInfoDesc());
        if ( textFont.IsOk() )
            cfg.Write("custom_font_text_name", textFont.GetNativeFontInfoDesc());

        // On Windows, we must update the UI here; on other platforms, it was done
        // via TransferDataFromWindowAndUpdateUI immediately:
        if (!wxPreferencesEditor::ShouldApplyChangesImmediately())
        {
            PoeditFrame::UpdateAllAfterPreferencesChange();
        }
    }

private:
    wxTextCtrl *m_userName, *m_userEmail;
    wxCheckBox *m_compileMo, *m_focusToText, *m_spellchecking;
    wxCheckBox *m_useFontList, *m_useFontText;
    wxFontPickerCtrl *m_fontList, *m_fontText;
#if NEED_CHOOSELANG_UI
    wxButton *m_uiLanguage;
#endif
};

class GeneralPage : public wxPreferencesPage
{
public:
    wxString GetName() const override { return _("General"); }
    wxBitmapBundle GetIcon() const override { return MacPageIcon("gearshape"); }
    wxWindow *CreateWindow(wxWindow *parent) override { return new GeneralPageWindow(parent); }
};



class TMPageWindow : public PrefsPanel
{
public:
    TMPageWindow(wxWindow *parent) : PrefsPanel(parent)
    {
        auto sizer = ContentSizer();
#ifdef __WXOSX__
        sizer->SetMinSize(PX(430), -1); // for macOS look
#endif

        m_useTM = new wxCheckBox(this, wxID_ANY, _("Use translation memory"));
        sizer->Add(m_useTM, wxSizerFlags().Expand());

        m_stats = new wxStaticText(this, wxID_ANY, "--\n--", wxDefaultPosition, wxDefaultSize, wxST_NO_AUTORESIZE);
        sizer->AddSpacer(PX(10));
        sizer->Add(m_stats, wxSizerFlags().Expand().Border(wxLEFT|wxRIGHT, PX(30)));
        sizer->AddSpacer(PX(10));

        auto buttonsSizer = new wxBoxSizer(wxHORIZONTAL);

        auto manage = new wxButton(this, wxID_ANY, _(L"Manage…"));
        buttonsSizer->Add(manage, wxSizerFlags());

        sizer->Add(buttonsSizer, wxSizerFlags().Expand().Border(wxLEFT|wxRIGHT, PX(30)));
        sizer->AddSpacer(PX(10));

        // TRANSLATORS: Followed by "match translations within the file" or "pre-translate from TM"
        m_mergeUse = new wxCheckBox(this, wxID_ANY, _("When updating from sources"));
        wxString mergeValues[] = {
            // TRANSLATORS: Preceded by "When updating from sources"
            _("fuzzy match within the file"),
            // TRANSLATORS: Preceded by "When updating from sources"
            _("pre-translate from TM")
        };
        m_mergeBehavior = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, WXSIZEOF(mergeValues), mergeValues);

        auto mergeSizer = new wxBoxSizer(wxHORIZONTAL);
        mergeSizer->Add(m_mergeUse, wxSizerFlags().Center());
        mergeSizer->AddSpacer(PX(5));
        mergeSizer->Add(m_mergeBehavior, wxSizerFlags().Center()
                    #ifdef __WXOSX__ // BORDER_WIN would reset this padding otherwise
                        .Border(wxTOP, AboveChoicePadding())
                    #else
                        .BORDER_WIN(wxBOTTOM, 1)
                    #endif
                    );
        sizer->Add(mergeSizer, wxSizerFlags().PXBorder(wxTOP|wxBOTTOM));

        auto explainTxt = _(L"Poedit can attempt to fill in new entries from only previous translations in the file or from your entire translation memory. Using the TM won’t be very effective if it’s near-empty, but it will get better as you add more translations to it.");
        auto explain = new ExplanationLabel(this, explainTxt);
        sizer->Add(explain, wxSizerFlags().Expand().Border(wxLEFT, UnderCheckboxIndent()));

        auto learnMore = new LearnMoreLink(this, "https://poedit.net/help/translation-memory");
        sizer->AddSpacer(PX(3));
        sizer->Add(learnMore, wxSizerFlags().Border(wxLEFT, UnderCheckboxIndent()));

#ifdef __WXOSX__
        m_stats->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
        manage->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif

        m_mergeBehavior->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e){ e.Enable(m_mergeUse->GetValue() == true); });

        m_stats->Bind(wxEVT_UPDATE_UI, &TMPageWindow::OnUpdateUI, this);
        manage->Bind(wxEVT_UPDATE_UI, &TMPageWindow::OnUpdateUI, this);

        manage->Bind(wxEVT_BUTTON, &TMPageWindow::OnManageTM, this);

        UpdateStats();

        if (wxPreferencesEditor::ShouldApplyChangesImmediately())
        {
            m_mergeUse->Bind(wxEVT_CHECKBOX, [=](wxCommandEvent&){ TransferDataFromWindow(); });
            m_mergeBehavior->Bind(wxEVT_CHOICE, [=](wxCommandEvent&){ TransferDataFromWindow(); });
            // Some settings directly affect the UI, so need a more expensive handler:
            m_useTM->Bind(wxEVT_CHECKBOX, &TMPageWindow::TransferDataFromWindowAndUpdateUI, this);
        }
    }

    void InitValues(const wxConfigBase&) override
    {
        m_useTM->SetValue(Config::UseTM());
        auto merge = Config::MergeBehavior();
        m_mergeUse->SetValue(merge != Merge_None);
        m_mergeBehavior->SetSelection(merge == Merge_UseTM ? 1 : 0);
    }

    void SaveValues(wxConfigBase&) override
    {
        Config::UseTM(m_useTM->GetValue());
        if (m_mergeUse->GetValue() == true)
        {
            Config::MergeBehavior(m_mergeBehavior->GetSelection() == 1 ? Merge_UseTM : Merge_FuzzyMatch);
        }
        else
        {
            Config::MergeBehavior(Merge_None);
        }
    }

private:
    void UpdateStats()
    {
        wxString sDocs("--");
        wxString sFileSize("--");
        if (Config::UseTM())
        {
            try
            {
                long docs, fileSize;
                TranslationMemory::Get().GetStats(docs, fileSize);
                sDocs.Printf("<b>%s</b>", wxNumberFormatter::ToString(docs));
                sFileSize.Printf("<b>%s</b>", wxFileName::GetHumanReadableSize(fileSize, "--", 1, wxSIZE_CONV_SI));
            }
            catch (Exception&)
            {
                // ignore Lucene errors -- if the index doesn't exist yet, just show --
            }
        }

        m_stats->SetLabelMarkup(wxString::Format(
            "%s %s\n%s %s",
            _("Stored translations:"),      sDocs,
            _("Database size on disk:"),    sFileSize
        ));
    }

    void OnManageTM(wxCommandEvent& e)
    {
        static wxWindowIDRef idLearn = NewControlId();
        static wxWindowIDRef idImportTMX = NewControlId();
        static wxWindowIDRef idExportTMX = NewControlId();
        static wxWindowIDRef idReset = NewControlId();

        wxMenu menu;
#ifdef __WXOSX__
        [menu.GetHMenu() setFont:[NSFont systemFontOfSize:13]];
#endif
        auto itemLearn = menu.Append(idLearn, MSW_OR_OTHER(_(L"Import translation files…"), _(L"Import Translation Files…")));
        menu.AppendSeparator();
        auto itemImport = menu.Append(idImportTMX, MSW_OR_OTHER(_(L"Import from TMX…"), _(L"Import From TMX…")));
        auto itemExport = menu.Append(idExportTMX, MSW_OR_OTHER(_(L"Export to TMX…"), _(L"Export To TMX…")));
        menu.AppendSeparator();
        // TRANSLATORS: This is a button that deletes everything in the translation memory (i.e. clears/resets it).
        auto itemEraseDB = menu.Append(idReset, MSW_OR_OTHER(_(L"Erase database…"), _(L"Erase Database…")));

        SetMacMenuIcon(itemLearn, "document.on.document");
        SetMacMenuIcon(itemImport, "arrow.down.document");
        SetMacMenuIcon(itemExport, "arrow.up.document");
        SetMacMenuIcon(itemEraseDB, "trash");

        menu.Bind(wxEVT_MENU, &TMPageWindow::OnImportIntoTM, this, idLearn);
        menu.Bind(wxEVT_MENU, &TMPageWindow::OnImportTMX, this, idImportTMX);
        menu.Bind(wxEVT_MENU, &TMPageWindow::OnExportTMX, this, idExportTMX);
        menu.Bind(wxEVT_MENU, &TMPageWindow::OnResetTM, this, idReset);

        auto win = dynamic_cast<wxButton*>(e.GetEventObject());
#ifdef __WXOSX__
        win->PopupMenu(&menu, 5, 26);
#else
        win->PopupMenu(&menu, 0, win->GetSize().y);
#endif
    }

    void OnImportIntoTM(wxCommandEvent&)
    {
        wxWindowPtr<wxFileDialog> dlg(new wxFileDialog(
            this,
            _("Select translation files to import"),
            wxEmptyString,
            wxEmptyString,
            Catalog::GetAllTypesFileMask(),
            wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE));

        // dlg->ShowWindowModalThenDo([=](int retcode){
        int retcode = dlg->ShowModal();
        {
            if (retcode != wxID_OK)
                return;

            wxArrayString paths;
            dlg->GetPaths(paths);

            auto tm = TranslationMemory::Get().GetWriter();

            DoImportIntoTM(paths, [=](const wxString& p)
            {
                Progress subprogress(1);
                auto cat = Catalog::Create(p);
                tm->Insert(cat);
                tm->Commit();
                return cat->GetCount();
            });
        }
    }

    void OnImportTMX(wxCommandEvent&)
    {
        wxWindowPtr<wxFileDialog> dlg(new wxFileDialog
        (
            this,
            MACOS_OR_OTHER("", _("Select TMX files to import")),
            "",
            "",
            MaskForType("*.tmx", _("TMX Files")),
            wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE)
        );

        // dlg->ShowWindowModalThenDo([=](int retcode){
        int retcode = dlg->ShowModal();
        {
            if (retcode != wxID_OK)
                return;

            wxArrayString paths;
            dlg->GetPaths(paths);
            DoImportIntoTM(paths, [=](const wxString& p)
            {
                std::ifstream f;
                f.open(p.fn_str());
                int count = TMX::ImportFromFile(f, TranslationMemory::Get());
                f.close();
                return count;
            });
        }
    }

    template<typename T>
    void DoImportIntoTM(const wxArrayString& paths, T&& doImportFile)
    {
        auto cancellation = std::make_shared<dispatch::cancellation_token>();
        wxWindowPtr<ProgressWindow> progress(new ProgressWindow(this, _(L"Importing translations…"), cancellation));
        progress->SetErrorMessage(_("Importing translation memory failed."));

        progress->RunTaskModal([=]() -> BackgroundTaskResult
        {
            Progress progress(paths.size());

            int count = 0;
            for (auto p: paths)
            {
                if (cancellation->is_cancelled())
                    break;

                auto pname = wxFileName(p).GetFullName();
                Progress subprogress(1);
                subprogress.message(wxString::Format(_(L"Importing from “%s”…"), pname));

                try
                {
                    count += doImportFile(p);
                }
                catch (...)
                {
                    wxLogError(("%s: %s"), pname, DescribeCurrentException());
                }
            }

            if (count == 0)
                return {};

            return wxString::Format
                   (
                       // TRANSLATORS: %s is a (formatted) number here
                       wxPLURAL("%s translation was imported.", "%s translations were imported.", count),
                       wxNumberFormatter::ToString((long)count)
                   );
        });

        UpdateStats();
    }

    void OnExportTMX(wxCommandEvent&)
    {
        wxWindowPtr<wxFileDialog> dlg(new wxFileDialog
        (
            this,
            MACOS_OR_OTHER("", _(L"Export as…")),
            "",
            "",
            MaskForType("*.tmx", _("TMX Files")),
            wxFD_SAVE | wxFD_OVERWRITE_PROMPT)
        );

        // dlg->ShowWindowModalThenDo([=](int retcode){
        int retcode = dlg->ShowModal();
        {
            if (retcode != wxID_OK)
                return;

            auto p = dlg->GetPath();

            wxWindowPtr<ProgressWindow> progress(new ProgressWindow(this, _(L"Exporting translations…")));
            progress->SetErrorMessage(wxString::Format(_(L"Exporting translation memory to “%s” failed."), wxFileName(p).GetFullName()));
            progress->RunTaskModal([=]()
            {
                TempOutputFileFor tempfile(p);

                std::ofstream f;
                f.open(tempfile.FileName().fn_str());
                TMX::ExportToFile(TranslationMemory::Get(), f);
                f.close();

                if ( !tempfile.Commit() )
                    BOOST_THROW_EXCEPTION(Exception(wxString::Format(_(L"Couldn’t save file %s."), wxFileName(p).GetFullName())));
            });
        }
    }

    void OnResetTM(wxCommandEvent&)
    {
        auto title = _("Reset translation memory");
        auto main = _("Are you sure you want to reset the translation memory?");
        auto details = _(L"Resetting the translation memory will irrevocably delete all stored translations from it. You can’t undo this operation.");

        wxWindowPtr<wxMessageDialog> dlg(new wxMessageDialog(this, main, title, wxYES_NO | wxNO_DEFAULT | wxICON_WARNING));
        dlg->SetExtendedMessage(details);
        dlg->SetYesNoLabels(_("Reset"), _("Cancel"));

        dlg->ShowWindowModalThenDo([this,dlg](int retcode){
            if (retcode == wxID_YES) {
                wxBusyCursor bcur;
                TranslationMemory::Get().DeleteAllAndReset();
                UpdateStats();
            }
        });
    }

    void OnUpdateUI(wxUpdateUIEvent& e)
    {
        e.Enable(m_useTM->GetValue());
    }

    wxCheckBox *m_useTM;
    wxCheckBox *m_mergeUse;
    wxChoice *m_mergeBehavior;
    wxStaticText *m_stats;
};

class TMPage : public wxPreferencesPage
{
public:
    wxString GetName() const override
    {
#if defined(__WXOSX__) || defined(__WXGTK__)
        // TRANSLATORS: This is abbreviation of "Translation Memory" used in Preferences on macOS.
        // Long text looks weird there, too short (like TM) too, but less so. "General" is about ideal
        // length there.
        return _("TM");
#else
        return _("Translation Memory");
#endif
    }
    wxBitmapBundle GetIcon() const override { return MacPageIcon("internaldrive"); }
    wxWindow *CreateWindow(wxWindow *parent) override { return new TMPageWindow(parent); }
};



class ExtractorsPageWindow : public PrefsPanel
{
public:
    ExtractorsPageWindow(wxWindow *parent) : PrefsPanel(parent)
    {
        auto sizer = ContentSizer();

        sizer->Add(new ExplanationLabel(this, _("Source code extractors are used to find translatable strings in the source code files and extract them so that they can be translated.")),
                   wxSizerFlags().Expand().PXDoubleBorder(wxBOTTOM));

        auto listPanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | BORDER_LISTLIKE);
        SetupListlikeBorder(listPanel);

        auto listSizer = new wxBoxSizer(wxVERTICAL);
        listPanel->SetSizer(listSizer);

        CreateBuiltinExtractorsUI(listPanel, listSizer);

        auto customExLabel = new wxStaticText(listPanel, wxID_ANY, MSW_OR_OTHER(_("Custom extractors:"), _("Custom Extractors:")));
#ifdef __WXOSX__
        customExLabel->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
        customExLabel->SetFont(customExLabel->GetFont().Bold());

        listSizer->AddSpacer(PX(5));
        listSizer->Add(customExLabel, wxSizerFlags().ReserveSpaceEvenIfHidden().Border(wxLEFT|wxRIGHT, PX(5)));
        listSizer->AddSpacer(PX(5));

        m_list = new wxCheckListBox(listPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxBORDER_NONE);
        m_list->SetMinSize(wxSize(PX(400),PX(200)));
#ifdef __WXOSX__
        m_list->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
        ((NSTableView*)[((NSScrollView*)m_list->GetHandle()) documentView]).style = NSTableViewStyleFullWidth;
#endif
        listSizer->Add(m_list, wxSizerFlags(1).Expand().Border(wxLEFT|wxRIGHT, PX(5)));

        sizer->Add(listPanel, wxSizerFlags(1).Expand().BORDER_WIN(wxLEFT, 1));

#if defined(__WXOSX__)
        m_new = new wxBitmapButton(this, wxID_ANY, wxArtProvider::GetBitmap("NSAddTemplate"), wxDefaultPosition, wxSize(18, 18), wxBORDER_SIMPLE);
        m_delete = new wxBitmapButton(this, wxID_ANY, wxArtProvider::GetBitmap("NSRemoveTemplate"), wxDefaultPosition, wxSize(18,18), wxBORDER_SIMPLE);
        int editButtonStyle = wxBU_EXACTFIT | wxBORDER_SIMPLE;
#elif defined(__WXMSW__)
        m_new = new wxBitmapButton(this, wxID_ANY, wxArtProvider::GetBitmap("list-add"), wxDefaultPosition, wxSize(PX(19),PX(19)));
        m_delete = new wxBitmapButton(this, wxID_ANY, wxArtProvider::GetBitmap("list-remove"), wxDefaultPosition, wxSize(PX(19),PX(19)));
        int editButtonStyle = wxBU_EXACTFIT;
#elif defined(__WXGTK__)
        m_new = new wxBitmapButton(this, wxID_ANY, wxArtProvider::GetBitmap("list-add@symbolic"), wxDefaultPosition, wxDefaultSize, wxNO_BORDER);
        m_delete = new wxBitmapButton(this, wxID_ANY, wxArtProvider::GetBitmap("list-remove@symbolic"), wxDefaultPosition, wxDefaultSize, wxNO_BORDER);
        int editButtonStyle = wxBU_EXACTFIT | wxBORDER_NONE;
#endif
        m_edit = new wxButton(this, wxID_ANY, _(L"Edit…"), wxDefaultPosition, wxSize(-1, MSW_OR_OTHER(PX(19), -1)), editButtonStyle);
#ifndef __WXGTK__
        m_edit->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif

        auto buttonSizer = new wxBoxSizer(wxHORIZONTAL);
        buttonSizer->Add(m_new);
#ifdef __WXOSX__
        buttonSizer->AddSpacer(PX(1));
#endif
        buttonSizer->Add(m_delete);
#ifdef __WXOSX__
        buttonSizer->AddSpacer(PX(1));
#endif
        buttonSizer->Add(m_edit);

        sizer->AddSpacer(PX(1));
        sizer->Add(buttonSizer, wxSizerFlags().BORDER_MACOS(wxLEFT, PX(1)));

        ColorScheme::SetupWindowColors(this, [=]
        {
            customExLabel->SetForegroundColour(ExplanationLabel::GetTextColor());

            auto listBg = ColorScheme::Get(Color::ListControlBg);
            listPanel->SetBackgroundColour(listBg);
#ifdef __WXOSX__
            // FIXME: In dark mode, listbox color is special and requires NSBox to
            //        be rendered correctly, so we just use normal background for now, incl. for the list
            m_list->SetBackgroundColour(listBg);
#endif
        });

        m_new->Bind(wxEVT_BUTTON, &ExtractorsPageWindow::OnNewExtractor, this);
        m_edit->Bind(wxEVT_BUTTON, &ExtractorsPageWindow::OnEditExtractor, this);
        m_delete->Bind(wxEVT_BUTTON, &ExtractorsPageWindow::OnDeleteExtractor, this);

        m_list->Bind(wxEVT_CHECKLISTBOX, &ExtractorsPageWindow::OnEnableExtractor, this);
        m_list->Bind(wxEVT_LISTBOX_DCLICK, &ExtractorsPageWindow::OnEditExtractor, this);

        m_edit->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e) { e.Enable(m_list->GetSelection() != wxNOT_FOUND); });
        m_delete->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e) { e.Enable(m_list->GetSelection() != wxNOT_FOUND); });
        customExLabel->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e) { e.Show(m_list->GetCount() > 0); });
    }

    void CreateBuiltinExtractorsUI(wxWindow *panel, wxSizer *topsizer)
    {
        auto sizer = new wxBoxSizer(wxHORIZONTAL);
        topsizer->Add(sizer, wxSizerFlags().Expand().Border(wxALL, PX(5)));

        sizer->Add(new wxStaticBitmap(panel, wxID_ANY, wxArtProvider::GetBitmap("ExtractorsGNUgettext")), wxSizerFlags().Top().Border(wxRIGHT, PX(5)));
        auto textSizer = new wxBoxSizer(wxVERTICAL);
        sizer->Add(textSizer, wxSizerFlags(1).Top());
        auto heading = new wxStaticText(panel, wxID_ANY, _("GNU gettext"));
#ifdef __WXOSX__
        heading->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
        heading->SetFont(heading->GetFont().Bold());
        textSizer->Add(heading, wxSizerFlags().Border(wxBOTTOM, PX(2)));
        auto desc = new ExplanationLabel(panel, _("Supports all programming languages recognized by GNU gettext tools (PHP, C/C++, C#, Perl, Python, Java, JavaScript and others)."));
        textSizer->Add(desc, wxSizerFlags(1).Expand());
        textSizer->Layout();
    }

    void InitValues(const wxConfigBase& cfg) override
    {
        m_extractors.Read(const_cast<wxConfigBase*>(&cfg));

        m_list->Clear();
        for (const auto& item: m_extractors.Data)
        {
            auto index = m_list->Append(bidi::platform_mark_direction(item.Name));
            m_list->Check(index, item.Enabled);
        }

        if (!m_extractors.Data.empty())
        {
            m_list->SetSelection(0);
            m_list->EnsureVisible(0);
        }
    }

    void SaveValues(wxConfigBase& cfg) override
    {
        m_extractors.Write(&cfg);
    }

private:
    class ExtractorEditDialog : public StandardDialog
    {
    public:
        ExtractorEditDialog(wxWindow *parent) : StandardDialog(parent, _("Extractor setup"))
        {
            auto sizer = ContentSizer();

            auto panel = wxXmlResource::Get()->LoadPanel(this, "edit_extractor");
            sizer->Add(panel, wxSizerFlags(1).Expand());

            CreateButtons(wxOK | wxCANCEL);

            FitSizer();
        }
    };

    /// Called to launch dialog for editing parser properties.
    template<typename TFunctor>
    void EditExtractor(int num, TFunctor completionHandler)
    {
        wxWindowPtr<ExtractorEditDialog> dlg(new ExtractorEditDialog(this));
        dlg->Centre();

        auto extractor_language = XRCCTRL(*dlg, "extractor_language", wxTextCtrl);
        auto extractor_extensions = XRCCTRL(*dlg, "extractor_extensions", wxTextCtrl);
        auto extractor_command = XRCCTRL(*dlg, "extractor_command", wxTextCtrl);
        auto extractor_keywords = XRCCTRL(*dlg, "extractor_keywords", wxTextCtrl);
        auto extractor_files = XRCCTRL(*dlg, "extractor_files", wxTextCtrl);
        auto extractor_charset = XRCCTRL(*dlg, "extractor_charset", wxTextCtrl);

        {
            const LegacyExtractorSpec& nfo = m_extractors.Data[num];
            extractor_language->SetValue(bidi::platform_mark_direction(nfo.Name));
            extractor_extensions->SetValue(bidi::mark_direction(nfo.Extensions, TextDirection::LTR));
            extractor_command->SetValue(bidi::mark_direction(nfo.Command, TextDirection::LTR));
            extractor_keywords->SetValue(bidi::mark_direction(nfo.KeywordItem, TextDirection::LTR));
            extractor_files->SetValue(bidi::mark_direction(nfo.FileItem, TextDirection::LTR));
            extractor_charset->SetValue(bidi::mark_direction(nfo.CharsetItem, TextDirection::LTR));
        }

        dlg->Bind
        (
            wxEVT_UPDATE_UI,
            [=](wxUpdateUIEvent& e){
                e.Enable(!extractor_language->IsEmpty() &&
                         !extractor_extensions->IsEmpty() &&
                         !extractor_command->IsEmpty() &&
                         !extractor_files->IsEmpty());
                // charset, keywords could in theory be empty if unsupported by the parser tool
            },
            wxID_OK
        );

        m_suppressDataTransfer++;
        dlg->ShowWindowModalThenDo([=](int retcode){
            m_suppressDataTransfer--;
            (void)dlg; // force use
            if (retcode == wxID_OK)
            {
                LegacyExtractorSpec& nfo = m_extractors.Data[num];
                nfo.Name = bidi::strip_control_chars(extractor_language->GetValue().Strip(wxString::both));
                nfo.Extensions = bidi::strip_control_chars(extractor_extensions->GetValue().Strip(wxString::both));
                nfo.Command = bidi::strip_control_chars(extractor_command->GetValue().Strip(wxString::both));
                nfo.KeywordItem = bidi::strip_control_chars(extractor_keywords->GetValue().Strip(wxString::both));
                nfo.FileItem = bidi::strip_control_chars(extractor_files->GetValue().Strip(wxString::both));
                nfo.CharsetItem = bidi::strip_control_chars(extractor_charset->GetValue().Strip(wxString::both));
                m_list->SetString(num, nfo.Name);
            }
            completionHandler(retcode == wxID_OK);
        });
    }

    void OnNewExtractor(wxCommandEvent&)
    {
        m_suppressDataTransfer++;

        LegacyExtractorSpec info;
        m_extractors.Data.push_back(info);
        auto index = m_list->Append(wxEmptyString);
        m_list->Check(index);
        EditExtractor(index, [=](bool added){
            if (added)
            {
                m_edit->Enable(true);
                m_delete->Enable(true);
            }
            else
            {
                m_list->Delete(index);
                m_extractors.Data.erase(m_extractors.Data.begin() + index);
            }

            m_suppressDataTransfer--;

            if (wxPreferencesEditor::ShouldApplyChangesImmediately())
                TransferDataFromWindow();
        });
    }

    void OnEditExtractor(wxCommandEvent&)
    {
        EditExtractor(m_list->GetSelection(), [=](bool changed){
            if (changed && wxPreferencesEditor::ShouldApplyChangesImmediately())
                TransferDataFromWindow();
        });
    }

    void OnDeleteExtractor(wxCommandEvent&)
    {
        int index = m_list->GetSelection();

        auto title = MSW_OR_OTHER(_("Delete extractor"), "");
        auto main = wxString::Format(_(L"Are you sure you want to delete the “%s” extractor?"), m_extractors.Data[index].Name);

        wxWindowPtr<wxMessageDialog> dlg(new wxMessageDialog(this, main, title, wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION));
        #ifdef __WXOSX__
        dlg->SetExtendedMessage(" "); // prevent wx from using the title stupidly
        #endif
        dlg->SetYesNoLabels(_("Delete"), _("Cancel"));

        dlg->ShowWindowModalThenDo([this,index,dlg](int retcode){
            if (retcode == wxID_YES)
            {
                m_extractors.Data.erase(m_extractors.Data.begin() + index);
                m_list->Delete(index);

                if (wxPreferencesEditor::ShouldApplyChangesImmediately())
                    TransferDataFromWindow();
            }
        });
    }

    void OnEnableExtractor(wxCommandEvent& e)
    {
        int index = e.GetInt();
        m_extractors.Data[index].Enabled = m_list->IsChecked(index);

        if (wxPreferencesEditor::ShouldApplyChangesImmediately())
            TransferDataFromWindow();
    }

    LegacyExtractorsDB m_extractors;

    wxCheckListBox *m_list;
    wxButton *m_new, *m_edit, *m_delete;
};

class ExtractorsPage : public wxPreferencesPage
{
public:
    wxString GetName() const override { return _("Extractors"); }
    wxBitmapBundle GetIcon() const override { return MacPageIcon("doc.text.viewfinder"); }
    wxWindow *CreateWindow(wxWindow *parent) override { return new ExtractorsPageWindow(parent); }
};



#ifdef HAVE_HTTP_CLIENT
class AccountsPageWindow : public PrefsPanel
{
public:
    AccountsPageWindow(wxWindow *parent) : PrefsPanel(parent)
    {
        auto sizer = ContentSizer();

        m_accounts = new AccountsPanel(this);
        sizer->Add(m_accounts, wxSizerFlags(1).Expand());

    #ifdef __WXOSX__
        // This window was possibly created on demand (pre-macOS 11), possibly
        // hidden. Initialize as soon as it is shown:
        Bind(wxEVT_SHOW, [=](wxShowEvent& e){
            if (e.IsShown())
                CallAfter([=]{ m_accounts->InitializeAfterShown(); });
        });
    #else
        // On other platforms, notebook pages are all created at once. Don't do
        // the expensive initialization until shown for the first time. This code
        // is a hack that takes advantage of wxPreferencesEditor's implementation
        // detail, but oh well:
        auto notebook = dynamic_cast<wxNotebook*>(parent);
        if (notebook)
        {
            notebook->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [=](wxBookCtrlEvent& e){
                e.Skip();
                if (notebook->GetPage(e.GetSelection()) == this)
                    CallAfter([=]{ m_accounts->InitializeAfterShown(); });
            });
        }
    #endif
    }

    void InitValues(const wxConfigBase&) override
    {
    }

    void SaveValues(wxConfigBase&) override
    {
    }

private:
    AccountsPanel *m_accounts;
};

class AccountsPage : public wxPreferencesPage
{
public:
    wxString GetName() const override { return _("Accounts"); }
    wxBitmapBundle GetIcon() const override { return MacPageIcon("at"); }
    wxWindow *CreateWindow(wxWindow *parent) override { return new AccountsPageWindow(parent); }
};
#endif // HAVE_HTTP_CLIENT


#ifdef HAS_UPDATES_CHECK
class UpdatesPageWindow : public PrefsPanel
{
public:
    UpdatesPageWindow(wxWindow *parent) : PrefsPanel(parent)
    {
        auto sizer = ContentSizer();
        sizer->SetMinSize(PX(400), -1); // for macOS look, wouldn't fit the toolbar otherwise

        m_updates = new wxCheckBox(this, wxID_ANY, _("Automatically check for updates"));
        sizer->Add(m_updates, wxSizerFlags().Expand().PXBorder(wxTOP|wxBOTTOM));

        m_beta = new wxCheckBox(this, wxID_ANY, _("Include beta versions"));
        sizer->Add(m_beta, wxSizerFlags().Expand().PXBorder(wxBOTTOM));

        sizer->Add(new ExplanationLabel(this, _("Beta versions contain the latest new features and improvements, but may be a bit less stable.")),
                   wxSizerFlags().Expand().Border(wxLEFT, UnderCheckboxIndent()));

        if (wxPreferencesEditor::ShouldApplyChangesImmediately())
            Bind(wxEVT_CHECKBOX, [=](wxCommandEvent&){ TransferDataFromWindow(); });
    }

    void InitValues(const wxConfigBase&) override
    {
        m_updates->SetValue(AppUpdates::Get().AutomaticChecksEnabled());
        m_beta->SetValue(Config::CheckForBetaUpdates());
    }

    void SaveValues(wxConfigBase&) override
    {
        // NB: Must be done first, before calling AppUpdates methods!
        Config::CheckForBetaUpdates(m_beta->GetValue());

        AppUpdates::Get().EnableAutomaticChecks(m_updates->GetValue());
    }

private:
    wxCheckBox *m_updates, *m_beta;
};

class UpdatesPage : public wxPreferencesPage
{
public:
    wxString GetName() const override { return _("Updates"); }
    wxBitmapBundle GetIcon() const override { return MacPageIcon("arrow.down.circle"); }
    wxWindow *CreateWindow(wxWindow *parent) override { return new UpdatesPageWindow(parent); }
};
#endif // HAS_UPDATES_CHECK


class AdvancedPageWindow : public PrefsPanel
{
public:
    AdvancedPageWindow(wxWindow *parent) : PrefsPanel(parent)
    {
        auto sizer = ContentSizer();

        sizer->Add(new ExplanationLabel(this, _("These settings affect internal formatting of PO files. Adjust them if you have specific requirements e.g. because of version control.")), wxSizerFlags().Expand().PXBorder(wxBOTTOM));

        auto crlfbox = new wxBoxSizer(wxHORIZONTAL);
        sizer->Add(crlfbox, wxSizerFlags().Expand().PXBorder(wxTOP));
        crlfbox->Add(new wxStaticText(this, wxID_ANY, _("Line endings:")), wxSizerFlags().Center().BORDER_WIN(wxTOP, PX(1)));
        crlfbox->AddSpacer(PX(5));
        m_crlf = new wxChoice(this, wxID_ANY);
        m_crlf->Append(_("Unix (recommended)"));
        m_crlf->Append(_("Windows"));
        crlfbox->Add(m_crlf, wxSizerFlags(1).Center().Border(wxTOP, AboveChoicePadding()));

        /// TRANSLATORS: Followed by text control for entering number; wraps text at given width
        m_wrap = new wxCheckBox(this, wxID_ANY, _("Wrap at:"));
        crlfbox->AddSpacer(PX(10));
        crlfbox->Add(m_wrap, wxSizerFlags().Center().BORDER_WIN(wxTOP, PX(1)));
    #ifdef __WXGTK3__
        m_wrapWidth = new wxSpinCtrl(this, wxID_ANY, "", wxDefaultPosition, wxSize(PX(110),-1));
    #else
        m_wrapWidth = new wxSpinCtrl(this, wxID_ANY, "", wxDefaultPosition, wxSize(PX(50),-1));
    #endif
        m_wrapWidth->SetRange(10, 999);
        crlfbox->Add(m_wrapWidth, wxSizerFlags().Center().BORDER_MACOS(wxLEFT, PX(3)));

        m_keepFmt = new wxCheckBox(this, wxID_ANY, _("Preserve formatting of existing files"));
        sizer->Add(m_keepFmt, wxSizerFlags().PXBorder(wxTOP));

        Fit();

        if (wxPreferencesEditor::ShouldApplyChangesImmediately())
        {
            Bind(wxEVT_CHECKBOX, [=](wxCommandEvent&){ TransferDataFromWindow(); });
            Bind(wxEVT_CHOICE, [=](wxCommandEvent&){ TransferDataFromWindow(); });
            Bind(wxEVT_TEXT, [=](wxCommandEvent&){ TransferDataFromWindow(); });
        }

        // handle UI updates:
        m_wrapWidth->Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& e){ e.Enable(m_wrap->GetValue()); });
    }

    void InitValues(const wxConfigBase& cfg) override
    {
        m_keepFmt->SetValue(cfg.ReadBool("keep_crlf", true));

        wxString format = cfg.Read("crlf_format", "unix");
        int sel;
        if (format == "win") sel = 1;
        else /* "unix" or obsolete settings */ sel = 0;
        m_crlf->SetSelection(sel);

        m_wrap->SetValue(cfg.ReadBool("wrap_po_files", true));
        m_wrapWidth->SetValue((int)cfg.ReadLong("wrap_po_files_width", 79));
    }

    void SaveValues(wxConfigBase& cfg) override
    {
        cfg.Write("keep_crlf", m_keepFmt->GetValue());

        static const char *formats[] = { "unix", "win" };
        cfg.Write("crlf_format", formats[m_crlf->GetSelection()]);

        cfg.Write("wrap_po_files", m_wrap->GetValue());
        cfg.Write("wrap_po_files_width", m_wrapWidth->GetValue());
    }

private:
    wxChoice *m_crlf;
    wxCheckBox *m_wrap;
    wxSpinCtrl *m_wrapWidth;
    wxCheckBox *m_keepFmt;
};

class AdvancedPage : public wxStockPreferencesPage
{
public:
    AdvancedPage() : wxStockPreferencesPage(Kind_Advanced) {}
    wxString GetName() const override { return _("Advanced"); }
    wxBitmapBundle GetIcon() const override { return MacPageIcon("gearshape.2"); }
    wxWindow *CreateWindow(wxWindow *parent) override { return new AdvancedPageWindow(parent); }
};


} // anonymous namespace



std::unique_ptr<PoeditPreferencesEditor> PoeditPreferencesEditor::Create()
{
    std::unique_ptr<PoeditPreferencesEditor> p(new PoeditPreferencesEditor);
    p->AddPage(new GeneralPage);
    p->AddPage(new TMPage);
    p->AddPage(new ExtractorsPage);
#ifdef HAVE_HTTP_CLIENT
    p->AddPage(new AccountsPage);
#endif
#ifdef HAS_UPDATES_CHECK
    p->AddPage(new UpdatesPage);
#endif
    p->AddPage(new AdvancedPage);
    return p;
}

PoeditPreferencesEditor::PoeditPreferencesEditor()
#if defined(__WXMSW__) || defined(__WXOSX__)
    : wxPreferencesEditor(_("Settings"))
#endif
{
}