-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.cc
752 lines (720 loc) · 23.5 KB
/
io.cc
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
#include "io.hh"
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <limits.h>
#include <fstream>
#if TEG_USE_SN && !defined(__WIN32__)
#include <dirent.h>
#endif
static std::unique_ptr<std::istream>
OpenDataFileForReadStupidWindowsHack(const std::string& path);
std::unique_ptr<std::istream>
IO::OpenDataFileForRead(const std::string& path) {
std::string massaged_path(path);
auto it = massaged_path.begin();
while(it != massaged_path.end()) {
if(*it == '.' && (it == path.begin() || it[-1] == '/'))
die("Attempt to access an illegal datafile path: %s", path.c_str());
else if(*DIR_SEP != '/') {
if(*it == '/') *it = *DIR_SEP;
else if(*it == *DIR_SEP) *it = '/';
}
++it;
}
return OpenDataFileForReadStupidWindowsHack(path);
}
#ifdef __WIN32__
# include <windows.h>
# include <tchar.h>
# ifdef _UNICODE
# define perror stupidperror
# define fprintf stupidfprintf
# include <stdarg.h>
static void stupidfprintf(FILE* f, const WCHAR* format, ...) {
static WCHAR wide_buffer[1024];
static char thin_buffer[1024];
va_list arg;
va_start(arg, format);
_vsnwprintf(wide_buffer, sizeof(wide_buffer)/sizeof(WCHAR), format, arg);
va_end(arg);
WideCharToMultiByte(CP_UTF8, 0, wide_buffer, -1, thin_buffer,
sizeof(thin_buffer), NULL, NULL);
fwrite(thin_buffer, strlen(thin_buffer), 1, f);
}
static void stupidperror(const WCHAR* wat) {
stupidfprintf(stderr, L"%S: %s\n", wat, strerror(errno));
}
# endif
# define strlen _tcslen
# define strcpy _tcscpy
# define strchr _tcschr
# define strrchr _tcsrchr
# define snprintf _sntprintf
# define getenv _tgetenv
# define getcwd _tgetcwd
# define fopen _tfopen
# define freopen _tfreopen
# define rename _trename
# define remove _tremove
#else
typedef char TCHAR; //I love Windows!
# define _T(a) a
#endif
#ifdef __WIN32__
# define CONFIG_BASE_ENV "USERPROFILE"
# define CONFIG_BASE_ENV_DEFAULT "C:\\Documents and Settings\\User"
# define CONFIG_BASE_DIR "My Documents\\My Games\\" GAME_PRETTY_NAME
# define DESKTOP_BASE_ENV "USERPROFILE"
# define DESKTOP_BASE_ENV_DEFAULT "C:\\Documents and Settings\\User"
# define DESKTOP_BASE_DIR "Desktop"
#elif defined(EMSCRIPTEN)
# define CONFIG_BASE_ENV "CONFIGPATH"
# define CONFIG_BASE_ENV_DEFAULT "/Config"
# define CONFIG_BASE_DIR "."
# define DESKTOP_BASE_ENV "DESKTOPPATH"
# define DESKTOP_BASE_ENV_DEFAULT "/Desktop"
# define DESKTOP_BASE_DIR "."
#else
# define CONFIG_BASE_ENV "HOME"
# ifdef MACOSX
# define CONFIG_BASE_ENV_DEFAULT "/Users/Shared"
# define CONFIG_BASE_DIR "Library/Preferences/" GAME_PRETTY_NAME
# else
# define CONFIG_BASE_ENV_DEFAULT "/home"
# define CONFIG_BASE_DIR ".local/share/" GAME_PRETTY_NAME
# endif
# define DESKTOP_BASE_ENV "HOME"
# define DESKTOP_BASE_ENV_DEFAULT CONFIG_BASE_ENV_DEFAULT
# define DESKTOP_BASE_DIR "Desktop"
#endif
#define CONFIG_EXT ""
#define DATA_BASE_DIR "Data"
#define LANG_BASE_DIR "Lang"
extern "C" const TCHAR* g_argv0;
#if MACOSX
static TCHAR* ExecutablePathToContentsPath(TCHAR* in_path) {
if(in_path && strlen(in_path) >= 6) {
if(!strcmp(in_path + strlen(in_path) - strlen("/MacOS"), "/MacOS")) {
in_path[strlen(in_path) - strlen("/MacOS")] = 0;
in_path = (TCHAR*)safe_realloc(in_path, strlen(in_path)+1);
}
}
return in_path;
}
#else
#define ExecutablePathToContentsPath(x) x
#endif
#ifdef __WIN32__
// https://stackoverflow.com/questions/23969094/c-ifstream-long-full-path-not-working/23969243#23969243
#include <ext/stdio_filebuf.h>
class ifstream : public std::ifstream {
private:
__gnu_cxx::stdio_filebuf<char> buf_;
std::streambuf* p_original_buf_;
public:
~ifstream() {
basic_ios::rdbuf( p_original_buf_ );
buf_.close();
}
ifstream(const TCHAR* filename,
std::ios_base::openmode mode = std::ios_base::in)
: std::ifstream(),
buf_(fopen(filename, _T("rb")), mode),
p_original_buf_(nullptr) {
p_original_buf_ = basic_ios::rdbuf(&buf_);
if(!buf_.file()) setstate(badbit);
}
};
class ofstream : public std::ofstream {
private:
__gnu_cxx::stdio_filebuf<char> buf_;
std::streambuf* p_original_buf_;
public:
~ofstream() {
basic_ios::rdbuf( p_original_buf_ );
buf_.close();
}
ofstream(const TCHAR* filename,
std::ios_base::openmode mode = std::ios_base::out)
: std::ofstream(),
buf_(fopen(filename, _T("wb")), mode),
p_original_buf_(nullptr) {
p_original_buf_ = basic_ios::rdbuf(&buf_);
if(!buf_.file()) setstate(badbit);
}
};
class fstream : public std::fstream {
private:
__gnu_cxx::stdio_filebuf<char> buf_;
std::streambuf* p_original_buf_;
public:
~fstream() {
basic_ios::rdbuf( p_original_buf_ );
buf_.close();
}
fstream(const TCHAR* filename,
std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out)
: std::fstream(),
buf_(fopen(filename, _T("r+b")), mode),
p_original_buf_(nullptr) {
p_original_buf_ = basic_ios::rdbuf(&buf_);
if(!buf_.file()) setstate(badbit);
}
};
#else
using std::ifstream;
using std::ofstream;
using std::fstream;
#endif
static const TCHAR* GetSelfPath() {
static TCHAR* self_path = NULL;
if(self_path == NULL) {
#ifdef __WIN32__
/* Windows */
self_path = (TCHAR*)safe_malloc(sizeof(TCHAR) * 1024);
DWORD r = GetModuleFileName(NULL, self_path, 1024);
if(r == 0)
/* Is this the best error message? */
fprintf(stderr, _T("GetModuleFileName() failed, error code %i (We're going to need a bigger buffer?"), GetLastError());
else if(r > 1) {
TCHAR* p = strrchr(self_path, *_T(DIR_SEP));
if(p) {
*p = 0;
self_path = (TCHAR*)safe_realloc(self_path, sizeof(TCHAR) * (strlen(self_path)+1));
self_path = ExecutablePathToContentsPath(self_path);
return self_path;
}
}
/* let the more portable code handle it */
if(self_path != NULL) {
safe_free(self_path);
self_path = NULL;
}
/*
DWORD req_buf = GetCurrentDirectory(0, NULL);
self_path = (TCHAR*)safe_malloc(sizeof(TCHAR) * req_buf);
DWORD dir_return = GetCurrentDirectory(req_buf, self_path);
if(dir_return == 0) {
fprintf(stderr, _T("GetCurrentDirectory failed, error code %i"), GetLastError());
} else if(dir_return > req_buf) {
fprintf(stderr, _T("Buffer not large enough to store directory path!\n")); // need win equiv of PROC_SELF_EXE
} else {
return self_path;
}
// copying verbatim from below
if(self_path != NULL) {
safe_free(self_path);
self_path = NULL;
}
*/
#else
/* UNIX-like */
#if MACOSX || EMSCRIPTEN
#define DISABLE_PROC_SELF_EXE 1
#endif
# ifndef DISABLE_PROC_SELF_EXE
/* first, try /proc/self/exe */
# define PROC_SELF_EXE DIR_SEP "proc" DIR_SEP "self" DIR_SEP "exe"
self_path = (TCHAR*)safe_malloc(sizeof(TCHAR) * (PATH_MAX+1));
ssize_t r = readlink(PROC_SELF_EXE, self_path, PATH_MAX);
if(r < 0)
perror(_T(PROC_SELF_EXE));
else {
self_path[r] = 0;
TCHAR* p = strrchr(self_path, *DIR_SEP);
if(p) {
*p = 0;
if(*self_path == 0) strcpy(self_path, DIR_SEP);
self_path = (TCHAR*)safe_realloc(self_path, strlen(self_path)+1);
self_path = ExecutablePathToContentsPath(self_path);
return self_path;
}
}
/* let the more portable code handle it */
if(self_path != NULL) {
safe_free(self_path);
self_path = NULL;
}
# endif
#endif
#ifndef DISABLE_ARGV0_PATH_EXTRACTION
if(!g_argv0)
die("g_argv0 was not set!");
else if(g_argv0) {
if(g_argv0[0] == *DIR_SEP) {
/* Absolute path. */
self_path = (TCHAR*)safe_malloc(sizeof(TCHAR) * (strlen(g_argv0)+1));
strcpy(self_path, g_argv0);
TCHAR* p = strrchr(self_path, *DIR_SEP);
if(p) {
*p = 0;
if(*self_path == 0) strcpy(self_path, _T("/"));
self_path = (TCHAR*)safe_realloc(self_path, strlen(self_path)+1);
self_path = ExecutablePathToContentsPath(self_path);
return self_path;
}
}
else if(strchr(g_argv0, *DIR_SEP)) {
/* Relative path. */
size_t path_len = 32;
while(1) {
self_path = (TCHAR*)safe_realloc(self_path, path_len);
if(getcwd(self_path, path_len) != NULL) break;
path_len *= 2;
if(path_len > 65536) die("Absurdly long working directory.");
}
path_len = strlen(self_path);
self_path = (TCHAR*)safe_realloc(self_path, path_len + strlen(g_argv0) + 2);
self_path[path_len] = '/';
strcpy(self_path + path_len + 1, g_argv0);
TCHAR* p = strrchr(self_path, *DIR_SEP);
if(p) {
*p = 0;
if(*self_path == 0) strcpy(self_path, _T("/"));
self_path = (TCHAR*)safe_realloc(self_path, strlen(self_path)+1);
self_path = ExecutablePathToContentsPath(self_path);
return self_path;
}
}
else {
/* Path in $PATH. */
/* We're not smart, let the user help. Fall through... */
}
}
/* give up */
if(self_path != NULL) {
safe_free(self_path);
self_path = NULL;
}
#endif
#if EMSCRIPTEN
self_path = const_cast<TCHAR*>(_T("."));
#endif
if(self_path == NULL) {
fprintf(stderr, _T("Unable to find the path to ourselves, using the working directory!\n"));
// won't actually be modified, so discarding const is okay
self_path = const_cast<TCHAR*>(_T("."));
}
}
return self_path;
}
static void clean_dirseps(TCHAR* p) {
TCHAR* q = p;
while(*p == *DIR_SEP) {
/* account for UNC paths */
*q++ = *p++;
}
while(*p) {
if(*p == *DIR_SEP) {
*q++ = *DIR_SEP;
while(*++p == *DIR_SEP)
;
}
else *q++ = *p++;
}
*q++ = 0;
}
/* return true if the attempt succeeded */
static bool try_recursive_mkdir(TCHAR* path) {
TCHAR* p = strrchr(path, *DIR_SEP);
if(!p || p == path) return false;
*p = 0;
bool ret = false;
#ifdef __WIN32__
if(CreateDirectory(path, NULL)) ret = true;
else if(GetLastError() == ERROR_PATH_NOT_FOUND && try_recursive_mkdir(path)
&& CreateDirectory(path, NULL)) ret = true;
/* # error Implement for Windows */
#else
if(mkdir(path, 0755) == 0) ret = true;
else if(errno == ENOENT && try_recursive_mkdir(path)
&& mkdir(path, 0755) == 0) ret = true;
#endif
*p = *DIR_SEP;
return ret;
}
static TCHAR* get_data_path(const char* in_filename) {
TCHAR* filename;
#if __WIN32__ && _UNICODE
int string_length = MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, NULL, 0);
filename = reinterpret_cast<TCHAR*>(safe_malloc(string_length * sizeof(TCHAR)));
MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, filename, string_length);
#else
/* won't actually be modified... thank you so much, Windows~ */
filename = const_cast<char*>(in_filename);
#endif
const TCHAR* self_path = GetSelfPath();
size_t len = strlen(self_path) + strlen(_T(DATA_BASE_DIR)) + strlen(filename) + 3;
TCHAR* path = (TCHAR*)safe_malloc(len * sizeof(TCHAR));
snprintf(path, len, _T("%s" DIR_SEP DATA_BASE_DIR DIR_SEP "%s"),
self_path, filename);
clean_dirseps(path);
#if __WIN32__ && _UNICODE
safe_free(filename);
#endif
return path;
}
std::unique_ptr<std::istream>
OpenDataFileForReadStupidWindowsHack(const std::string& filename) {
TCHAR* path = get_data_path(filename.c_str());
std::unique_ptr<std::istream> ret(new ifstream(path,
std::ios::binary
|std::ios::in));
if(!ret->good()) {
perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
static TCHAR* get_raw_path(const char* in_path) {
TCHAR* path;
#if __WIN32__ && _UNICODE
int string_length = MultiByteToWideChar(CP_UTF8, 0, in_path, -1, NULL, 0);
path = reinterpret_cast<TCHAR*>(safe_malloc(string_length * sizeof(TCHAR)));
MultiByteToWideChar(CP_UTF8, 0, in_path, -1, path, string_length);
#else
path = teg_strdup(in_path);
#endif
clean_dirseps(path);
return path;
}
std::unique_ptr<std::istream>
IO::OpenRawPathForRead(const std::string& filename, bool log_error) {
TCHAR* path = get_raw_path(filename.c_str());
std::unique_ptr<std::istream> ret(new ifstream(path,
std::ios::binary
|std::ios::in));
if(!ret->good()) {
if(log_error) perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
std::unique_ptr<std::ostream>
IO::OpenRawPathForWrite(const std::string& filename, bool log_error) {
TCHAR* path = get_raw_path(filename.c_str());
std::unique_ptr<std::ostream> ret(new ofstream(path,
std::ios::binary
|std::ios::out));
if(!ret->good()) {
if(log_error) perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
std::unique_ptr<std::iostream>
IO::OpenRawPathForUpdate(const std::string& filename, bool log_error) {
TCHAR* path = get_raw_path(filename.c_str());
std::unique_ptr<std::iostream> ret(new fstream(path,
std::ios::binary
|std::ios::out
|std::ios::in));
if(!ret->good()) {
if(log_error) perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
enum path_type {
NORMAL, BACKUP, EDIT
};
static TCHAR* get_config_path(const char* in_filename, path_type wat=NORMAL) {
TCHAR* filename;
#if __WIN32__ && _UNICODE
int string_length = MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, NULL, 0);
filename = reinterpret_cast<TCHAR*>(safe_malloc(string_length * sizeof(TCHAR)));
MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, filename, string_length);
#else
/* won't actually be modified... thank you so much, Windows~ */
filename = const_cast<char*>(in_filename);
#endif
const TCHAR* home = getenv(_T(CONFIG_BASE_ENV));
if(!home) home = _T(CONFIG_BASE_ENV_DEFAULT);
size_t len = strlen(home) + strlen(_T(CONFIG_BASE_DIR)) + strlen(_T(CONFIG_EXT)) + strlen(filename) + (wat == NORMAL ? 0 : 1) + 3;
TCHAR* path = (TCHAR*)safe_malloc(len * sizeof(TCHAR));
snprintf(path, len, _T("%s" DIR_SEP CONFIG_BASE_DIR DIR_SEP "%s" CONFIG_EXT "%s"),
home, filename, wat == BACKUP ? _T("~") : wat == EDIT ? _T("^") : _T(""));
clean_dirseps(path);
#if __WIN32__ && _UNICODE
safe_free(filename);
#endif
return path;
}
std::unique_ptr<std::istream>
IO::OpenConfigFileForRead(const std::string& filename) {
TCHAR* path = get_config_path(filename.c_str());
std::unique_ptr<std::istream> ret(new ifstream(path,
std::ios::binary
|std::ios::in));
if(!ret->good() && errno == ENOENT) {
safe_free(path);
path = get_config_path(filename.c_str(), BACKUP);
ret = std::unique_ptr<std::istream>(new ifstream(path,
std::ios::binary
|std::ios::in));
}
if(!ret->good()) {
if(errno != ENOENT) perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
std::unique_ptr<std::ostream>
IO::OpenConfigFileForWrite(const std::string& filename) {
TCHAR* path = get_config_path(filename.c_str(), EDIT);
std::unique_ptr<std::ostream> ret(new ofstream(path,
std::ios::binary
|std::ios::out));
if(!ret->good() && errno == ENOENT && try_recursive_mkdir(path)) {
ret->clear();
ret = std::unique_ptr<std::ostream>(new ofstream(path,
std::ios::binary
|std::ios::in));
}
if(!ret->good()) {
perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
std::string IO::GetConfigFilePath(const std::string& filename) {
#if __WIN32__ && _UNICODE
TCHAR* tpath = get_config_path(filename.c_str());
char* path;
int string_length = WideCharToMultiByte(CP_UTF8, 0, tpath, -1, NULL, 0,
NULL, NULL);
path = reinterpret_cast<char*>(safe_malloc(string_length));
WideCharToMultiByte(CP_UTF8, 0, tpath, -1, path, string_length,
NULL, NULL);
safe_free(tpath);
#else
/* won't actually be modified... thank you so much, Windows~ */
char* path = get_config_path(filename.c_str());
#endif
std::string ret(path);
safe_free(path);
return ret;
}
void IO::TryCreateConfigDirectory() {
TCHAR* path = get_config_path("Missingfi");
try_recursive_mkdir(path);
safe_free(path);
}
void IO::UpdateConfigFile(const std::string& filename) {
TCHAR* path_normal = get_config_path(filename.c_str(), NORMAL);
TCHAR* path_backup = get_config_path(filename.c_str(), BACKUP);
TCHAR* path_edit = get_config_path(filename.c_str(), EDIT);
/* optimistically assume success on all the below operations */
/* TODO: fsync/_commit this file */
remove(path_backup);
rename(path_normal, path_backup);
rename(path_edit, path_normal);
safe_free(path_normal);
safe_free(path_backup);
safe_free(path_edit);
}
#if __WIN32__
static TCHAR* get_relative_path(const char* in_filename) {
TCHAR* filename;
#if _UNICODE
int string_length = MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, NULL, 0);
filename = reinterpret_cast<TCHAR*>(safe_malloc(string_length * sizeof(TCHAR)));
MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, filename, string_length);
#else
/* won't actually be modified... thank you so much, Windows~ */
filename = const_cast<char*>(in_filename);
#endif
const TCHAR* self_path = GetSelfPath();
size_t len = strlen(self_path) + strlen(filename) + 2;
TCHAR* path = (TCHAR*)safe_malloc(len * sizeof(TCHAR));
snprintf(path, len, _T("%s" DIR_SEP "%s"),
self_path, filename);
clean_dirseps(path);
#if _UNICODE
safe_free(filename);
#endif
return path;
}
void IO::DoRedirectOutput() {
/* lots of copy-pasting here... */
TCHAR* path = get_relative_path("stdout.utxt");
if(!freopen(path, _T("wb"), stdout)) {
safe_free(path);
path = get_config_path("stdout.utxt");
if(!freopen(path, _T("wb"), stdout)) {
if(errno == ENOENT) {
if(!try_recursive_mkdir(path)) return; // If try_recursive_mkdir failed, attempting to redirect stderr is pointless
freopen(path, _T("wb"), stdout);
}
/* if it failed, oh well */
}
}
safe_free(path);
path = get_relative_path("stderr.utxt");
if(!freopen(path, _T("wb"), stderr)) {
safe_free(path);
path = get_config_path("stderr.utxt");
freopen(path, _T("wb"), stderr);
/* don't try_recursive_mkdir again because why would that even happen? */
}
safe_free(path);
}
#endif
static TCHAR* get_desktop_path(const char* in_filename) {
TCHAR* filename;
#if __WIN32__ && _UNICODE
int string_length = MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, NULL, 0);
filename = reinterpret_cast<TCHAR*>(safe_malloc(string_length * sizeof(TCHAR)));
MultiByteToWideChar(CP_UTF8, 0, in_filename, -1, filename, string_length);
#else
/* won't actually be modified... thank you so much, Windows~ */
filename = const_cast<char*>(in_filename);
#endif
const TCHAR* home = getenv(_T(DESKTOP_BASE_ENV));
if(!home) home = _T(DESKTOP_BASE_ENV_DEFAULT);
size_t len = strlen(home) + strlen(_T(DESKTOP_BASE_DIR)) + strlen(filename) + 3;
TCHAR* path = (TCHAR*)safe_malloc(len * sizeof(TCHAR));
snprintf(path, len, _T("%s" DIR_SEP DESKTOP_BASE_DIR DIR_SEP "%s"),
home, filename);
clean_dirseps(path);
#if __WIN32__ && _UNICODE
safe_free(filename);
#endif
return path;
}
std::unique_ptr<std::ostream>
IO::OpenDesktopFileForWrite(const std::string& filename) {
TCHAR* path = get_desktop_path(filename.c_str());
{
ifstream check(path, std::ios::binary|std::ios::in);
if(check.good()) {
safe_free(path);
return nullptr;
}
}
std::unique_ptr<std::ostream> ret(new ofstream(path,
std::ios::binary
|std::ios::out));
if(!ret->good() && errno == ENOENT && try_recursive_mkdir(path)) {
ret->clear();
ret = std::unique_ptr<std::ostream>(new ofstream(path,
std::ios::binary
|std::ios::in));
}
if(!ret->good()) {
perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
#if TEG_USE_SN
namespace {
class TegCatSource : public SN::CatSource {
static const std::string SUFFIX;
TCHAR* base_path;
#ifdef __WIN32__
TCHAR* base_pattern;
#endif
public:
TegCatSource() {
base_path = get_data_path(LANG_BASE_DIR DIR_SEP);
#ifdef __WIN32__
base_pattern = get_data_path(LANG_BASE_DIR DIR_SEP "*");
#endif
}
~TegCatSource() {
if(base_path != nullptr) safe_free(base_path);
#ifdef __WIN32__
if(base_pattern != nullptr) safe_free(base_pattern);
#endif
}
void GetAvailableCats(std::function<void(std::string)> func) {
#ifdef __WIN32__
struct _tfinddata_t ent;
intptr_t handle = _tfindfirst(base_pattern, &ent);
if(handle != -1) {
do {
if(ent.name[0] == '.'
|| (ent.attrib & (_A_HIDDEN|_A_SUBDIR))) continue;
#if _UNICODE
int len = WideCharToMultiByte(CP_UTF8, 0, ent.name, -1, nullptr, 0,
nullptr, nullptr);
if(len > 0) --len;
char* thin_buffer = reinterpret_cast<char*>(safe_malloc(len));
WideCharToMultiByte(CP_UTF8, 0, ent.name, -1, thin_buffer, len,
nullptr, nullptr);
std::string name(thin_buffer, thin_buffer + len);
safe_free(thin_buffer);
#else
std::string name(ent.name);
#endif
if(name.compare(name.length()-SUFFIX.length(), name.length(),
SUFFIX) != 0) continue;
std::string code(name.begin(),
name.begin()+(name.length()-SUFFIX.length()));
for(auto& c : code) {
if(c == '-') continue;
else if(c == '_') c = '-';
}
if(SN::IsValidLanguageCode(code)) func(std::move(code));
} while(_tfindnext(handle, &ent) != -1);
_findclose(handle);
}
#else
DIR* d = opendir(base_path);
if(d) {
struct dirent* ent;
while((ent = readdir(d))) {
if(ent->d_name[0] == '.'
#ifdef DT_REG
|| ent->d_type != DT_REG
#endif
) continue;
std::string name(ent->d_name);
if(name.compare(name.length()-SUFFIX.length(), name.length(),
SUFFIX) != 0)
continue;
std::string code(name.begin(),
name.begin()+(name.length()-SUFFIX.length()));
for(auto& c : code) {
if(c == '-') continue;
else if(c == '_') c = '-';
}
if(SN::IsValidLanguageCode(code)) func(std::move(code));
}
closedir(d);
}
#endif
}
std::unique_ptr<std::istream> OpenCat(const std::string& cat) {
std::string path_string(LANG_BASE_DIR DIR_SEP + cat + SUFFIX);
TCHAR* path = get_data_path(path_string.c_str());
std::unique_ptr<std::istream> ret(new ifstream(path,
std::ios::binary
|std::ios::in));
if(!ret->good()) {
perror(path);
ret.reset();
}
safe_free(path);
return ret;
}
};
#ifndef TEG_SN_CAT_EXTENSION
#define TEG_SN_CAT_EXTENSION ".utxt"
#endif
const std::string TegCatSource::SUFFIX(TEG_SN_CAT_EXTENSION);
}
std::unique_ptr<SN::CatSource> IO::GetSNCatSource() {
return std::make_unique<TegCatSource>();
}
#endif