-
Notifications
You must be signed in to change notification settings - Fork 803
/
Copy pathfilemanager.cpp
2017 lines (1754 loc) · 69.5 KB
/
filemanager.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
/******************************************************************************
* Project: PROJ
* Purpose: File manager
* Author: Even Rouault, <even.rouault at spatialys.com>
*
******************************************************************************
* Copyright (c) 2019, Even Rouault, <even.rouault at spatialys.com>
*
* 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.
*****************************************************************************/
#ifndef FROM_PROJ_CPP
#define FROM_PROJ_CPP
#endif
#define LRU11_DO_NOT_DEFINE_OUT_OF_CLASS_METHODS
#include <errno.h>
#include <stdlib.h>
#include <algorithm>
#include <limits>
#include <string>
#include "filemanager.hpp"
#include "proj.h"
#include "proj/internal/internal.hpp"
#include "proj/internal/io_internal.hpp"
#include "proj/io.hpp"
#include "proj_internal.h"
#include <sys/stat.h>
#include "proj_config.h"
#ifdef _WIN32
#include <shlobj.h>
#include <windows.h>
#else
#ifdef HAVE_LIBDL
#include <dlfcn.h>
#endif
#include <sys/types.h>
#include <unistd.h>
#endif
//! @cond Doxygen_Suppress
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
using namespace NS_PROJ::internal;
NS_PROJ_START
// ---------------------------------------------------------------------------
File::File(const std::string &filename) : name_(filename) {}
// ---------------------------------------------------------------------------
File::~File() = default;
// ---------------------------------------------------------------------------
std::string File::read_line(size_t maxLen, bool &maxLenReached,
bool &eofReached) {
constexpr size_t MAX_MAXLEN = 1024 * 1024;
maxLen = std::min(maxLen, MAX_MAXLEN);
while (true) {
// Consume existing lines in buffer
size_t pos = readLineBuffer_.find_first_of("\r\n");
if (pos != std::string::npos) {
if (pos > maxLen) {
std::string ret(readLineBuffer_.substr(0, maxLen));
readLineBuffer_ = readLineBuffer_.substr(maxLen);
maxLenReached = true;
eofReached = false;
return ret;
}
std::string ret(readLineBuffer_.substr(0, pos));
if (readLineBuffer_[pos] == '\r' &&
readLineBuffer_[pos + 1] == '\n') {
pos += 1;
}
readLineBuffer_ = readLineBuffer_.substr(pos + 1);
maxLenReached = false;
eofReached = false;
return ret;
}
const size_t prevSize = readLineBuffer_.size();
if (maxLen <= prevSize) {
std::string ret(readLineBuffer_.substr(0, maxLen));
readLineBuffer_ = readLineBuffer_.substr(maxLen);
maxLenReached = true;
eofReached = false;
return ret;
}
if (eofReadLine_) {
std::string ret = readLineBuffer_;
readLineBuffer_.clear();
maxLenReached = false;
eofReached = ret.empty();
return ret;
}
readLineBuffer_.resize(maxLen);
const size_t nRead =
read(&readLineBuffer_[prevSize], maxLen - prevSize);
if (nRead < maxLen - prevSize)
eofReadLine_ = true;
readLineBuffer_.resize(prevSize + nRead);
}
}
// ---------------------------------------------------------------------------
#ifdef _WIN32
/* The bulk of utf8towc()/utf8fromwc() is derived from the utf.c module from
* FLTK. It was originally downloaded from:
* http://svn.easysw.com/public/fltk/fltk/trunk/src/utf.c
* And already used by GDAL
*/
/************************************************************************/
/* ==================================================================== */
/* UTF.C code from FLTK with some modifications. */
/* ==================================================================== */
/************************************************************************/
/* Set to 1 to turn bad UTF8 bytes into ISO-8859-1. If this is to zero
they are instead turned into the Unicode REPLACEMENT CHARACTER, of
value 0xfffd.
If this is on utf8decode will correctly map most (perhaps all)
human-readable text that is in ISO-8859-1. This may allow you
to completely ignore character sets in your code because virtually
everything is either ISO-8859-1 or UTF-8.
*/
#define ERRORS_TO_ISO8859_1 1
/* Set to 1 to turn bad UTF8 bytes in the 0x80-0x9f range into the
Unicode index for Microsoft's CP1252 character set. You should
also set ERRORS_TO_ISO8859_1. With this a huge amount of more
available text (such as all web pages) are correctly converted
to Unicode.
*/
#define ERRORS_TO_CP1252 1
/* A number of Unicode code points are in fact illegal and should not
be produced by a UTF-8 converter. Turn this on will replace the
bytes in those encodings with errors. If you do this then converting
arbitrary 16-bit data to UTF-8 and then back is not an identity,
which will probably break a lot of software.
*/
#define STRICT_RFC3629 0
#if ERRORS_TO_CP1252
// Codes 0x80..0x9f from the Microsoft CP1252 character set, translated
// to Unicode:
constexpr unsigned short cp1252[32] = {
0x20ac, 0x0081, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021,
0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f,
0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178};
#endif
/************************************************************************/
/* utf8decode() */
/************************************************************************/
/*
Decode a single UTF-8 encoded character starting at \e p. The
resulting Unicode value (in the range 0-0x10ffff) is returned,
and \e len is set the number of bytes in the UTF-8 encoding
(adding \e len to \e p will point at the next character).
If \a p points at an illegal UTF-8 encoding, including one that
would go past \e end, or where a code is uses more bytes than
necessary, then *reinterpret_cast<const unsigned char*>(p) is translated as
though it is
in the Microsoft CP1252 character set and \e len is set to 1.
Treating errors this way allows this to decode almost any
ISO-8859-1 or CP1252 text that has been mistakenly placed where
UTF-8 is expected, and has proven very useful.
If you want errors to be converted to error characters (as the
standards recommend), adding a test to see if the length is
unexpectedly 1 will work:
\code
if( *p & 0x80 )
{ // What should be a multibyte encoding.
code = utf8decode(p, end, &len);
if( len<2 ) code = 0xFFFD; // Turn errors into REPLACEMENT CHARACTER.
}
else
{ // Handle the 1-byte utf8 encoding:
code = *p;
len = 1;
}
\endcode
Direct testing for the 1-byte case (as shown above) will also
speed up the scanning of strings where the majority of characters
are ASCII.
*/
static unsigned utf8decode(const char *p, const char *end, int *len) {
unsigned char c = *reinterpret_cast<const unsigned char *>(p);
if (c < 0x80) {
*len = 1;
return c;
#if ERRORS_TO_CP1252
} else if (c < 0xa0) {
*len = 1;
return cp1252[c - 0x80];
#endif
} else if (c < 0xc2) {
goto FAIL;
}
if (p + 1 >= end || (p[1] & 0xc0) != 0x80)
goto FAIL;
if (c < 0xe0) {
*len = 2;
return ((p[0] & 0x1f) << 6) + ((p[1] & 0x3f));
} else if (c == 0xe0) {
if ((reinterpret_cast<const unsigned char *>(p))[1] < 0xa0)
goto FAIL;
goto UTF8_3;
#if STRICT_RFC3629
} else if (c == 0xed) {
// RFC 3629 says surrogate chars are illegal.
if ((reinterpret_cast<const unsigned char *>(p))[1] >= 0xa0)
goto FAIL;
goto UTF8_3;
} else if (c == 0xef) {
// 0xfffe and 0xffff are also illegal characters.
if ((reinterpret_cast<const unsigned char *>(p))[1] == 0xbf &&
(reinterpret_cast<const unsigned char *>(p))[2] >= 0xbe)
goto FAIL;
goto UTF8_3;
#endif
} else if (c < 0xf0) {
UTF8_3:
if (p + 2 >= end || (p[2] & 0xc0) != 0x80)
goto FAIL;
*len = 3;
return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + ((p[2] & 0x3f));
} else if (c == 0xf0) {
if ((reinterpret_cast<const unsigned char *>(p))[1] < 0x90)
goto FAIL;
goto UTF8_4;
} else if (c < 0xf4) {
UTF8_4:
if (p + 3 >= end || (p[2] & 0xc0) != 0x80 || (p[3] & 0xc0) != 0x80)
goto FAIL;
*len = 4;
#if STRICT_RFC3629
// RFC 3629 says all codes ending in fffe or ffff are illegal:
if ((p[1] & 0xf) == 0xf &&
(reinterpret_cast<const unsigned char *>(p))[2] == 0xbf &&
(reinterpret_cast<const unsigned char *>(p))[3] >= 0xbe)
goto FAIL;
#endif
return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12) +
((p[2] & 0x3f) << 6) + ((p[3] & 0x3f));
} else if (c == 0xf4) {
if ((reinterpret_cast<const unsigned char *>(p))[1] > 0x8f)
goto FAIL; // After 0x10ffff.
goto UTF8_4;
} else {
FAIL:
*len = 1;
#if ERRORS_TO_ISO8859_1
return c;
#else
return 0xfffd; // Unicode REPLACEMENT CHARACTER
#endif
}
}
/************************************************************************/
/* utf8towc() */
/************************************************************************/
/* Convert a UTF-8 sequence into an array of wchar_t. These
are used by some system calls, especially on Windows.
\a src points at the UTF-8, and \a srclen is the number of bytes to
convert.
\a dst points at an array to write, and \a dstlen is the number of
locations in this array. At most \a dstlen-1 words will be
written there, plus a 0 terminating word. Thus this function
will never overwrite the buffer and will always return a
zero-terminated string. If \a dstlen is zero then \a dst can be
null and no data is written, but the length is returned.
The return value is the number of words that \e would be written
to \a dst if it were long enough, not counting the terminating
zero. If the return value is greater or equal to \a dstlen it
indicates truncation, you can then allocate a new array of size
return+1 and call this again.
Errors in the UTF-8 are converted as though each byte in the
erroneous string is in the Microsoft CP1252 encoding. This allows
ISO-8859-1 text mistakenly identified as UTF-8 to be printed
correctly.
Notice that sizeof(wchar_t) is 2 on Windows and is 4 on Linux
and most other systems. Where wchar_t is 16 bits, Unicode
characters in the range 0x10000 to 0x10ffff are converted to
"surrogate pairs" which take two words each (this is called UTF-16
encoding). If wchar_t is 32 bits this rather nasty problem is
avoided.
*/
static unsigned utf8towc(const char *src, unsigned srclen, wchar_t *dst,
unsigned dstlen) {
const char *p = src;
const char *e = src + srclen;
unsigned count = 0;
if (dstlen)
while (true) {
if (p >= e) {
dst[count] = 0;
return count;
}
if (!(*p & 0x80)) {
// ASCII
dst[count] = *p++;
} else {
int len = 0;
unsigned ucs = utf8decode(p, e, &len);
p += len;
#ifdef _WIN32
if (ucs < 0x10000) {
dst[count] = static_cast<wchar_t>(ucs);
} else {
// Make a surrogate pair:
if (count + 2 >= dstlen) {
dst[count] = 0;
count += 2;
break;
}
dst[count] = static_cast<wchar_t>(
(((ucs - 0x10000u) >> 10) & 0x3ff) | 0xd800);
dst[++count] = static_cast<wchar_t>((ucs & 0x3ff) | 0xdc00);
}
#else
dst[count] = static_cast<wchar_t>(ucs);
#endif
}
if (++count == dstlen) {
dst[count - 1] = 0;
break;
}
}
// We filled dst, measure the rest:
while (p < e) {
if (!(*p & 0x80)) {
p++;
} else {
int len = 0;
#ifdef _WIN32
const unsigned ucs = utf8decode(p, e, &len);
p += len;
if (ucs >= 0x10000)
++count;
#else
utf8decode(p, e, &len);
p += len;
#endif
}
++count;
}
return count;
}
// ---------------------------------------------------------------------------
struct NonValidUTF8Exception : public std::exception {};
// May throw exceptions
static std::wstring UTF8ToWString(const std::string &str) {
std::wstring wstr;
wstr.resize(str.size());
wstr.resize(utf8towc(str.data(), static_cast<unsigned>(str.size()),
&wstr[0], static_cast<unsigned>(wstr.size()) + 1));
for (const auto ch : wstr) {
if (ch == 0xfffd) {
throw NonValidUTF8Exception();
}
}
return wstr;
}
// ---------------------------------------------------------------------------
/************************************************************************/
/* utf8fromwc() */
/************************************************************************/
/* Turn "wide characters" as returned by some system calls
(especially on Windows) into UTF-8.
Up to \a dstlen bytes are written to \a dst, including a null
terminator. The return value is the number of bytes that would be
written, not counting the null terminator. If greater or equal to
\a dstlen then if you malloc a new array of size n+1 you will have
the space needed for the entire string. If \a dstlen is zero then
nothing is written and this call just measures the storage space
needed.
\a srclen is the number of words in \a src to convert. On Windows
this is not necessarily the number of characters, due to there
possibly being "surrogate pairs" in the UTF-16 encoding used.
On Unix wchar_t is 32 bits and each location is a character.
On Unix if a src word is greater than 0x10ffff then this is an
illegal character according to RFC 3629. These are converted as
though they are 0xFFFD (REPLACEMENT CHARACTER). Characters in the
range 0xd800 to 0xdfff, or ending with 0xfffe or 0xffff are also
illegal according to RFC 3629. However I encode these as though
they are legal, so that utf8towc will return the original data.
On Windows "surrogate pairs" are converted to a single character
and UTF-8 encoded (as 4 bytes). Mismatched halves of surrogate
pairs are converted as though they are individual characters.
*/
static unsigned int utf8fromwc(char *dst, unsigned dstlen, const wchar_t *src,
unsigned srclen) {
unsigned int i = 0;
unsigned int count = 0;
if (dstlen)
while (true) {
if (i >= srclen) {
dst[count] = 0;
return count;
}
unsigned int ucs = src[i++];
if (ucs < 0x80U) {
dst[count++] = static_cast<char>(ucs);
if (count >= dstlen) {
dst[count - 1] = 0;
break;
}
} else if (ucs < 0x800U) {
// 2 bytes.
if (count + 2 >= dstlen) {
dst[count] = 0;
count += 2;
break;
}
dst[count++] = 0xc0 | static_cast<char>(ucs >> 6);
dst[count++] = 0x80 | static_cast<char>(ucs & 0x3F);
#ifdef _WIN32
} else if (ucs >= 0xd800 && ucs <= 0xdbff && i < srclen &&
src[i] >= 0xdc00 && src[i] <= 0xdfff) {
// Surrogate pair.
unsigned int ucs2 = src[i++];
ucs = 0x10000U + ((ucs & 0x3ff) << 10) + (ucs2 & 0x3ff);
// All surrogate pairs turn into 4-byte utf8.
#else
} else if (ucs >= 0x10000) {
if (ucs > 0x10ffff) {
ucs = 0xfffd;
goto J1;
}
#endif
if (count + 4 >= dstlen) {
dst[count] = 0;
count += 4;
break;
}
dst[count++] = 0xf0 | static_cast<char>(ucs >> 18);
dst[count++] = 0x80 | static_cast<char>((ucs >> 12) & 0x3F);
dst[count++] = 0x80 | static_cast<char>((ucs >> 6) & 0x3F);
dst[count++] = 0x80 | static_cast<char>(ucs & 0x3F);
} else {
#ifndef _WIN32
J1:
#endif
// All others are 3 bytes:
if (count + 3 >= dstlen) {
dst[count] = 0;
count += 3;
break;
}
dst[count++] = 0xe0 | static_cast<char>(ucs >> 12);
dst[count++] = 0x80 | static_cast<char>((ucs >> 6) & 0x3F);
dst[count++] = 0x80 | static_cast<char>(ucs & 0x3F);
}
}
// We filled dst, measure the rest:
while (i < srclen) {
unsigned int ucs = src[i++];
if (ucs < 0x80U) {
count++;
} else if (ucs < 0x800U) {
// 2 bytes.
count += 2;
#ifdef _WIN32
} else if (ucs >= 0xd800 && ucs <= 0xdbff && i < srclen - 1 &&
src[i + 1] >= 0xdc00 && src[i + 1] <= 0xdfff) {
// Surrogate pair.
++i;
#else
} else if (ucs >= 0x10000 && ucs <= 0x10ffff) {
#endif
count += 4;
} else {
count += 3;
}
}
return count;
}
// ---------------------------------------------------------------------------
static std::string WStringToUTF8(const std::wstring &wstr) {
std::string str;
str.resize(wstr.size());
str.resize(utf8fromwc(&str[0], static_cast<unsigned>(str.size() + 1),
wstr.data(), static_cast<unsigned>(wstr.size())));
return str;
}
// ---------------------------------------------------------------------------
static std::string Win32Recode(const char *src, unsigned src_code_page,
unsigned dst_code_page) {
// Convert from source code page to Unicode.
// Compute the length in wide characters.
int wlen = MultiByteToWideChar(src_code_page, MB_ERR_INVALID_CHARS, src, -1,
nullptr, 0);
if (wlen == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
return std::string();
}
// Do the actual conversion.
std::wstring wbuf;
wbuf.resize(wlen);
MultiByteToWideChar(src_code_page, 0, src, -1, &wbuf[0], wlen);
// Convert from Unicode to destination code page.
// Compute the length in chars.
int len = WideCharToMultiByte(dst_code_page, 0, &wbuf[0], -1, nullptr, 0,
nullptr, nullptr);
// Do the actual conversion.
std::string out;
out.resize(len);
WideCharToMultiByte(dst_code_page, 0, &wbuf[0], -1, &out[0], len, nullptr,
nullptr);
out.resize(strlen(out.c_str()));
return out;
}
// ---------------------------------------------------------------------------
class FileWin32 : public File {
PJ_CONTEXT *m_ctx;
HANDLE m_handle;
FileWin32(const FileWin32 &) = delete;
FileWin32 &operator=(const FileWin32 &) = delete;
protected:
FileWin32(const std::string &name, PJ_CONTEXT *ctx, HANDLE handle)
: File(name), m_ctx(ctx), m_handle(handle) {}
public:
~FileWin32() override;
size_t read(void *buffer, size_t sizeBytes) override;
size_t write(const void *buffer, size_t sizeBytes) override;
bool seek(unsigned long long offset, int whence = SEEK_SET) override;
unsigned long long tell() override;
void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; }
// We may lie, but the real use case is only for network files
bool hasChanged() const override { return false; }
static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access);
};
// ---------------------------------------------------------------------------
FileWin32::~FileWin32() { CloseHandle(m_handle); }
// ---------------------------------------------------------------------------
size_t FileWin32::read(void *buffer, size_t sizeBytes) {
DWORD dwSizeRead = 0;
size_t nResult = 0;
if (!ReadFile(m_handle, buffer, static_cast<DWORD>(sizeBytes), &dwSizeRead,
nullptr))
nResult = 0;
else
nResult = dwSizeRead;
return nResult;
}
// ---------------------------------------------------------------------------
size_t FileWin32::write(const void *buffer, size_t sizeBytes) {
DWORD dwSizeWritten = 0;
size_t nResult = 0;
if (!WriteFile(m_handle, buffer, static_cast<DWORD>(sizeBytes),
&dwSizeWritten, nullptr))
nResult = 0;
else
nResult = dwSizeWritten;
return nResult;
}
// ---------------------------------------------------------------------------
bool FileWin32::seek(unsigned long long offset, int whence) {
LONG dwMoveMethod, dwMoveHigh;
uint32_t nMoveLow;
LARGE_INTEGER li;
switch (whence) {
case SEEK_CUR:
dwMoveMethod = FILE_CURRENT;
break;
case SEEK_END:
dwMoveMethod = FILE_END;
break;
case SEEK_SET:
default:
dwMoveMethod = FILE_BEGIN;
break;
}
li.QuadPart = offset;
nMoveLow = li.LowPart;
dwMoveHigh = li.HighPart;
SetLastError(0);
SetFilePointer(m_handle, nMoveLow, &dwMoveHigh, dwMoveMethod);
return GetLastError() == NO_ERROR;
}
// ---------------------------------------------------------------------------
unsigned long long FileWin32::tell() {
LARGE_INTEGER li;
li.HighPart = 0;
li.LowPart = SetFilePointer(m_handle, 0, &(li.HighPart), FILE_CURRENT);
return static_cast<unsigned long long>(li.QuadPart);
}
// ---------------------------------------------------------------------------
std::unique_ptr<File> FileWin32::open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access) {
DWORD dwDesiredAccess = access == FileAccess::READ_ONLY
? GENERIC_READ
: GENERIC_READ | GENERIC_WRITE;
DWORD dwCreationDisposition =
access == FileAccess::CREATE ? CREATE_ALWAYS : OPEN_EXISTING;
DWORD dwFlagsAndAttributes = (dwDesiredAccess == GENERIC_READ)
? FILE_ATTRIBUTE_READONLY
: FILE_ATTRIBUTE_NORMAL;
try {
HANDLE hFile = CreateFileW(
UTF8ToWString(std::string(filename)).c_str(), dwDesiredAccess,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
dwCreationDisposition, dwFlagsAndAttributes, nullptr);
return std::unique_ptr<File>(hFile != INVALID_HANDLE_VALUE
? new FileWin32(filename, ctx, hFile)
: nullptr);
} catch (const std::exception &e) {
pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what());
return nullptr;
}
}
#else
// ---------------------------------------------------------------------------
class FileStdio : public File {
PJ_CONTEXT *m_ctx;
FILE *m_fp;
FileStdio(const FileStdio &) = delete;
FileStdio &operator=(const FileStdio &) = delete;
protected:
FileStdio(const std::string &filename, PJ_CONTEXT *ctx, FILE *fp)
: File(filename), m_ctx(ctx), m_fp(fp) {}
public:
~FileStdio() override;
size_t read(void *buffer, size_t sizeBytes) override;
size_t write(const void *buffer, size_t sizeBytes) override;
bool seek(unsigned long long offset, int whence = SEEK_SET) override;
unsigned long long tell() override;
void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; }
// We may lie, but the real use case is only for network files
bool hasChanged() const override { return false; }
static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access);
};
// ---------------------------------------------------------------------------
FileStdio::~FileStdio() { fclose(m_fp); }
// ---------------------------------------------------------------------------
size_t FileStdio::read(void *buffer, size_t sizeBytes) {
return fread(buffer, 1, sizeBytes, m_fp);
}
// ---------------------------------------------------------------------------
size_t FileStdio::write(const void *buffer, size_t sizeBytes) {
return fwrite(buffer, 1, sizeBytes, m_fp);
}
// ---------------------------------------------------------------------------
bool FileStdio::seek(unsigned long long offset, int whence) {
// TODO one day: use 64-bit offset compatible API
if (offset != static_cast<unsigned long long>(static_cast<long>(offset))) {
pj_log(m_ctx, PJ_LOG_ERROR,
"Attempt at seeking to a 64 bit offset. Not supported yet");
return false;
}
return fseek(m_fp, static_cast<long>(offset), whence) == 0;
}
// ---------------------------------------------------------------------------
unsigned long long FileStdio::tell() {
// TODO one day: use 64-bit offset compatible API
return ftell(m_fp);
}
// ---------------------------------------------------------------------------
std::unique_ptr<File> FileStdio::open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access) {
auto fp = fopen(filename,
access == FileAccess::READ_ONLY
? "rb"
: access == FileAccess::READ_UPDATE ? "r+b" : "w+b");
return std::unique_ptr<File>(fp ? new FileStdio(filename, ctx, fp)
: nullptr);
}
#endif // _WIN32
// ---------------------------------------------------------------------------
#ifndef REMOVE_LEGACY_SUPPORT
class FileLegacyAdapter : public File {
PJ_CONTEXT *m_ctx;
PAFile m_fp;
FileLegacyAdapter(const FileLegacyAdapter &) = delete;
FileLegacyAdapter &operator=(const FileLegacyAdapter &) = delete;
protected:
FileLegacyAdapter(const std::string &filename, PJ_CONTEXT *ctx, PAFile fp)
: File(filename), m_ctx(ctx), m_fp(fp) {}
public:
~FileLegacyAdapter() override;
size_t read(void *buffer, size_t sizeBytes) override;
size_t write(const void *, size_t) override { return 0; }
bool seek(unsigned long long offset, int whence = SEEK_SET) override;
unsigned long long tell() override;
void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; }
// We may lie, but the real use case is only for network files
bool hasChanged() const override { return false; }
static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access);
};
// ---------------------------------------------------------------------------
FileLegacyAdapter::~FileLegacyAdapter() { pj_ctx_fclose(m_ctx, m_fp); }
// ---------------------------------------------------------------------------
size_t FileLegacyAdapter::read(void *buffer, size_t sizeBytes) {
return pj_ctx_fread(m_ctx, buffer, 1, sizeBytes, m_fp);
}
// ---------------------------------------------------------------------------
bool FileLegacyAdapter::seek(unsigned long long offset, int whence) {
if (offset != static_cast<unsigned long long>(static_cast<long>(offset))) {
pj_log(m_ctx, PJ_LOG_ERROR,
"Attempt at seeking to a 64 bit offset. Not supported yet");
return false;
}
return pj_ctx_fseek(m_ctx, m_fp, static_cast<long>(offset), whence) == 0;
}
// ---------------------------------------------------------------------------
unsigned long long FileLegacyAdapter::tell() {
return pj_ctx_ftell(m_ctx, m_fp);
}
// ---------------------------------------------------------------------------
std::unique_ptr<File>
FileLegacyAdapter::open(PJ_CONTEXT *ctx, const char *filename, FileAccess) {
auto fid = pj_ctx_fopen(ctx, filename, "rb");
return std::unique_ptr<File>(fid ? new FileLegacyAdapter(filename, ctx, fid)
: nullptr);
}
#endif // REMOVE_LEGACY_SUPPORT
// ---------------------------------------------------------------------------
class FileApiAdapter : public File {
PJ_CONTEXT *m_ctx;
PROJ_FILE_HANDLE *m_fp;
FileApiAdapter(const FileApiAdapter &) = delete;
FileApiAdapter &operator=(const FileApiAdapter &) = delete;
protected:
FileApiAdapter(const std::string &filename, PJ_CONTEXT *ctx,
PROJ_FILE_HANDLE *fp)
: File(filename), m_ctx(ctx), m_fp(fp) {}
public:
~FileApiAdapter() override;
size_t read(void *buffer, size_t sizeBytes) override;
size_t write(const void *, size_t) override;
bool seek(unsigned long long offset, int whence = SEEK_SET) override;
unsigned long long tell() override;
void reassign_context(PJ_CONTEXT *ctx) override { m_ctx = ctx; }
// We may lie, but the real use case is only for network files
bool hasChanged() const override { return false; }
static std::unique_ptr<File> open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access);
};
// ---------------------------------------------------------------------------
FileApiAdapter::~FileApiAdapter() {
m_ctx->fileApi.close_cbk(m_ctx, m_fp, m_ctx->fileApi.user_data);
}
// ---------------------------------------------------------------------------
size_t FileApiAdapter::read(void *buffer, size_t sizeBytes) {
return m_ctx->fileApi.read_cbk(m_ctx, m_fp, buffer, sizeBytes,
m_ctx->fileApi.user_data);
}
// ---------------------------------------------------------------------------
size_t FileApiAdapter::write(const void *buffer, size_t sizeBytes) {
return m_ctx->fileApi.write_cbk(m_ctx, m_fp, buffer, sizeBytes,
m_ctx->fileApi.user_data);
}
// ---------------------------------------------------------------------------
bool FileApiAdapter::seek(unsigned long long offset, int whence) {
return m_ctx->fileApi.seek_cbk(m_ctx, m_fp, static_cast<long long>(offset),
whence, m_ctx->fileApi.user_data) != 0;
}
// ---------------------------------------------------------------------------
unsigned long long FileApiAdapter::tell() {
return m_ctx->fileApi.tell_cbk(m_ctx, m_fp, m_ctx->fileApi.user_data);
}
// ---------------------------------------------------------------------------
std::unique_ptr<File> FileApiAdapter::open(PJ_CONTEXT *ctx,
const char *filename,
FileAccess eAccess) {
PROJ_OPEN_ACCESS eCAccess = PROJ_OPEN_ACCESS_READ_ONLY;
switch (eAccess) {
case FileAccess::READ_ONLY:
// Initialized above
break;
case FileAccess::READ_UPDATE:
eCAccess = PROJ_OPEN_ACCESS_READ_UPDATE;
break;
case FileAccess::CREATE:
eCAccess = PROJ_OPEN_ACCESS_CREATE;
break;
}
auto fp =
ctx->fileApi.open_cbk(ctx, filename, eCAccess, ctx->fileApi.user_data);
return std::unique_ptr<File>(fp ? new FileApiAdapter(filename, ctx, fp)
: nullptr);
}
// ---------------------------------------------------------------------------
std::unique_ptr<File> FileManager::open(PJ_CONTEXT *ctx, const char *filename,
FileAccess access) {
if (starts_with(filename, "http://") || starts_with(filename, "https://")) {
if (!proj_context_is_network_enabled(ctx)) {
pj_log(
ctx, PJ_LOG_ERROR,
"Attempt at accessing remote resource not authorized. Either "
"set PROJ_NETWORK=ON or "
"proj_context_set_enable_network(ctx, TRUE)");
return nullptr;
}
return pj_network_file_open(ctx, filename);
}
#ifndef REMOVE_LEGACY_SUPPORT
// If the user has specified a legacy fileapi, use it
if (ctx->fileapi_legacy != pj_get_default_fileapi()) {
return FileLegacyAdapter::open(ctx, filename, access);
}
#endif
if (ctx->fileApi.open_cbk != nullptr) {
return FileApiAdapter::open(ctx, filename, access);
}
#ifdef _WIN32
return FileWin32::open(ctx, filename, access);
#else
return FileStdio::open(ctx, filename, access);
#endif
}
// ---------------------------------------------------------------------------
bool FileManager::exists(PJ_CONTEXT *ctx, const char *filename) {
if (ctx->fileApi.exists_cbk) {
return ctx->fileApi.exists_cbk(ctx, filename, ctx->fileApi.user_data) !=
0;
}
#ifdef _WIN32
struct __stat64 buf;
try {
return _wstat64(UTF8ToWString(filename).c_str(), &buf) == 0;
} catch (const std::exception &e) {
pj_log(ctx, PJ_LOG_DEBUG, "%s", e.what());
return false;
}
#else
(void)ctx;
struct stat sStat;
return stat(filename, &sStat) == 0;
#endif
}
// ---------------------------------------------------------------------------
bool FileManager::mkdir(PJ_CONTEXT *ctx, const char *filename) {
if (ctx->fileApi.mkdir_cbk) {
return ctx->fileApi.mkdir_cbk(ctx, filename, ctx->fileApi.user_data) !=