-
Notifications
You must be signed in to change notification settings - Fork 275
/
prefsdlg.cpp
1251 lines (1066 loc) · 47.4 KB
/
prefsdlg.cpp
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
/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2000-2021 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>
#if !wxCHECK_VERSION(3,1,0)
#define CenterVertical() Center()
#endif
#include "edapp.h"
#include "edframe.h"
#include "catalog.h"
#include "configuration.h"
#include "crowdin_gui.h"
#include "hidpi.h"
#include "tm/transmem.h"
#include "tm/tmx_io.h"
#include "chooselang.h"
#include "errors.h"
#include "extractors/extractor_legacy.h"
#include "spellchecking.h"
#include "str_helpers.h"
#include "utility.h"
#include "customcontrols.h"
#include "unicode_helpers.h"
#ifdef __WXMSW__
#include <winsparkle.h>
#endif
#ifdef USE_SPARKLE
#include "macos_helpers.h"
#endif // USE_SPARKLE
#if defined(USE_SPARKLE) || defined(__WXMSW__)
#define HAS_UPDATES_CHECK
#endif
// Handling of different page icons
#ifdef __WXOSX__
inline wxBitmap MacPageIcon(const char *macos10, const char *macos11)
{
(void)macos11;
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16
if (@available(macOS 11.0, *))
return wxBitmap([NSImage imageWithSystemSymbolName:str::to_NS(macos11) accessibilityDescription:nil]);
else
#endif
return wxArtProvider::GetBitmap(macos10);
}
#else
inline wxBitmap MacPageIcon(const char*, const char*) { return wxNullBitmap; }
#endif
namespace
{
class PrefsPanel : public WindowWith2DSizingConstraints<wxPanel>
{
public:
PrefsPanel(wxWindow *parent)
: WindowWith2DSizingConstraints<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)
{
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
topsizer->SetMinSize(PX(400), -1);
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(sizer, wxSizerFlags(1).Expand().PXDoubleBorderAll());
SetSizer(topsizer);
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);
m_showSummary = new wxCheckBox(this, wxID_ANY, _("Show summary after updating files"));
sizer->Add(m_showSummary, wxSizerFlags().PXBorder(wxTOP));
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, PX(ExplanationLabel::CHECKBOX_INDENT)));
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_showSummary->SetValue(cfg.ReadBool("show_summary", false));
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("show_summary", m_showSummary->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_showSummary, *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"); }
wxBitmap GetLargeIcon() const override { return MacPageIcon("Prefs-General", "gearshape"); }
wxWindow *CreateWindow(wxWindow *parent) override { return new GeneralPageWindow(parent); }
};
class TMPageWindow : public PrefsPanel
{
public:
TMPageWindow(wxWindow *parent) : PrefsPanel(parent)
{
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
#ifdef __WXOSX__
topsizer->SetMinSize(PX(430), -1); // for macOS look
#endif
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(sizer, wxSizerFlags(1).Expand().PXDoubleBorderAll());
SetSizer(topsizer);
sizer->AddSpacer(PX(5));
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().BORDER_MACOS(wxTOP, PX(1)).BORDER_WIN(wxBOTTOM, 1));
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, PX(ExplanationLabel::CHECKBOX_INDENT)));
auto learnMore = new LearnMoreLink(this, "https://poedit.net/trac/wiki/Doc/TranslationMemory");
sizer->AddSpacer(PX(3));
sizer->Add(learnMore, wxSizerFlags().Border(wxLEFT, PX(ExplanationLabel::CHECKBOX_INDENT + LearnMoreLink::EXTRA_INDENT)));
sizer->AddSpacer(PX(10));
#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 const auto idLearn = wxNewId();
static const auto idImportTMX = wxNewId();
static const auto idExportTMX = wxNewId();
static const auto idReset = wxNewId();
wxMenu menu;
#ifdef __WXOSX__
[menu.GetHMenu() setFont:[NSFont systemFontOfSize:13]];
#endif
menu.Append(idLearn, MSW_OR_OTHER(_(L"Import translation files…"), _(L"Import Translation Files…")));
menu.AppendSeparator();
menu.Append(idImportTMX, MSW_OR_OTHER(_(L"Import from TMX…"), _(L"Import From TMX…")));
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).
menu.Append(idReset, _("Reset"));
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){
if (retcode != wxID_OK)
return;
wxArrayString paths;
dlg->GetPaths(paths);
wxProgressDialog progress(_("Translation Memory"),
_(L"Importing translations…"),
(int)paths.size() * 2 + 1,
this,
wxPD_APP_MODAL|wxPD_AUTO_HIDE|wxPD_CAN_ABORT);
auto tm = TranslationMemory::Get().GetWriter();
int step = 0;
for (size_t i = 0; i < paths.size(); i++)
{
auto cat = Catalog::Create(paths[i]);
if (!progress.Update(++step))
break;
if (cat && cat->IsOk())
tm->Insert(cat);
if (!progress.Update(++step))
break;
}
progress.Pulse(_(L"Finalizing…"));
tm->Commit();
UpdateStats();
});
}
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){
if (retcode != wxID_OK)
return;
wxArrayString paths;
dlg->GetPaths(paths);
wxProgressDialog progress(_("Translation Memory"),
_(L"Importing translations…"),
(int)paths.size() + 1,
this,
wxPD_APP_MODAL|wxPD_AUTO_HIDE|wxPD_CAN_ABORT);
progress.Pulse();
for (auto p: paths)
{
try
{
std::ifstream f;
f.open(p.fn_str());
TMX::ImportFromFile(f, TranslationMemory::Get());
f.close();
if (!progress.Pulse())
break;
}
catch (...)
{
wxWindowPtr<wxMessageDialog> err(new wxMessageDialog
(
this,
wxString::Format(_(L"Importing translation memory from “%s” failed."), p),
_("Import error"),
wxOK | wxICON_ERROR
));
err->SetExtendedMessage(DescribeCurrentException());
err->ShowWindowModalThenDo([err](int){});
break;
}
}
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){
if (retcode != wxID_OK)
return;
auto p = dlg->GetPath();
wxProgressDialog progress(_("Translation Memory"),
_(L"Exporting translations…"),
1,
this,
wxPD_APP_MODAL|wxPD_AUTO_HIDE|wxPD_CAN_ABORT);
progress.Pulse();
try
{
std::ofstream f;
f.open(p.fn_str());
TMX::ExportToFile(TranslationMemory::Get(), f);
f.close();
}
catch (...)
{
wxWindowPtr<wxMessageDialog> err(new wxMessageDialog
(
this,
wxString::Format(_(L"Exporting translation memory to “%s” failed."), p),
_("Export error"),
wxOK | wxICON_ERROR
));
err->SetExtendedMessage(DescribeCurrentException());
err->ShowWindowModalThenDo([err](int){});
}
});
}
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
}
wxBitmap GetLargeIcon() const override { return MacPageIcon("Prefs-TM", "internaldrive"); }
wxWindow *CreateWindow(wxWindow *parent) override { return new TMPageWindow(parent); }
};
class ExtractorsPageWindow : public PrefsPanel
{
public:
ExtractorsPageWindow(wxWindow *parent) : PrefsPanel(parent)
{
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(sizer, wxSizerFlags(1).Expand().PXDoubleBorderAll());
SetSizer(topsizer);
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));
// FIXME: Neither wxBORDER_ flag produces correct results on macOS or Windows, would need to paint manually
auto listPanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | MSW_OR_OTHER(wxBORDER_SIMPLE, wxBORDER_SUNKEN));
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);
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16
if (@available(macOS 11.0, *))
((NSTableView*)[((NSScrollView*)m_list->GetHandle()) documentView]).style = NSTableViewStyleFullWidth;
#endif
#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());
#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:
if (ColorScheme::GetWindowMode(this) == ColorScheme::Dark)
{
listPanel->SetBackgroundColour(listPanel->GetDefaultAttributes().colBg);
}
else
#endif
{
listPanel->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX));
}
});
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_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:
/// Called to launch dialog for editing parser properties.
template<typename TFunctor>
void EditExtractor(int num, TFunctor completionHandler)
{
wxWindowPtr<wxDialog> dlg(wxXmlResource::Get()->LoadDialog(this, "edit_extractor"));
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;