summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/rltiles/bmp2png/common.c
blob: 2d6042ae85549492b2da6cac5ea45dcbd579fe53 (plain) (blame)
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
/*
**  bmp2png --- conversion from (Windows or OS/2 style) BMP to PNG
**  png2bmp --- conversion from PNG to (Windows style) BMP
**
**  Copyright (C) 1999-2005 MIYASAKA Masaru
**
**  For conditions of distribution and use,
**  see copyright notice in common.h.
*/

#include "common.h"

#if defined(__DJGPP__)		/* DJGPP V.2 */
#include <crt0.h>
int _crt0_startup_flags = _CRT0_FLAG_DISALLOW_RESPONSE_FILES;
unsigned short _djstat_flags =	/* for stat() */
	_STAT_INODE | _STAT_EXEC_EXT | _STAT_EXEC_MAGIC | _STAT_DIRSIZE |
	_STAT_ROOT_TIME;
#endif

#if defined(__BORLANDC__)	/* Borland C++ */
#include <wildargs.h>
typedef void _RTLENTRY (* _RTLENTRY _argv_expand_fnc)(char *, _PFN_ADDARG);
typedef void _RTLENTRY (* _RTLENTRY _wargv_expand_fnc)(wchar_t *, _PFN_ADDARG);
_argv_expand_fnc  _argv_expand_ptr  = _expand_wild;		/* expand wild cards */
_wargv_expand_fnc _wargv_expand_ptr = _wexpand_wild;
#endif


/* -----------------------------------------------------------------------
**		screen management
*/

#define LINE_LEN	79
#define STATUS_LEN	22
#define PROGBAR_MAX	(LINE_LEN - STATUS_LEN - 1)

static char status_msg[128];
static int  progbar_scale = 0;
static int  progbar_len   = 0;
static int  progbar_pos   = -1;

int quietmode = 0;		/* -Q option */
int errorlog  = 0;		/* -L option */


static void print_status(void)
{
    if (quietmode) return;

	fprintf(stderr, "\r%-*.*s ", STATUS_LEN, STATUS_LEN, status_msg);
	fflush(stderr);
	progbar_pos = 0;
}

static void put_dots(int dotchar, int num)
{
	int i;

	if (num > PROGBAR_MAX) num = PROGBAR_MAX;
	if (progbar_pos == -1) print_status();

	for (i = progbar_pos; i < num; i++)
		fputc(dotchar, stderr);

	if (progbar_pos < num) {
		progbar_pos = num;
		fflush(stderr);
	}
}

static void print_scale(void)
{
	if (progbar_pos != 0) print_status();
	put_dots('.', progbar_len);
	print_status();
	progbar_scale = 1;
}

static void init_progress_bar(int max)
{
	if (quietmode) return;

	progbar_len = max;
	print_scale();
}

static void update_progress_bar(int num)
{
	if (quietmode) return;

	if (!progbar_scale) print_scale();
	put_dots('o', num);
}

static void clear_line(void)
{
	if (quietmode) return;

	fprintf(stderr, "\r%*c\r", LINE_LEN, ' ');
	progbar_scale = 0;
	progbar_pos   = -1;
}

void xxprintf(const char *fmt, ...)
{
	va_list ap;
	FILE *f;

    if (quietmode) return;

	va_start(ap, fmt);

	clear_line();
	vfprintf(stderr, fmt, ap);
	fflush(stderr);

	if (errorlog && (f = fopen(errlogfile, "a")) != NULL) {
		vfprintf(f, fmt, ap);
		fclose(f);
	}

	va_end(ap);
}

void set_status(const char *fmt, ...)
{
	va_list ap;

	if (quietmode) return;

	va_start(ap, fmt);
	vsprintf(status_msg, fmt, ap);
	va_end(ap);

	print_status();
}

void feed_line(void)
{
	if (quietmode) return;

	fputc('\n', stderr);
	fflush(stderr);
	progbar_scale = 0;
	progbar_pos   = -1;
}


/* -----------------------------------------------------------------------
**		libpng progress meter
*/

