forked from KhronosGroup/KTX-Software
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathktxapp.h
472 lines (406 loc) · 13.1 KB
/
ktxapp.h
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
// -*- tab-width: 4; -*-
// vi: set sw=2 ts=4 sts=4 expandtab:
// Copyright 2019-2020 The Khronos Group Inc.
// SPDX-License-Identifier: Apache-2.0
#include "stdafx.h"
#if defined (_WIN32)
#define _CRT_SECURE_NO_WARNINGS
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <stdarg.h>
#if (_MSVC_LANG >= 201703L || __cplusplus >= 201703L)
#include <algorithm>
#endif
#include <iostream>
#include <vector>
#include <ktx.h>
#include "argparser.h"
#include "platform_utils.h"
#define QUOTE(x) #x
#define STR(x) QUOTE(x)
// Thanks Windows!!!
#if defined(min)
#undef min
#endif
#if defined(max)
#undef max
#endif
using namespace std;
// clamp is in std:: from c++17.
#if !(_MSVC_LANG >= 201703L || __cplusplus >= 201703L)
template <typename T> inline T clamp(T value, T low, T high) {
return (value < low) ? low : ((value > high) ? high : value);
}
#endif
template<typename T>
struct clamped
{
clamped(T def_v, T min_v, T max_v) :
def(def_v),
min(min_v),
max(max_v),
value(def_v)
{
}
void clear()
{
value = def;
}
operator T() const
{
return value;
}
T operator= (T v)
{
value = clamp<T>(v, min, max);
return value;
}
T def;
T min;
T max;
T value;
};
/**
//! [ktxApp options]
<dl>
<dt>-h, \--help</dt>
<dd>Print this usage message and exit.</dd>
<dt>-v, \--version</dt>
<dd>Print the version number of this program and exit.</dd>
</dl>
//! [ktxApp options]
*/
class ktxApp {
public:
virtual int main(int argc, char* argv[]) = 0;
virtual void usage() {
cerr <<
" -h, --help Print this usage message and exit.\n"
" -v, --version Print the version number of this program and exit.\n"
#if defined(_WIN32) && defined(DEBUG)
" --ld Launch Visual Studio deugger at start up.\n"
#endif
;
};
string& getName() { return name; }
protected:
struct commandOptions {
std::vector<string> infiles;
string outfile;
int test;
int warn;
int launchDebugger;
commandOptions() : test(false), warn(1), launchDebugger(0) { }
};
ktxApp(std::string& version, std::string& defaultVersion,
commandOptions& options)
: version(version), defaultVersion(defaultVersion),
options(options) { }
void error(const char *pFmt, ...) {
va_list args;
va_start(args, pFmt);
cerr << name << ": ";
vfprintf(stderr, pFmt, args);
va_end(args);
cerr << "\n";
}
void warning(const char *pFmt, va_list args) {
if (options.warn) {
cerr << name << " warning! ";
vfprintf(stderr, pFmt, args);
cerr << endl;
}
}
void warning(const char *pFmt, ...) {
if (options.warn) {
va_list args;
va_start(args, pFmt);
warning(pFmt, args);
cerr << endl;
}
}
void warning(const string& msg) {
if (options.warn) {
cerr << name << " warning! ";
cerr << msg << endl;
}
}
/** @internal
* @~English
* @brief Open a file for writing, failing if it exists.
*
* Assumes binary mode is wanted.
*
* Works around an annoying limitation of the VS2013-era msvcrt's
* @c fopen that implements an early version of the @c fopen spec.
* that does not accept 'x' as a mode character. For some reason
* Mingw uses this ancient version. Rather than use ifdef heuristics
* to identify sufferers of the limitation, it handles the error case
* and uses an alternate way to check for file existence.
*
* @return A stdio FILE* for the created file. If the file already exists
* returns nullptr and sets errno to EEXIST.
*/
static FILE* fopen_write_if_not_exists(const string& path) {
FILE* file = ::fopenUTF8(path, "wxb");
if (!file && errno == EINVAL) {
file = ::fopenUTF8(path, "r");
if (file) {
fclose(file);
file = nullptr;
errno = EEXIST;
} else {
file = ::fopenUTF8(path, "wb");
}
}
return file;
}
int strtoi(const char* str)
{
char* endptr;
int value = (int)strtol(str, &endptr, 0);
// Some implementations set errno == EINVAL but we can't rely on it.
if (value == 0 && endptr && *endptr != '\0') {
cerr << "Argument \"" << endptr << "\" not a number." << endl;
usage();
exit(1);
}
return value;
}
enum StdinUse { eDisallowStdin, eAllowStdin };
enum OutfilePos { eNone, eFirst, eLast };
void processCommandLine(int argc, char* argv[],
StdinUse stdinStat = eAllowStdin,
OutfilePos outfilePos = eNone)
{
uint32_t i;
size_t slash, dot;
name = argv[0];
// For consistent Id, only use the stem of name;
slash = name.find_last_of('\\');
if (slash == string::npos)
slash = name.find_last_of('/');
if (slash != string::npos)
name.erase(0, slash+1); // Remove directory name.
dot = name.find_last_of('.');
if (dot != string::npos)
name.erase(dot, string::npos); // Remove extension.
argparser parser(argc, argv);
processOptions(parser);
i = parser.optind;
if (argc - i > 0) {
if (outfilePos == eFirst)
options.outfile = parser.argv[i++];
uint32_t infileCount = outfilePos == eLast ? argc - 1 : argc;
for (; i < infileCount; i++) {
if (parser.argv[i][0] == '@') {
if (!loadFileList(parser.argv[i],
parser.argv[i][1] == '@',
options.infiles)) {
exit(1);
}
} else {
options.infiles.push_back(parser.argv[i]);
}
}
if (options.infiles.size() > 1) {
std::vector<string>::const_iterator it;
for (it = options.infiles.begin(); it < options.infiles.end(); it++) {
if (it->compare("-") == 0) {
error("cannot use stdin as one among many inputs.");
usage();
exit(1);
}
}
}
if (outfilePos == eLast)
options.outfile = parser.argv[i];
}
if (options.infiles.size() == 0) {
if (stdinStat == eAllowStdin) {
options.infiles.push_back("-"); // Use stdin as 0 files.
} else {
error("need some input files.");
usage();
exit(1);
}
}
if (outfilePos != eNone && options.outfile.empty()) {
error("need an output file");
}
}
bool loadFileList(const string &f, bool relativize,
vector<string>& filenames)
{
string listName(f);
listName.erase(0, relativize ? 2 : 1);
FILE *lf = nullptr;
lf = fopenUTF8(listName, "r");
if (!lf) {
error("failed opening filename list: \"%s\": %s\n",
listName.c_str(), strerror(errno));
return false;
}
string dirname;
if (relativize) {
size_t dirnameEnd = listName.find_last_of('/');
if (dirnameEnd == string::npos) {
relativize = false;
} else {
dirname = listName.substr(0, dirnameEnd + 1);
}
}
for (;;) {
// Cross platform PATH_MAX def is too much trouble!
char buf[4096];
buf[0] = '\0';
char *p = fgets(buf, sizeof(buf), lf);
if (!p) {
if (ferror(lf)) {
error("failed reading filename list: \"%s\": %s\n",
listName.c_str(), strerror(errno));
fclose(lf);
return false;
} else
break;
}
string readFilename(p);
while (readFilename.size()) {
if (readFilename[0] == ' ')
readFilename.erase(0, 1);
else
break;
}
while (readFilename.size()) {
const char c = readFilename.back();
if ((c == ' ') || (c == '\n') || (c == '\r'))
readFilename.erase(readFilename.size() - 1, 1);
else
break;
}
if (readFilename.size()) {
if (relativize)
filenames.push_back(dirname + readFilename);
else
filenames.push_back(readFilename);
}
}
fclose(lf);
return true;
}
virtual void processOptions(argparser& parser) {
int opt;
while ((opt = parser.getopt(&short_opts, option_list.data(), NULL)) != -1) {
switch (opt) {
case 0:
break;
case 10000:
break;
case 'h':
usage();
exit(0);
case 'v':
printVersion();
exit(0);
case ':':
error("missing required option argument.");
usage();
exit(0);
default:
if (!processOption(parser, opt)) {
usage();
exit(1);
}
}
}
#if defined(_WIN32) && defined(DEBUG)
if (options.launchDebugger)
launchDebugger();
#endif
}
virtual bool processOption(argparser& parser, int opt) = 0;
void writeId(std::ostream& dst, bool chktest) {
dst << name << " ";
dst << (!chktest || !options.test ? version : defaultVersion);
}
void printVersion() {
writeId(cerr, false);
cerr << endl;
}
#if defined(_WIN32) && defined(DEBUG)
// For use when debugging stdin with Visual Studio which does not have a
// "wait for executable to be launched" choice in its debugger settings.
bool launchDebugger()
{
// Get System directory, typically c:\windows\system32
std::wstring systemDir(MAX_PATH + 1, '\0');
UINT nChars = GetSystemDirectoryW(&systemDir[0],
static_cast<UINT>(systemDir.length()));
if (nChars == 0) return false; // failed to get system directory
systemDir.resize(nChars);
// Get process ID and create the command line
DWORD pid = GetCurrentProcessId();
std::wostringstream s;
s << systemDir << L"\\vsjitdebugger.exe -p " << pid;
std::wstring cmdLine = s.str();
// Start debugger process
STARTUPINFOW si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
if (!CreateProcessW(NULL, &cmdLine[0], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) return false;
// Close debugger process handles to eliminate resource leak
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
// Wait for the debugger to attach
while (!IsDebuggerPresent()) Sleep(100);
// Stop execution so the debugger can take over
DebugBreak();
return true;
}
#endif
string name;
string& version;
string& defaultVersion;
commandOptions& options;
virtual void validateOptions() { }
std::vector<argparser::option> option_list {
{ "help", argparser::option::no_argument, NULL, 'h' },
{ "version", argparser::option::no_argument, NULL, 'v' },
{ "test", argparser::option::no_argument, &options.test, 1},
#if defined(_WIN32) && defined(DEBUG)
{ "ld", argparser::option::no_argument, &options.launchDebugger, 1},
#endif
// -NSDocumentRevisionsDebugMode YES is appended to the end
// of the command by Xcode when debugging and "Allow debugging when
// using document Versions Browser" is checked in the scheme. It
// defaults to checked and is saved in a user-specific file not the
// pbxproj file so it can't be disabled in a generated project.
// Remove these from the arguments under consideration.
{ "-NSDocumentRevisionsDebugMode", argparser::option::required_argument, NULL, 10000 },
{ nullptr, argparser::option::no_argument, nullptr, 0 }
};
string short_opts = "hv";
};
extern ktxApp& theApp;
/** @internal
* @~English
* @brief Common main for all derived classes.
*
* Handles rewriting of argv to UTF-8 on Windows.
* Each app needs to initialize @c theApp to
* point to an instance of itself.
*/
int main(int argc, char* argv[])
{
InitUTF8CLI(argc, argv);
#if 0
if (!SetConsoleOutputCP(CP_UTF8)) {
cerr << theApp.getName() << "warning: failed to set UTF-8 code page for console output."
<< endl;
}
#endif
return theApp.main(argc, argv);
}