-
Notifications
You must be signed in to change notification settings - Fork 278
/
catalog_po.cpp
1830 lines (1555 loc) · 56.6 KB
/
catalog_po.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) 1999-2024 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 "catalog_po.h"
#include "configuration.h"
#include "errors.h"
#include "extractors/extractor.h"
#include "gexecute.h"
#include "str_helpers.h"
#include "utility.h"
#include "version.h"
#include "language.h"
#include <stdio.h>
#include <wx/utils.h>
#include <wx/tokenzr.h>
#include <wx/log.h>
#include <wx/intl.h>
#include <wx/datetime.h>
#include <wx/config.h>
#include <wx/textfile.h>
#include <wx/stdpaths.h>
#include <wx/strconv.h>
#include <wx/memtext.h>
#include <wx/filename.h>
#include <set>
#include <algorithm>
#ifdef __WXOSX__
#import <Foundation/Foundation.h>
#endif
// TODO: split into different file
#if wxUSE_GUI
#include <wx/msgdlg.h>
#endif
// ----------------------------------------------------------------------
// Textfile processing utilities:
// ----------------------------------------------------------------------
namespace
{
// If input begins with pattern, fill output with end of input (without
// pattern; strips trailing spaces) and return true. Return false otherwise
// and don't touch output. Is permissive about whitespace in the input:
// a space (' ') in pattern will match any number of any whitespace characters
// on that position in input.
bool ReadParam(const wxString& input, const wxString& pattern, wxString& output, bool preserveWhitespace = false)
{
if (input.size() < pattern.size())
return false;
unsigned in_pos = 0;
unsigned pat_pos = 0;
while (pat_pos < pattern.size() && in_pos < input.size())
{
const wxChar pat = pattern[pat_pos++];
if (pat == _T(' '))
{
if (!wxIsspace(input[in_pos++]))
return false;
if (!preserveWhitespace)
{
while (wxIsspace(input[in_pos]))
{
in_pos++;
if (in_pos == input.size())
return false;
}
}
}
else
{
if (input[in_pos++] != pat)
return false;
}
}
if (pat_pos < pattern.size()) // pattern not fully matched
return false;
output = input.Mid(in_pos);
if (!preserveWhitespace)
output.Trim(true); // trailing whitespace
return true;
}
// Checks if the file was loaded correctly, i.e. that non-empty lines
// ended up non-empty in memory, after doing charset conversion in
// wxTextFile. This detects for example files that claim they are in UTF-8
// while in fact they are not.
bool VerifyFileCharset(const wxTextFile& f, const wxString& filename,
const wxString& charset)
{
wxTextFile f2;
if (!f2.Open(filename, wxConvISO8859_1))
return false;
if (f.GetLineCount() != f2.GetLineCount())
{
int linesCount = (int)f2.GetLineCount() - (int)f.GetLineCount();
wxLogError(wxPLURAL(L"%i line of file “%s” was not loaded correctly.",
L"%i lines of file “%s” were not loaded correctly.",
linesCount),
linesCount,
filename.c_str());
return false;
}
bool ok = true;
size_t cnt = f.GetLineCount();
for (size_t i = 0; i < cnt; i++)
{
if (f[i].empty() && !f2[i].empty()) // wxMBConv conversion failed
{
wxLogError(
_(L"Line %d of file “%s” is corrupted (not valid %s data)."),
int(i), filename.c_str(), charset.c_str());
ok = false;
}
}
return ok;
}
wxTextFileType GetFileCRLFFormat(wxTextFile& po_file)
{
wxLogNull null;
auto crlf = po_file.GuessType();
// Discard any unsupported setting. In particular, we ignore "Mac"
// line endings, because the ancient OS 9 systems aren't used anymore,
// OSX uses Unix ending *and* "Mac" endings break gettext tools. So if
// we encounter a catalog with "Mac" line endings, we silently convert
// it into Unix endings (i.e. the modern Mac).
if (crlf == wxTextFileType_Mac)
crlf = wxTextFileType_Unix;
if (crlf != wxTextFileType_Dos && crlf != wxTextFileType_Unix)
crlf = wxTextFileType_None;
return crlf;
}
wxTextFileType GetDesiredCRLFFormat(wxTextFileType existingCRLF)
{
if (existingCRLF != wxTextFileType_None && wxConfigBase::Get()->ReadBool("keep_crlf", true))
{
return existingCRLF;
}
else
{
wxString format = wxConfigBase::Get()->Read("crlf_format", "unix");
if (format == "win")
return wxTextFileType_Dos;
else /* "unix" or obsolete settings */
return wxTextFileType_Unix;
}
}
unsigned GetCountFromPluralFormsHeader(const Catalog::HeaderData& header)
{
if ( header.HasHeader("Plural-Forms") )
{
// e.g. "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ?
// 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
wxString form = header.GetHeader("Plural-Forms");
form = form.BeforeFirst(_T(';'));
if (form.BeforeFirst(_T('=')) == "nplurals")
{
wxString vals = form.AfterFirst('=');
if (vals == "INTEGER") // POT default
return 2;
long val;
if (vals.ToLong(&val))
return (unsigned)val;
}
}
// fallback value for plural forms count should be 2, as in English:
return 2;
}
} // anonymous namespace
// ----------------------------------------------------------------------
// Parsers
// ----------------------------------------------------------------------
bool POCatalogParser::Parse()
{
static const wxString prefix_flags(wxS("#, "));
static const wxString prefix_autocomments(wxS("#. "));
static const wxString prefix_autocomments2(wxS("#.")); // account for empty auto comments
static const wxString prefix_references(wxS("#: "));
static const wxString prefix_prev_msgid(wxS("#| "));
static const wxString prefix_msgctxt(wxS("msgctxt \""));
static const wxString prefix_msgid(wxS("msgid \""));
static const wxString prefix_msgid_plural(wxS("msgid_plural \""));
static const wxString prefix_msgstr(wxS("msgstr \""));
static const wxString prefix_msgstr_plural(wxS("msgstr["));
static const wxString prefix_deleted(wxS("#~"));
static const wxString prefix_deleted_msgid(wxS("#~ msgid"));
if (m_textFile->GetLineCount() == 0)
return false;
wxString line, dummy;
wxString mflags, mstr, msgid_plural, mcomment;
wxArrayString mrefs, mextractedcomments, mtranslations;
wxArrayString msgid_old;
bool has_plural = false;
bool has_context = false;
wxString msgctxt;
unsigned mlinenum = 0;
line = m_textFile->GetFirstLine();
if (line.empty()) line = ReadTextLine();
while (!line.empty())
{
// ignore empty special tags (except for extracted comments which we
// DO want to preserve):
while (line.length() == 2 && *line.begin() == '#' && (line[1] == ',' || line[1] == ':' || line[1] == '|'))
line = ReadTextLine();
// flags:
// Can't we have more than one flag, now only the last is kept ...
if (ReadParam(line, prefix_flags, dummy))
{
static wxString prefix_flags_partial(wxS(", "));
mflags = prefix_flags_partial + dummy;
line = ReadTextLine();
}
// auto comments:
if (ReadParam(line, prefix_autocomments, dummy, /*preserveWhitespace=*/true) || ReadParam(line, prefix_autocomments2, dummy, /*preserveWhitespace=*/true))
{
mextractedcomments.Add(dummy);
line = ReadTextLine();
}
// references:
else if (ReadParam(line, prefix_references, dummy, /*preserveWhitespace=*/true))
{
// Just store the references unmodified, we don't modify this
// data anywhere.
mrefs.push_back(dummy);
line = ReadTextLine();
}
// previous msgid value:
else if (ReadParam(line, prefix_prev_msgid, dummy))
{
msgid_old.Add(dummy);
line = ReadTextLine();
}
// msgctxt:
else if (ReadParam(line, prefix_msgctxt, dummy))
{
has_context = true;
msgctxt = UnescapeCString(dummy.RemoveLast());
while (!(line = ReadTextLine()).empty())
{
if (line[0u] == _T('\t'))
line.Remove(0, 1);
if (line[0u] == _T('"') && line.Last() == _T('"'))
{
msgctxt += UnescapeCString(line.Mid(1, line.Length() - 2));
PossibleWrappedLine();
}
else
break;
}
}
// msgid:
else if (ReadParam(line, prefix_msgid, dummy))
{
mstr = UnescapeCString(dummy.RemoveLast());
mlinenum = unsigned(m_textFile->GetCurrentLine() + 1);
while (!(line = ReadTextLine()).empty())
{
if (line[0u] == wxS('\t'))
line.Remove(0, 1);
if (line[0u] == wxS('"') && line.Last() == wxS('"'))
{
mstr += UnescapeCString(line.Mid(1, line.Length() - 2));
PossibleWrappedLine();
}
else
break;
}
}
// msgid_plural:
else if (ReadParam(line, prefix_msgid_plural, dummy))
{
msgid_plural = UnescapeCString(dummy.RemoveLast());
has_plural = true;
mlinenum = unsigned(m_textFile->GetCurrentLine() + 1);
while (!(line = ReadTextLine()).empty())
{
if (line[0u] == _T('\t'))
line.Remove(0, 1);
if (line[0u] == _T('"') && line.Last() == _T('"'))
{
msgid_plural += UnescapeCString(line.Mid(1, line.Length() - 2));
PossibleWrappedLine();
}
else
break;
}
}
// msgstr:
else if (ReadParam(line, prefix_msgstr, dummy))
{
if (has_plural)
{
wxLogError(_("Broken PO file: singular form msgstr used together with msgid_plural"));
return false;
}
wxString str = UnescapeCString(dummy.RemoveLast());
while (!(line = ReadTextLine()).empty())
{
if (line[0u] == _T('\t'))
line.Remove(0, 1);
if (line[0u] == _T('"') && line.Last() == _T('"'))
{
str += UnescapeCString(line.Mid(1, line.Length() - 2));
PossibleWrappedLine();
}
else
break;
}
mtranslations.Add(str);
bool shouldIgnore = m_ignoreHeader && (mstr.empty() && !has_context);
if ( shouldIgnore )
{
OnIgnoredEntry();
}
else
{
if (!mstr.empty() && m_ignoreTranslations)
mtranslations.clear();
if (!OnEntry(mstr, wxEmptyString, false,
has_context, msgctxt,
mtranslations,
mflags, mrefs, mcomment, mextractedcomments, msgid_old,
mlinenum))
{
return false;
}
}
mcomment = mstr = msgid_plural = msgctxt = mflags = wxEmptyString;
has_plural = has_context = false;
mrefs.Clear();
mextractedcomments.Clear();
mtranslations.Clear();
msgid_old.Clear();
}
// msgstr[i]:
else if (ReadParam(line, prefix_msgstr_plural, dummy))
{
if (!has_plural)
{
wxLogError(_("Broken PO file: plural form msgstr used without msgid_plural"));
return false;
}
wxString idx = dummy.BeforeFirst(wxS(']'));
wxString label_prefix = prefix_msgstr_plural + idx + wxS("] \"");
while (ReadParam(line, label_prefix, dummy))
{
wxString str = UnescapeCString(dummy.RemoveLast());
while (!(line=ReadTextLine()).empty())
{
line.Trim(/*fromRight=*/false);
if (line[0u] == wxS('"') && line.Last() == wxS('"'))
{
str += UnescapeCString(line.Mid(1, line.Length() - 2));
PossibleWrappedLine();
}
else
{
if (ReadParam(line, prefix_msgstr_plural, dummy))
{
idx = dummy.BeforeFirst(wxS(']'));
label_prefix = prefix_msgstr_plural + idx + wxS("] \"");
}
break;
}
}
mtranslations.Add(str);
}
if (m_ignoreTranslations)
mtranslations.clear();
if (!OnEntry(mstr, msgid_plural, true,
has_context, msgctxt,
mtranslations,
mflags, mrefs, mcomment, mextractedcomments, msgid_old,
mlinenum))
{
return false;
}
mcomment = mstr = msgid_plural = msgctxt = mflags = wxEmptyString;
has_plural = has_context = false;
mrefs.Clear();
mextractedcomments.Clear();
mtranslations.Clear();
msgid_old.Clear();
}
// deleted lines:
else if (ReadParam(line, prefix_deleted, dummy))
{
wxArrayString deletedLines;
deletedLines.Add(line);
mlinenum = unsigned(m_textFile->GetCurrentLine() + 1);
while (!(line = ReadTextLine()).empty())
{
// if line does not start with "#~" anymore, stop reading
if (!ReadParam(line, prefix_deleted, dummy))
break;
// if the line starts with "#~ msgid", we skipped an empty line
// and it's a new entry, so stop reading too (see bug #329)
if (ReadParam(line, prefix_deleted_msgid, dummy))
break;
deletedLines.Add(line);
}
if (!OnDeletedEntry(deletedLines,
mflags, mrefs, mcomment, mextractedcomments, mlinenum))
{
return false;
}
mcomment = mstr = msgid_plural = mflags = wxEmptyString;
has_plural = false;
mrefs.Clear();
mextractedcomments.Clear();
mtranslations.Clear();
msgid_old.Clear();
}
// comment:
else if (line[0u] == wxS('#'))
{
bool readNewLine = false;
while (!line.empty() &&
line[0u] == wxS('#') &&
(line.Length() < 2 || (line[1u] != wxS(',') && line[1u] != wxS(':') && line[1u] != wxS('.') && line[1u] != wxS('~') )))
{
mcomment << line << wxS('\n');
readNewLine = true;
line = ReadTextLine();
}
if (!readNewLine)
line = ReadTextLine();
}
else
{
line = ReadTextLine();
}
}
return true;
}
wxString POCatalogParser::ReadTextLine()
{
m_previousLineHardWrapped = m_lastLineHardWrapped;
m_lastLineHardWrapped = false;
static const wxString msgid_alone(wxS("msgid \"\""));
static const wxString msgstr_alone(wxS("msgstr \"\""));
for (;;)
{
if (m_textFile->Eof())
return wxString();
// read next line and strip insignificant whitespace from it:
const auto& ln = m_textFile->GetNextLine();
if (ln.empty())
continue;
// gettext tools don't include (extracted) comments in wrapping, so they can't
// be reliably used to detect file's wrapping either; just skip them.
if (!ln.starts_with(wxS("#. ")) && !ln.starts_with(wxS("# ")))
{
if (ln.ends_with(wxS("\\n\"")))
{
// Similarly, lines ending with \n are always wrapped, so skip that too.
m_lastLineHardWrapped = true;
}
else if (ln == msgid_alone || ln == msgstr_alone)
{
// The header is always indented like this
m_lastLineHardWrapped = true;
}
else
{
// Watch out for lines with too long words that couldn't be wrapped.
// That "2" is to account for unwrappable comment lines: "#: somethinglong"
// See https://github.com/vslavik/poedit/issues/135
auto space = ln.find_last_of(' ');
if (space != wxString::npos && space > 2)
{
m_detectedLineWidth = std::max(m_detectedLineWidth, (int)ln.size());
}
}
}
if (wxIsspace(ln[0]) || wxIsspace(ln.Last()))
{
auto s = ln.Strip(wxString::both);
if (!s.empty())
return s;
}
else
{
return ln;
}
}
return wxString();
}
int POCatalogParser::GetWrappingWidth() const
{
if (!m_detectedWrappedLines)
return POCatalog::NO_WRAPPING;
return m_detectedLineWidth;
}
class POCharsetInfoFinder : public POCatalogParser
{
public:
POCharsetInfoFinder(wxTextFile *f)
: POCatalogParser(f), m_charset("UTF-8") {}
wxString GetCharset() const { return m_charset; }
protected:
wxString m_charset;
virtual bool OnEntry(const wxString& msgid,
const wxString& /*msgid_plural*/,
bool /*has_plural*/,
bool has_context,
const wxString& /*context*/,
const wxArrayString& mtranslations,
const wxString& /*flags*/,
const wxArrayString& /*references*/,
const wxString& /*comment*/,
const wxArrayString& /*extractedComments*/,
const wxArrayString& /*msgid_old*/,
unsigned /*lineNumber*/)
{
if (msgid.empty() && !has_context)
{
// gettext header:
Catalog::HeaderData hdr;
hdr.FromString(mtranslations[0]);
m_charset = hdr.Charset;
if (m_charset == "CHARSET")
m_charset = "ISO-8859-1";
return false; // stop parsing
}
return true;
}
};
class POLoadParser : public POCatalogParser
{
public:
POLoadParser(POCatalog& c, wxTextFile *f)
: POCatalogParser(f),
FileIsValid(false),
m_catalog(c), m_nextId(1), m_seenHeaderAlready(false) {}
// true if the file is valid, i.e. has at least some data
bool FileIsValid;
Language GetSpecifiedMsgidLanguage()
{
auto x_srclang = m_catalog.Header().GetHeader("X-Source-Language");
if (x_srclang.empty())
x_srclang = m_catalog.m_header.GetHeader("X-Loco-Source-Locale");
if (!x_srclang.empty())
{
auto parsed = Language::TryParse(str::to_utf8(x_srclang));
if (parsed.IsValid())
return parsed;
}
return Language();
}
protected:
POCatalog& m_catalog;
virtual bool OnEntry(const wxString& msgid,
const wxString& msgid_plural,
bool has_plural,
bool has_context,
const wxString& context,
const wxArrayString& mtranslations,
const wxString& flags,
const wxArrayString& references,
const wxString& comment,
const wxArrayString& extractedComments,
const wxArrayString& msgid_old,
unsigned lineNumber);
virtual bool OnDeletedEntry(const wxArrayString& deletedLines,
const wxString& flags,
const wxArrayString& references,
const wxString& comment,
const wxArrayString& extractedComments,
unsigned lineNumber);
virtual void OnIgnoredEntry() { FileIsValid = true; }
private:
int m_nextId;
bool m_seenHeaderAlready;
};
bool POLoadParser::OnEntry(const wxString& msgid,
const wxString& msgid_plural,
bool has_plural,
bool has_context,
const wxString& context,
const wxArrayString& mtranslations,
const wxString& flags,
const wxArrayString& references,
const wxString& comment,
const wxArrayString& extractedComments,
const wxArrayString& msgid_old,
unsigned lineNumber)
{
FileIsValid = true;
static const wxString MSGCAT_CONFLICT_MARKER("#-#-#-#-#");
if (msgid.empty() && !has_context)
{
if (!m_seenHeaderAlready)
{
// gettext header:
m_catalog.m_header.FromString(mtranslations[0]);
m_catalog.m_header.Comment = comment;
for (const auto& s : extractedComments)
m_catalog.m_header.Comment += "\n#. " + s;
for (const auto& s : references)
m_catalog.m_header.Comment += "\n#: " + s;
if (!flags.empty())
m_catalog.m_header.Comment += "\n#" + flags;
m_seenHeaderAlready = true;
}
// else: ignore duplicate header in malformed files
}
else
{
auto d = std::make_shared<POCatalogItem>();
d->SetId(m_nextId++);
if (!flags.empty())
d->SetFlags(flags);
d->SetString(msgid);
if (has_plural)
{
m_catalog.m_hasPluralItems = true;
d->SetPluralString(msgid_plural);
}
if (has_context)
d->SetContext(context);
d->SetTranslations(mtranslations);
d->SetComment(comment);
d->SetLineNumber(lineNumber);
d->SetRawReferences(references);
for (auto i: extractedComments)
{
// Sometimes, msgcat produces conflicts in extracted comments; see the gory details:
// https://groups.google.com/d/topic/poedit/j41KuvXtVUU/discussion
// As a workaround, just filter them out.
// FIXME: Fix this properly... but not using msgcat in the first place
if (i.starts_with(MSGCAT_CONFLICT_MARKER) && i.ends_with(MSGCAT_CONFLICT_MARKER))
continue;
d->AddExtractedComments(i);
}
d->SetOldMsgid(msgid_old);
m_catalog.AddItem(d);
}
return true;
}
bool POLoadParser::OnDeletedEntry(const wxArrayString& deletedLines,
const wxString& flags,
const wxArrayString& /*references*/,
const wxString& comment,
const wxArrayString& extractedComments,
unsigned lineNumber)
{
FileIsValid = true;
POCatalogDeletedData d;
if (!flags.empty()) d.SetFlags(flags);
d.SetDeletedLines(deletedLines);
d.SetComment(comment);
d.SetLineNumber(lineNumber);
for (size_t i = 0; i < extractedComments.GetCount(); i++)
d.AddExtractedComments(extractedComments[i]);
m_catalog.AddDeletedItem(d);
return true;
}
// ----------------------------------------------------------------------
// POCatalogItem class
// ----------------------------------------------------------------------
wxArrayString POCatalogItem::GetReferences() const
{
// A line may contain several references, separated by white-space.
// Traditionally, each reference was in the form "path_name:line_number", but non
// standard references are sometime used too, including hyperlinks.
// Filenames that contain spaces are supported - they must be enclosed by Unicode
// characters U+2068 and U+2069.
wxArrayString refs;
for (auto ref = m_references.begin(); ref != m_references.end(); ++ref)
{
auto line = ref->Strip(wxString::both);
wxString buf;
auto i = line.begin();
while (i != line.end())
{
const wchar_t c = *i;
if (wxIsspace(c))
{
// store reference text encountered so far:
if (!buf.empty())
{
refs.push_back(buf);
buf.clear();
}
++i;
}
else if (c == L'\u2068')
{
// quoted filename between U+2068 and U+2069:
++i;
while (i != line.end() && *i != L'\u2069')
{
buf += *i;
++i;
}
if (i != line.end())
++i; // skip trailing U+2069
}
else
{
buf += c;
++i;
}
}
if (!buf.empty())
refs.push_back(buf);
}
return refs;
}
// ----------------------------------------------------------------------
// POCatalog class
// ----------------------------------------------------------------------
POCatalog::POCatalog(Type type) : Catalog(type)
{
m_fileCRLF = wxTextFileType_None;
m_fileWrappingWidth = DEFAULT_WRAPPING;
}
POCatalog::POCatalog(const wxString& po_file, int flags) : Catalog(Type::PO)
{
m_fileCRLF = wxTextFileType_None;
m_fileWrappingWidth = DEFAULT_WRAPPING;
Load(po_file, flags);
}
void POCatalog::PostCreation()
{
Catalog::PostCreation();
// gettext historically assumes English:
if (!m_sourceLanguage.IsValid() && !m_sourceIsSymbolicID)
m_sourceLanguage = Language::English();
}
bool POCatalog::HasCapability(Catalog::Cap cap) const
{
switch (cap)
{
case Cap::Translations:
case Cap::LanguageSetting:
case Cap::UserComments:
case Cap::FuzzyTranslations:
return m_fileType == Type::PO;
}
return false; // silence VC++ warning
}
bool POCatalog::CanLoadFile(const wxString& extension)
{
return extension == "po" || extension == "pot";
}
wxString POCatalog::GetPreferredExtension() const
{
switch (m_fileType)
{
case Type::PO:
return "po";
case Type::POT:
return "pot";
default:
wxFAIL_MSG("not possible here");
return "po";
}
return "po";
}
static inline wxString GetCurrentTimeString()
{
return wxDateTime::Now().Format("%Y-%m-%d %H:%M%z");
}
void POCatalog::Load(const wxString& po_file, int flags)
{
wxTextFile f;
Clear();
m_fileName = po_file;
m_header.BasePath = wxEmptyString;
wxString ext;
wxFileName::SplitPath(po_file, nullptr, nullptr, &ext);
if (ext.CmpNoCase("pot") == 0 || (flags & CreationFlag_IgnoreTranslations))
m_fileType = Type::POT;
else
m_fileType = Type::PO;
/* Load the .po file: */
if (!f.Open(po_file, wxConvISO8859_1))
{
throw Exception(_(L"Couldn’t load the file, it is probably damaged."));
}
{
wxLogNull null; // don't report parsing errors from here, report them later
POCharsetInfoFinder charsetFinder(&f);
charsetFinder.Parse();
m_header.Charset = charsetFinder.GetCharset();
}
f.Close();
wxCSConv encConv(m_header.Charset);
if (!f.Open(po_file, encConv))
{
throw Exception(_(L"Couldn’t load the file, it is probably damaged."));
}
if (!VerifyFileCharset(f, po_file, m_header.Charset))
{
wxLogError(_("There were errors when loading the file. Some data may be missing or corrupted as the result."));
}
POLoadParser parser(*this, &f);
parser.IgnoreHeader(flags & CreationFlag_IgnoreHeader);
parser.IgnoreTranslations(flags & CreationFlag_IgnoreTranslations);
if (!parser.Parse())
{
throw Exception(_(L"Couldn’t load the file, it is probably damaged."));
}
m_sourceLanguage = parser.GetSpecifiedMsgidLanguage(); // may be, and likely will, invalid
m_fileCRLF = GetFileCRLFFormat(f);
m_fileWrappingWidth = parser.GetWrappingWidth();
wxLogTrace("poedit", "detect line wrapping: %d", m_fileWrappingWidth);
// If we didn't find any entries, the file must be invalid:
if (!parser.FileIsValid)
{
throw Exception(_(L"Couldn’t load the file, it is probably damaged."));
}
f.Close();
FixupCommonIssues();
if ( flags & CreationFlag_IgnoreHeader )
CreateNewHeader();
}
void POCatalog::FixupCommonIssues()
{
if (m_header.Project == "PACKAGE VERSION")
m_header.Project.clear();
// In PHP use, strings with % (typically: 100%) get frequently mis-identified as php-format, because the
// format string allows space, so e.g. "100% complete" has a valid "% c" format flag in it. Work around
// this by removing the flag ourselves, as translators can rarely influence it:
for (auto& i: items())
{
if (i->GetFormatFlag() == "php")
{
auto s = i->GetRawString();
if (s.Contains(wxS("% ")) && !s.Contains(wxS("%% ")))
{
auto poi = std::dynamic_pointer_cast<POCatalogItem>(i);
poi->m_moreFlags.Replace("php-format", "no-php-format");
}
}
}
// All the following fixups are specific to POs and should *not* be done in POTs:
if (m_fileType == Type::POT)
return;