/*
 * -------------------------------------------------------------
 *
 *  PNG �̃C���^�[���X�`�� "Adam7" �̉摜�p�����[�^�F
 *
 *  �p�X   ��  ����  �J�n�_ �ʐϔ� �i�s��
 *  pass width height origin  area progress
 *    0   1/8   1/8   (0,0)   1/64  1/64 (  1.6%)
 *    1   1/8   1/8   (4,0)   1/64  1/32 (  3.1%)
 *    2   1/4   1/8   (0,4)   1/32  1/16 (  6.3%)
 *    3   1/4   1/4   (2,0)   1/16  1/8  ( 12.5%)
 *    4   1/2   1/4   (0,2)   1/8   1/4  ( 25.0%)
 *    5   1/2   1/2   (1,0)   1/4   1/2  ( 50.0%)
 *    6    1    1/2   (0,1)   1/2   1/1  (100.0%)
 *
 *  Adam7 �̎��̐i�s�󋵎Z�o�@�F
 *
 *  (width / 8) * 1 �̃s�N�Z���O���[�v���P�u���b�N�ƍl���A
 *  ���̃u���b�N��ʎZ�ł����o�͂������Ői�s�󋵂��Z�o����B
 *  �Ⴆ�� pass 0 �̎��́A���������̉摜�� 1/8 �Ȃ̂ŁA
 *  �R�[���o�b�N�֐����Ă΂��(��s�o�͂���)���ƂɂP�u���b�N��
 *  �o�͂������ƂɂȂ�Apass 4 �̎���(���l�ɍl����)�S�u���b�N��
 *  �o�͂������ƂɂȂ�B
 *  ���̌v�Z���@�ɂ��ƁA����̃p�X�����݂��Ȃ��Ȃ�悤��
 *  �ɒ[�ɏ������摜�łȂ�����(���� maxcount_adam7() ���Q��)�A
 *  �摜�S�̂̑��u���b�N���� (height * 8) �ɓ������Ȃ�B
 *
 *  ���ۂɂ��̕����Ői�s�󋵂�\�����Ă݂�ƁA�O������(pass0-5)
 *  �����㔼����(pass6)�������i�s����悤�Ɍ�����B����́A
 *  Adam7 �̓����Ƃ��ăs�N�Z�����c���o�����ɊԈ�����ĕ���
 *  ����Ă���A���ɉ������ɊԈ�����Ă��� pass0-5 (�O������)
 *  �ł͉摜�̍č\���Ɏ��Ԃ��������Ă�����̂Ǝv����B
 *
 * -------------------------------------------------------------
 */

static png_uint_32 counter;
static png_uint_32 maxcount;
static int         barlen;


static png_uint_32
 maxcount_adam7(png_uint_32 width, png_uint_32 height)
{
	png_uint_32 c = 0;

	if (    1    ) c += ((height - 0 + 7) / 8) * 1;		/* Pass 0 */
	if (width > 4) c += ((height - 0 + 7) / 8) * 1;		/* Pass 1 */
	if (    1    ) c += ((height - 4 + 7) / 8) * 2;		/* Pass 2 */
	if (width > 2) c += ((height - 0 + 3) / 4) * 2;		/* Pass 3 */
	if (    1    ) c += ((height - 2 + 3) / 4) * 4;		/* Pass 4 */
	if (width > 1) c += ((height - 0 + 1) / 2) * 4;		/* Pass 5 */
	if (    1    ) c += ((height - 1 + 1) / 2) * 8;		/* Pass 6 */

	return c;
}


/*
**		initialize the progress meter
*/
void init_progress_meter(png_structp png_ptr, png_uint_32 width,
                         png_uint_32 height)
{
	enum { W = 1024, H = 768 };

	if (png_set_interlace_handling(png_ptr) == 7) {
		maxcount = maxcount_adam7(width, height);	/* interlaced image */
	} else {
		maxcount = height;							/* non-interlaced image */
	}
	if (height > ((png_uint_32)W * H) / width) {
		barlen = PROGBAR_MAX;
	} else {
		barlen = (PROGBAR_MAX * width * height + (W * H - 1)) / (W * H);
	}
	counter = 0;
	init_progress_bar(barlen);
}


/*
**		row callback function for progress meter
*/
void row_callback(png_structp png_ptr, png_uint_32 row, int pass)
{
/*	static const png_byte step[] = { 1, 1, 2, 2, 4, 4, 8 }; */

	if (row == 0) pass--;
	/*
	 *	libpng's bug ?? : In the case of interlaced image,
	 *	  this function is called with row=0 and pass=current_pass+1
	 *	  when the row should be equal to height and the pass should
	 *	  be equal to current_pass.
	 */

	counter += (1 << (pass >> 1));	/* step[pass]; */
	update_progress_bar(barlen * counter / maxcount);
}


/* -----------------------------------------------------------------------
**		libpng error handling
*/

/*
**		fatal error handling function
*/
void png_my_error(png_structp png_ptr, png_const_charp message)
{
	xxprintf("ERROR(libpng): %s - %s\n", message,
	             (char *)png_get_error_ptr(png_ptr));
	longjmp(png_jmpbuf(png_ptr), 1);
}


/*
**		non-fatal error handling function
*/
void png_my_warning(png_structp png_ptr, png_const_charp message)
{
	xxprintf("WARNING(libpng): %s - %s\n", message,
	             (char *)png_get_error_ptr(png_ptr));
}


/* -----------------------------------------------------------------------
**		image buffer management
*/

/*
**		allocate image buffer
*/
BOOL imgbuf_alloc(IMAGE *img)
{
	BYTE *bp, **rp;
	LONG n;

	if (img->palnum > 0) {
		img->palette = malloc((size_t)img->palnum * sizeof(PALETTE));
		if (img->palette == NULL) { imgbuf_init(img); return FALSE; }
	} else {
		img->palette = NULL;
	}
	img->rowbytes = ((DWORD)img->width * img->pixdepth + 31) / 32 * 4;
	img->imgbytes = img->rowbytes * img->height;
	img->rowptr   = malloc((size_t)img->height * sizeof(BYTE *));
	img->bmpbits  = malloc((size_t)img->imgbytes);

	if (img->rowptr == NULL || img->bmpbits == NULL) {
		imgbuf_free(img); imgbuf_init(img); return FALSE;
	}

	n  = img->height;
	rp = img->rowptr;
	bp = img->bmpbits;

	if (img->topdown) {
		while (--n >= 0) {
			*(rp++) = bp;
			bp += img->rowbytes;
		/*	((DWORD *)bp)[-1] = 0;	*/
		}
	} else {	/* bottom-up */
		bp += img->imgbytes;
		while (--n >= 0) {
			/* fill zeros to padding bytes (for write_bmp()) */
			((DWORD *)bp)[-1] = 0;
			bp -= img->rowbytes;
			*(rp++) = bp;
		}
	}

	return TRUE;
}


/*
**		free image buffer allocated by imgbuf_alloc()
*/
void imgbuf_free(IMAGE *img)
{
	free(img->palette);
	free(img->rowptr);
	free(img->bmpbits);
}


/*
**		init image buffer to empty
*/
void imgbuf_init(IMAGE *img)
{
	img->palette = NULL;
	img->rowptr  = NULL;
	img->bmpbits = NULL;
}


/* -----------------------------------------------------------------------
**		�R�}���h���C�������̏���
*/

#define isoption(p)	(IsOptChar((p)[0]) && (p)[1]!='\0')

/*
**	�R�}���h���C��������ǂ�
*/
int parsearg(int *opt, char **arg, int argc, char **argv, char *aopts)
{
	static int   agi = 1;
	static char *agp = NULL;
	char *p;
	int c, i;

	if (agp != NULL && *agp == '\0') {
		agp = NULL;
		agi++;
	}
	if (agi >= argc) return 0;		/* end */

	if (p = argv[agi], agp == NULL && !isoption(p)) {
		/* non-option element */
		c = 0;
		agi++;
	} else {
		if (agp == NULL) agp = p + 1;
		if (c = (*agp & 0xFF), strchr(aopts, c) != NULL) {
			/* option with an argument */
			if (p = agp + 1, *p != '\0') {
				/*NULL*/;
			} else if (i = agi + 1, p = argv[i], i < argc && !isoption(p)) {
				agi = i;
			} else {
				p = NULL;
			}
			agp = NULL;
			agi++;
		} else {
			/* option without an argument */
			p = NULL;
			agp++;
		}
	}
	*opt = c;
	*arg = p;

	return 1;
}


/*
**	�‹��ϐ��Ŏw�肳��Ă���I�v�V������ argc, argv �ɕ�������
*/
char **envargv(int *argcp, char ***argvp, const char *envn)
{
	int argc, nagc, envc, i;
	char **argv, **nagv, *envs, *ep;

	ep = getenv(envn);
	if (ep == NULL || ep[0] == '\0') return NULL;

	envs = malloc(strlen(ep) + 1);
	if (envs == NULL) return NULL;
	strcpy(envs, ep);

	envc = tokenize(envs, envs);
	if (envc == 0) { free(envs); return NULL; }

	argc = *argcp;
	argv = *argvp;
	nagv = malloc((argc + envc + 1) * sizeof(char *));
	if (nagv == NULL) { free(envs); return NULL; }

	nagc = 1;
	nagv[0] = argv[0];

	for (i = 0; i < envc; i++) {
		nagv[nagc++] = envs;
		while (*(envs++) != '\0') ;
	}
	for (i = 1; i < argc; i++) {
		nagv[nagc++] = argv[i];
	}
	nagv[nagc] = NULL;

	*argcp = nagc;
	*argvp = nagv;

	return argv;
}


/*
**	��������󔒕���(�X�y�[�X/�����^�u/���s)�̏��ŋ�؂�(�N�I�[�g�����t��)
**	��؂�ꂽ����������̐���Ԃ�
*/
int tokenize(char *buf, const char *str)
{
	enum { STR = 0x01, QUOTE = 0x02 };
	int flag = 0;
	int num = 0;
	char c;
	int i;

	while ((c = *str++) != '\0') {
		if (!(flag & QUOTE) &&
		    (c == ' ' || c == '\t' || c == '\n' || c == '\r')) {
			if (flag & STR) {
				flag &= ~STR;
				*buf++ = '\0';
			}
		} else {
			if (!(flag & STR)) {
				flag |= STR;
				num++;
			}
			switch (c) {
			case '\\':
				/*
				 *	Escaping of `"' is the same as
				 *	command-line parsing of MS-VC++.
				 *
				 *	ex.) "     ->      quote
				 *	     \"    ->      "
				 *	     \\"   -> \  + quote
				 *	     \\\"  -> \  + "
				 *	     \\\\" -> \\ + quote
				 *	     \\\\\ -> \\\\\
				 */
				for (i = 1; (c = *str) == '\\'; str++, i++) ;
				if (c == '"') {
					while ((i -= 2) >= 0)
						*buf++ = '\\';
					if (i == -1) {
						*buf++ = '"';
						str++;
					}
				} else {
					while ((--i) >= 0)
						*buf++ = '\\';
				}
				break;

			case '"':
				flag ^= QUOTE;
				break;

			default:
				*buf++ = c;
			}
		}
	}
	if (flag & STR) *buf = '\0';

	return num;
}


/* -----------------------------------------------------------------------
**		�t�@�C���Ɋւ���G�p����
*/

/*
**	�����K�w�̃f�B���N�g������x�ɍ쐬����
*/
int makedir(const char *path)
{
	char dir[FILENAME_MAX];
	struct stat sbuf;
	char *p, c;
	int r;

	delslash(strcpy(dir, path));
	if (stat(dir, &sbuf) == 0) {
		if ((sbuf.st_mode & S_IFMT) == S_IFDIR) return 0;
		/* errno = EEXIST; */
		return -1;
	}
	p = path_skiproot(dir);
	do {
		p = path_nextslash(p);
		c = *p;  *p = '\0';
		r = MKDIR(dir, 0777);
		*p++ = c;
	} while (c != '\0');

	return r;
}


/*
**	�����̓����t�@�C�����o�b�N�A�b�v(���l�[��)����
*/
int renbak(const char *path)
{
	char bak[FILENAME_MAX];
	struct stat sbuf;
	char *sfx;
	int i;

	strcpy(bak, path);
	if (stat(bak, &sbuf) != 0) return 0;

#ifdef MSDOS
	sfx = suffix(bak);
#else
	sfx = bak + strlen(bak);
#endif
	strcpy(sfx, ".bak");
	i = 0;
	while (1) {
		if (stat(bak, &sbuf) != 0 && rename(path, bak) == 0) return 0;
		if (i >= 1000) break;
		sprintf(sfx, ".%03d", i++);
	}
	return -1;
}


/*
**	�t�@�C���̃^�C���X�^���v���R�s�[����
*/
int cpyftime(const char *srcf, const char *dstf)
{
	struct stat sbuf;
	struct utimbuf ubuf;

	if (stat(srcf, &sbuf) != 0) return -1;

	ubuf.actime  = sbuf.st_atime;
	ubuf.modtime = sbuf.st_mtime;

	return utime(dstf, &ubuf);
}


/*
**	�o�C�i�����[�h�̕W�����o�̓X�g���[�����擾����
*/
FILE *binary_stdio(int fd)
{
	FILE *fp;

	if (fd != 0 && fd != 1) return NULL;

#ifdef BINSTDIO_FDOPEN
	fp = fdopen(fd, (fd==0)? "rb":"wb");
#else
#ifdef BINSTDIO_SETMODE
	setmode(fd, O_BINARY);
#endif
	fp = (fd == 0) ? stdin : stdout;
#endif
	return fp;
}


/* -----------------------------------------------------------------------
**   path functions
*/

/*
**	Return a pointer that points the suffix of the PATH
**	ex.) c:\dosuty\log\test.exe -> .exe
**	ex.) c:\dosuty\log\test.tar.gz -> .gz
*/
char *suffix(const char *path)
{
	char c, *p, *q, *r;

	for (r = q = p = basname(path); (c = *p) != '\0'; p++)
		if (c == '.') q = p;
	if (q == r) q = p;			/* dotfile with no suffix */

	return q;
}


/*
**	Return a pointer that points the basename of the PATH
**	ex.) c:\dos\format.exe -> format.exe
*/
char *basname(const char *path)
{
	const char *p, *q;

	for (p = path_skiproot(path);
	     *(q = path_nextslash(p)) != '\0'; p = q + 1) ;

	return (char *)p;
}


/*
**	Append a path-delimiter to the PATH. If the PATH is a string
**	like "c:\", "\", "c:", "", do nothing.
**	ex.) c:\dos -> c:\dos\
*/
char *addslash(char *path)
{
	char *p, *q;

	for (p = path_skiproot(path);
	     *(q = path_nextslash(p)) != '\0'; p = q + 1) ;
	/*
	 *	s = path_skiproot( path );
	 *	if( q==s && q==p ) - s is a mull string.
	 *	if( q!=s && q==p ) - s is followed by a path delimiter.
	 *	if( q!=s && q!=p ) - s is not followed by a path delimiter.
	 */
	if (q != p) {
		*q++ = PATHDELIM;
		*q   = '\0';
	}

	return path;
}


/*
**	Remove a path-delimiter at the end of the PATH. If the PATH is
**	a string like "c:\", "\", "c:", "", append a dot.
**	ex.) c:\dos\ -> c:\dos
**	     c:\ -> c:\.
*/
char *delslash(char *path)
{
	char *p, *q, *s;

	for (p = s = path_skiproot(path);
	     *(q = path_nextslash(p)) != '\0'; p = q + 1) ;
	/*
	 *	if( q==s && q==p ) - s is a mull string.
	 *	if( q!=s && q==p ) - s is followed by a path delimiter.
	 *	if( q!=s && q!=p ) - s is not followed by a path delimiter.
	 */
	if (q == s) {
		*q++ = '.';
		*q   = '\0';
	} else if (q == p) {
		*--q = '\0';
	}

	return path;
}


char *path_skiproot(const char *path)
{
#ifdef DRIVESUFFIX
	if (isalpha((unsigned char)path[0])
	    && path[1] == DRIVESUFFIX) path += 2;
#endif
	if (IsPathDelim(path[0])) path++;
	return (char *)path;
}


char *path_nextslash(const char *path)
{
	char c;

	for (; (c = *path) != '\0'; path++) {
		if (IsDBCSLead((unsigned char)c)) {
			if (*(++path) == '\0') break;
			continue;
		}
		if (IsPathDelim(c)) break;
	}
	return (char *)path;
}

#ifdef WIN32_LFN

/*
**	return TRUE if the PATH is a dos-style filename.
*/
int is_dos_filename(const char *path)
{
	unsigned char c;
	char *b, *p;

	for (b = p = basname(path); (c = *p) != '\0' && c != '.'; p++)
		if (islower(c)) return 0;
	if ((p - b) == 0 || (p - b) > 8) return 0;
	if (c == '.') {
		for (b = ++p; (c = *p) != '\0'; p++)
			if (islower(c) || c == '.') return 0;
		if ((p - b) == 0 || (p - b) > 3) return 0;
	}
	return 1;
}

#endif /* WIN32_LFN */