-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathimv.c
4122 lines (3587 loc) · 125 KB
/
imv.c
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
/* stb(imv) windows image viewer
Copyright 2007 Sean Barrett
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Set section alignment to minimize alignment overhead
#if (_MSC_VER < 1300)
#pragma comment(linker, "/FILEALIGN:0x200")
#endif
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <process.h>
#include <math.h>
#define STB_DEFINE
#include "stb.h" /* http://nothings.org/stb.h */
// general configuration options
#ifndef USE_STBI
#define USE_STBI 1
#endif
#ifndef USE_GDIPLUS
#define USE_GDIPLUS 1
#endif
#ifndef USE_FREEIMAGE
#define USE_FREEIMAGE 1
#endif
#ifndef ALLOW_RECOLORING
#define ALLOW_RECOLORING 0
#endif
//#define MONO2
// implement USE_STBI
#if USE_STBI
#define STBI_FAILURE_USERMSG
#define STBI_NO_STDIO
#define STBI_NO_WRITE
#include "stb_image.c" /* http://nothings.org/stb_image.c */
#endif
#include "resource.h"
typedef int Bool;
// size of border in pixels
#define FRAME 3
// location within frame of secondary border
#define FRAME2 (FRAME >> 1)
// color of secondary border
#define GREY 192
Bool do_show;
float delay_time = 4;
int nearest_neighbor = 0; // internal use
// all programs get the version number from the same place: version.bat
#define set static char *
#include "version.bat"
;
#undef set
// trivial error handling
void error(char *str) { MessageBox(NULL, str, "imv(stb) error", MB_OK); }
// OutputDebugString with varargs, can be compiled out
#ifdef _DEBUG
int do_debug=1;
void ods(char *str, ...)
{
if (do_debug) {
char buffer[1024];
va_list va;
va_start(va,str);
vsprintf(buffer, str, va);
va_end(va);
OutputDebugString(buffer);
}
}
#define o(x) ods x
#else
#define o(x)
#endif
// internal messages (all used for waking up main thread from tasks)
enum
{
WM_APP_DECODED = WM_APP,
WM_APP_LOAD_ERROR,
WM_APP_DECODE_ERROR,
};
// a few extra options for GetSystemMetrics for old compilers
#if WINVER < 0x0500
#define SM_XVIRTUALSCREEN 76
#define SM_YVIRTUALSCREEN 77
#define SM_CXVIRTUALSCREEN 78
#define SM_CYVIRTUALSCREEN 79
#define SM_CMONITORS 80
#define SM_SAMEDISPLAYFORMAT 81
#endif
char *displayName = "imv(stb)";
CHAR szAppName[] = "stb_imv";
HWND win;
// number of bytes per pixel (not bits); can be 3 or 4
#define BPP 4
// lightweight SetDIBitsToDevice() wrapper
// (once upon a time this was a platform-independent, hence the name)
// if 'dim' is set, draw it darkened
void platformDrawBitmap(HDC hdc, int x, int y, unsigned char *bits, int w, int h, int stride, int dim)
{
int i;
BITMAPINFOHEADER b = { sizeof(b) };
int result;
b.biPlanes=1;
b.biBitCount=BPP*8;
b.biWidth = stride/BPP;
b.biHeight = -h; // tell windows the bitmap is stored top-to-bottom
if (dim)
// divide the brightness of each channel by two... (if BPP==3, this
// does 4 pixels every 3 iterations)
for (i=0; i < stride*h; i += 4)
*(uint32 *)(bits+i) = (*(uint32 *)(bits+i) >> 1) & 0x7f7f7f7f;
result = SetDIBitsToDevice(hdc, x,y, w,abs(h), 0,0, 0,abs(h), bits, (BITMAPINFO *) &b, DIB_RGB_COLORS);
if (result == 0) {
DWORD e = GetLastError();
}
// bug: we restore by shifting, so we've discarded the bottom bit;
// thus, once you've viewed the help and come back, the display
// is slightly wrong until you resize or switch images. so we should
// probably save and restore it instead... slow, but we're displaying
// the help so no big deal?
if (dim)
for (i=0; i < stride*h; i += 4)
*(uint32 *)(bits+i) = (*(uint32 *)(bits+i) << 1);
}
// memory barrier for x86
void barrier(void)
{
long dummy;
__asm {
xchg dummy, eax
}
}
// awake the main thread when something interesting happens
void wake(int message)
{
PostMessage(win, message, 0,0);
}
typedef struct
{
int x,y; // size of the image
int stride; // distance between rows in bytes
int frame; // does this image have a frame (border)?
uint8 *pixels; // pointer to (0,0)th pixel
int had_alpha; // did this have alpha and we statically overwrote it?
} Image;
enum
{
// owned by main thread
LOAD_unused=0, // empty slot
LOAD_inactive, // filename slot, not loaded
// finished reading, needs decoding--originally decoder
// owned this, but then we couldn't free from the cache
LOAD_reading_done,
// in any of the following states, the image is as done as it can be
LOAD_error_reading,
LOAD_error_decoding,
LOAD_available, // loaded successfully
// owned by resizer
LOAD_resizing,
// owned by loader
LOAD_reading,
// owned by decoder
LOAD_decoding,
};
// does the main thread own this? (if this is true, the main
// thread can manipulate without locking, except for LOAD_reading_done
// which requires locking)
#define MAIN_OWNS(x) ((x)->status <= LOAD_available)
// data about a specific file
typedef struct
{
char *filename; // name of the file on disk, must be free()d
char *filedata; // data loaded from disk -- passed from reader to decoder
int len; // length of data loaded from disk -- as above
Image *image; // cached image -- passed from decoder to main
char *error; // error message -- from reader or decoder, must be free()d
int status; // current status/ownership with LOAD_* enum
int bail; // flag from main thread to work threads indicating to give up
int lru; // the larger, the higher priority--effectively a timestamp
} ImageFile;
// controls for interlocking communications
stb_mutex cache_mutex, decode_mutex;
stb_semaphore decode_queue;
stb_semaphore disk_command_queue;
stb_sync resize_merge;
// a request communicated from the main thread to the disk-loader task
typedef struct
{
int num_files;
ImageFile *files[4];
} DiskCommand;
// there can only be one pending command in flight
volatile DiskCommand dc_shared;
// the disk loader sits in this loop forever
void *diskload_task(void *p)
{
for(;;) {
int i;
DiskCommand dc;
// wait to be woken up by a command from the main thread
o(("READ: Waiting for disk request.\n"));
stb_sem_waitfor(disk_command_queue);
// it's possible for the main thread to do:
// 1. ... store a command in the command buffer ...
// 2. sem_release()
// 3. ... store a command in the command buffer ...
// 4. sem_release()
// and for this thread to complete a previous command and
// reach the waitfor() right after step 3 above. If this happens,
// this thread will pass the waitfor() (setting the semaphore to 0),
// process the latest command, the main thread will do step 4 (setting
// the semaphore to 1), and then this thread comes back around and
// passes the waitfor() again with no actual pending command. This
// case is handled below by clearing the command length to 0.
// grab the command; don't let the command or the cache change while we do it
stb_mutex_begin(cache_mutex);
{
// copy the command into a local buffer
dc = dc_shared;
// claim ownership over all the files in the command
for (i=0; i < dc.num_files; ++i) {
dc.files[i]->status = LOAD_reading;
assert(dc.files[i]->filedata == NULL);
}
// clear the command so we won't re-process it
dc_shared.num_files = 0;
}
stb_mutex_end(cache_mutex);
o(("READ: Got disk request, %d items.\n", dc.num_files));
for (i=0; i < dc.num_files; ++i) {
int n;
uint8 *data;
assert(dc.files[i]->status == LOAD_reading);
// check if the main thread changed its mind about this
// e.g. if this is the third file in a request, and the main thread
// has already made another command pending, then it will set this
// flag on previous requests, and we shouldn't waste time loading
// data that's no longer high-priority
if (dc.files[i]->bail) {
o(("READ: Bailing on disk request\n"));
dc.files[i]->status = LOAD_inactive;
} else {
o(("READ: Loading file %s\n", dc.files[i]->filename));
assert(dc.files[i]->filedata == NULL);
// read the data
data = stb_file(dc.files[i]->filename, &n);
// update the results
// don't need to mutex these, because we own them via ->status
if (data == NULL) {
o(("READ: error reading\n"));
dc.files[i]->error = strdup("can't open");
dc.files[i]->filedata = NULL;
dc.files[i]->len = 0;
barrier();
dc.files[i]->status = LOAD_error_reading;
wake(WM_APP_LOAD_ERROR); // wake main thread to react to error
} else {
o(("READ: Successfully read %d bytes\n", n));
dc.files[i]->error = NULL;
assert(dc.files[i]->filedata == NULL);
dc.files[i]->filedata = data;
dc.files[i]->len = n;
barrier();
dc.files[i]->status = LOAD_reading_done;
stb_sem_release(decode_queue); // wake the decode task if needed
}
}
}
}
}
static unsigned char alpha_background[2][3] =
{
{ 200,40,200 },
{ 150,30,150 },
};
// given raw decoded data from stbi_load, make it into a proper Image (e.g. creating a
// windows-compatible bitmap with 4-byte aligned rows and BGR color order)
#if ALLOW_RECOLORING
float lmin=0,lmax=1;
int mono;
#endif
void make_image(Image *z, int image_x, int image_y, uint8 *image_data, BOOL image_loaded_as_rgb, int image_n)
{
#ifdef ALLOW_RECOLORING
int ms,md, ns,nd;
#endif
int i,j,k,ymin=0,ymax=256*8-1;
z->pixels = image_data;
z->x = image_x;
z->y = image_y;
z->stride = image_x*BPP;
z->frame = 0;
z->had_alpha = (image_n==4);
if (z->had_alpha) {
int n=0;
for (n=0; n < image_x * image_y; ++n)
if (image_data[n*4+3])
break;
if (n == image_x * image_y) {
// all alpha is 0, so force to 255
for (n=0; n < image_x * image_y; ++n)
image_data[n*4+3] = 255;
}
}
#if ALLOW_RECOLORING
if (mono) {
k = 0;
for (j=0; j < image_y; ++j) {
for (i=0; i < image_x; ++i) {
int y = image_data[k+0]*5 + image_data[k+1]*9 + image_data[k+2]*2;
if (y < ymin) ymin = y;
if (y > ymax) ymax = y;
k += BPP;
}
}
}
#endif
#if ALLOW_RECOLORING
if (lmin > 0)
ms = (int) (lmin * 255), md=0;
else
ms = 0, md = (int)(-lmin*255);
if (lmax < 1)
ns = (int)(lmax * 255), nd=255;
else
ns = 255, nd = (int) ((2-lmax)*255);
if (ns <= ms)
ns = ms+1;
if (nd < md)
nd = md+1;
if (ns == 256) --ns,--ms;
if (nd == 256) --nd,--md;
#endif
k=0;
for (j=0; j < image_y; ++j) {
for (i=0; i < image_x; ++i) {
// TODO: hoist branches outside of loops?
if (image_loaded_as_rgb) {
// swap RGB to BGR
unsigned char t = image_data[k+0];
image_data[k+0] = image_data[k+2];
image_data[k+2] = t;
}
#if ALLOW_RECOLORING
if (mono) {
#ifdef MONO2
int p = image_data[k+2];
#else
int y = image_data[k+0]*5 + image_data[k+1]*9 + image_data[k+2]*2;
int p = (int) stb_linear_remap(y, ymin, ymax, 0,255);
#endif
image_data[k+0] = p;
image_data[k+1] = p;
image_data[k+2] = p;
} else if (lmin != 0 || lmax != 1) {
int c;
for (c=0; c < 3; ++c) {
int z = (int) stb_linear_remap(image_data[k+c], ms,ns, md,nd);
image_data[k+c] = stb_clamp(z, 0, 255);
}
}
#endif
#if BPP==4
// if image had an alpha channel, pre-blend with background
if (image_n == 4) {
unsigned char *p = image_data+k;
int a = (255-p[3]);
if ((i ^ j) & 8) {
p[0] += (((alpha_background[0][2] - (int) p[0])*a)>>8);
p[1] += (((alpha_background[0][1] - (int) p[1])*a)>>8);
p[2] += (((alpha_background[0][0] - (int) p[2])*a)>>8);
} else {
p[0] += (((alpha_background[1][2] - (int) p[0])*a)>>8);
p[1] += (((alpha_background[1][1] - (int) p[1])*a)>>8);
p[2] += (((alpha_background[1][0] - (int) p[2])*a)>>8);
}
}
#endif
k += BPP;
}
}
}
// Max entries in image cache. This shouldn't be TOO large, because we
// traverse it inside mutexes sometimes. Also, for large images, we'll
// hit cache-size limits fairly quickly (a 2 megapixel image requires
// 8MB, so you could only fit 50 in a 400MB cache), so no reason to be
// too large anyway
#define MAX_CACHED_IMAGES 200
// no idea if it needs to be volatile, decided not to worry about proving
// it one way or the other
volatile ImageFile cache[MAX_CACHED_IMAGES];
// choose which image to decode and claim ownership
volatile ImageFile *decoder_choose(void)
{
int i, best_lru=0;
volatile ImageFile *best = NULL;
// if we get unlucky we may have to bail and start over
start:
// iterate through the cache and find the ready-to-decode image
// that was most in demand (the highest priority will be the most-recently
// accessed image or, for prefetching, one right next to it; but this
// is policy determined by the main thread, not by this thread).
for (i=0; i < MAX_CACHED_IMAGES; ++i) {
if (cache[i].status == LOAD_reading_done) {
if (cache[i].lru > best_lru) {
best = &cache[i];
best_lru = best->lru;
}
}
}
// it's possible there is no image to decode; see the description
// in diskload_task of how it's possible for a task to be woken
// from the sem_release() without there being a pending command.
if (best) {
int retry = FALSE;
// if there is a best one, it's possible that while iterating
// it was flushed by the main thread. so let's make sure it's
// still ready to decode. (Of course it ALSO could have changed
// lru priority and other such, so not be the best anymore, but
// it's no big deal to get that wrong since it's close.)
stb_mutex_begin(cache_mutex);
{
if (best->status == LOAD_reading_done)
best->status = LOAD_decoding;
else
retry = TRUE;
}
stb_mutex_end(cache_mutex);
// if the status changed out from under us, try again
if (retry)
goto start;
}
return best;
}
static uint8 *imv_decode_from_memory(uint8 *mem, int len, int *x, int *y, BOOL *loaded_as_rgb, int *n, int n_req, char *filename);
static char *imv_failure_reason(void);
void *decode_task(void *p)
{
for(;;) {
// find the best image to decode
volatile ImageFile *f = decoder_choose();
if (f == NULL) {
// wait for load thread to wake us
o(("DECODE: blocking\n"));
stb_sem_waitfor(decode_queue);
o(("DECODE: woken\n"));
} else {
int x,y,loaded_as_rgb,n;
uint8 *data;
assert(f->status == LOAD_decoding);
// decode image
o(("DECIDE: decoding %s\n", f->filename));
data = imv_decode_from_memory(f->filedata, f->len, &x, &y, &loaded_as_rgb, &n, BPP, f->filename);
o(("DECODE: decoded %s\n", f->filename));
// free copy of data from disk, which we don't need anymore
free(f->filedata);
f->filedata = NULL;
if (data == NULL) {
// error reading file, record the reason for it
f->error = strdup(imv_failure_reason());
barrier();
f->status = LOAD_error_reading;
// wake up the main thread in case this is the most recent image
wake(WM_APP_DECODE_ERROR);
} else {
// post-process the image into the right format
f->image = (Image *) malloc(sizeof(*f->image));
make_image(f->image, x, y,data, loaded_as_rgb, n);
barrier();
f->status = LOAD_available;
// wake up the main thread in case this is the most recent image
wake(WM_APP_DECODED);
}
}
}
}
// the image cache entry currently trying to be displayed (may be waiting on resizer)
ImageFile *source_c;
// the image currently being displayed--historically redundant to source_c->image
Image *source;
// allocate an image in windows-friendly format
Image *bmp_alloc(int x, int y)
{
Image *i = malloc(sizeof(*i));
if (!i) return NULL;
i->x = x;
i->y = y;
i->stride = x*BPP;
i->stride += (-i->stride) & 3;
i->pixels = malloc(i->stride * i->y);
i->frame = 0;
i->had_alpha = 0;
if (i->pixels == NULL) { free(i); return NULL; }
return i;
}
// toggle for whether to draw the stripe in the middle of the border
int extra_border = TRUE;
// build the border into an image--this was easier than drawing it on
// the fly, although slightly less efficient, but probably totally
// redundant now that we paint an infinite black border around the image?
// reduces flickering of the stripe, I guess.
void frame(Image *z)
{
int i;
z->frame = FRAME;
memset(z->pixels, 0, FRAME*z->stride);
memset(z->pixels + z->stride*(z->y-FRAME), 0, FRAME*z->stride);
if (extra_border) {
memset(z->pixels + z->stride*FRAME2 + FRAME2*BPP, GREY, (z->x-FRAME2*2)*BPP);
memset(z->pixels + z->stride*(z->y-FRAME2-1) + FRAME2*BPP, GREY, (z->x-FRAME2*2)*BPP);
}
for (i=FRAME; i < z->y-FRAME; ++i) {
memset(z->pixels + i*z->stride, 0, FRAME*BPP);
memset(z->pixels + i*z->stride + (z->x-FRAME)*BPP, 0, FRAME*BPP);
}
if (extra_border) {
for (i=2; i < z->y-2; ++i) {
memset(z->pixels + i*z->stride+FRAME2*BPP, GREY, BPP);
memset(z->pixels + i*z->stride + (z->x-FRAME2-1)*BPP, GREY, BPP);
}
}
}
// free an image and its contents
void imfree(Image *x)
{
if (x) {
free(x->pixels);
free(x);
}
}
// return an Image which is a sub-region of another image
Image image_region(Image *p, int x, int y, int w, int h)
{
Image q;
q.stride = p->stride;
q.x = w;
q.y = h;
q.pixels = p->pixels + y*p->stride + x*BPP;
return q;
}
// the currently displayed image--may slightly lag source/source_c
// while waiting on a resize
Image *cur;
// the filename for the currently displayed image
char *cur_filename;
int show_help=0;
int downsample_cubic = TRUE;
int upsample_cubic = TRUE;
int cur_loc = -1; // offset within the current list of files
// information about files we have currently loaded
struct
{
char *filename;
int lru;
} *fileinfo;
// declare with extra bytes so we can print the version number into it
char helptext_center[150] =
"imv(stb)\n"
"Copyright 2007 Sean Barrett\n"
"http://code.google.com/p/stb-imv\n"
"version "
;
char helptext_left[] =
"\n\n\n\n\n\n\n"
" ALT-ENTER: toggle size\n"
" CTRL-PLUS: zoom in\n"
"CTRL-MINUS: zoom out\n"
"RIGHT, SPACE: next image\n"
"LEFT, BACKSPACE: previous image\n"
" O: open image\n"
" B: toggle border\n"
"SHIFT-B: toggle border but keep stripe\n"
" CTRL-B: toggle white stripe in border\n"
" L: toggle filename label\n"
" S: slideshow in current directory\n"
" CTRL-S: sharpen when upscaling\n"
;
char helptext_right[] =
"\n\n\n\n\n\n\n"
"right-click to exit\n"
"left drag center to move\n"
"left drag edges to resize\n"
"double-click to toggle size\n"
"mousewheel to zoom\n"
"\n"
"F1, H, ?: help\n"
"ESC: exit\n"
"P: change preferences\n"
"CTRL-C: copy filename to clipboard\n"
"CTRL-I: launch new viewer instance\n"
;
// draw the help text semi-prettily
// originally this was to try to avoid having to darken the image
// that it's rendered over, but I couldn't make that work, and with
// the darkened image there's no real need to do this, but hey, it
// looks a little nicer so why not
void draw_nice(HDC hdc, char *text, RECT *rect, uint flags)
{
int i,j;
SetTextColor(hdc, RGB(80,80,80));
for (i=2; i >= 1; i -= 1)
for (j=2; j >= 1; j -= 1)
{
// displace the rectangle so as to displace the text
RECT r = { rect->left+i, rect->top+j, rect->right+i, rect->bottom + j };
if (i == 1 && j == 1)
SetTextColor(hdc, RGB(0,0,0));
DrawText(hdc, text, -1, &r, flags);
}
SetTextColor(hdc, RGB(255,255,255));
DrawText(hdc, text, -1, rect, flags);
}
// cached error message for most recent image
char display_error[1024];
// to make an image with an error the most recent image, call this
void set_error(volatile ImageFile *z)
{
sprintf(display_error, "File:\n%s\nError:\n%s\n", z->filename, z->error);
InvalidateRect(win, NULL, FALSE);
imfree(cur);
cur = NULL;
free(cur_filename);
cur_filename = strdup(z->filename);
source_c = (ImageFile *) z;
source = NULL;
}
HFONT label_font;
int label_font_height=12;
// build the font for the filename label
void build_label_font(void)
{
LOGFONT lf = {0};
lf.lfHeight = label_font_height;
lf.lfOutPrecision = OUT_TT_PRECIS; // prefer truetype to raster fonts
strcpy(lf.lfFaceName, "Times New Roman");
if (label_font) DeleteObject(label_font);
label_font = CreateFontIndirect(&lf);
}
char path_to_file[4096];
int show_frame = TRUE; // show border or not?
int show_label = FALSE; // display the help text or not
int recursive = FALSE;
// WM_PAINT, etc.
void display(HWND win, HDC hdc)
{
RECT rect,r2;
HBRUSH b = GetStockObject(BLACK_BRUSH);
int w,h,x,y;
// get the window size for centering
GetClientRect(win, &rect);
w = rect.right - rect.left;
h = rect.bottom - rect.top;
// set the text rendering mode for our fancy text
SetBkMode(hdc, TRANSPARENT);
// if the current image had an error, just display that
if (display_error[0]) {
FillRect(hdc, &rect, b); // clear to black -- will flicker
if (rect.bottom > rect.top + 100) rect.top += 50; // displace down from top; could center
draw_nice(hdc, display_error, &rect, DT_CENTER);
return;
}
// because show_frame toggles the window size, and we center the bitmap,
// we just go ahead and render the entire bitmap with the border in it
// regardless of the show_frame toggle. You can see that when you resize
// a window in one dimension--the strip is still there, just off the edge
// of the window.
x = (w - cur->x) >> 1;
y = (h - cur->y) >> 1;
platformDrawBitmap(hdc, x,y,cur->pixels, cur->x, cur->y, cur->stride, show_help);
// draw in infinite borders on all four sides
r2 = rect;
r2.right = x; FillRect(hdc, &r2, b); r2=rect;
r2.left = x + cur->x; FillRect(hdc, &r2, b); r2 = rect;
r2.left = x;
r2.right = x+cur->x;
r2.bottom = y; FillRect(hdc, &r2, b); r2 = rect;
r2.left = x;
r2.right = x+cur->x;
r2.top = y + cur->y; FillRect(hdc, &r2, b);
// should we show the name of the file?
if (show_label) {
SIZE size;
RECT z;
HFONT old = NULL;
char buffer[1024];
char *name = cur_filename ? cur_filename : "(none)";
if (fileinfo) {
if (recursive)
sprintf(buffer, "%s ( %d / %d - %s)", name, cur_loc+1, stb_arr_len(fileinfo), path_to_file);
else
sprintf(buffer, "%s ( %d / %d )", name, cur_loc+1, stb_arr_len(fileinfo));
name = buffer;
}
if (label_font) old = SelectObject(hdc, label_font);
// get rect around label so we can draw it ourselves, because
// the DrawText() one is poorly sized
GetTextExtentPoint32(hdc, name, strlen(name), &size);
z.left = rect.left+1;
z.bottom = rect.bottom+1;
z.top = z.bottom - size.cy - 4;
z.right = z.left + size.cx + 10;
FillRect(hdc, &z, b);
z.bottom -= 2; // extra padding on bottom because it's at edge of window
SetTextColor(hdc, RGB(255,255,255));
DrawText(hdc, name, -1, &z, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
if (old) SelectObject(hdc, old);
}
if (show_help) {
int h2;
RECT box = rect;
// measure height of longest text
DrawText(hdc, helptext_left, -1, &box, DT_CALCRECT);
h2 = box.bottom - box.top;
// build rect of correct height
box = rect;
box.top = stb_max((h - h2) >> 1, 0);
//box.bottom = box.top + h2;
// expand on left & right so following code is well behaved
// (we're centered anyway, so the exact numbers don't matter)
box.left -= 200; box.right += 200;
// draw center text
draw_nice(hdc, helptext_center, &box, DT_CENTER);
// displace box to left and draw left column
box.left -= 150; box.right -= 150;
draw_nice(hdc, helptext_left, &box, DT_CENTER);
// displace box to right and draw right column
box.left += 300; box.right += 300;
draw_nice(hdc, helptext_right, &box, DT_CENTER);
}
}
typedef struct
{
int x,y;
int w,h;
} queued_size;
// most recent unsatisfied resize request (private to main thread)
queued_size qs;
// active resize request, mainly just used by main thread (resize
// thread writes to 'image' field.
struct
{
queued_size size;
Image *image;
char *filename;
ImageFile *image_c;
} pending_resize;
// temporary structure for communicating across stb_workq() call
typedef struct
{
ImageFile *src;
Image dest;
Image *result;
} Resize;
// threaded image resizer, uses work queue AND current thread
void image_resize(Image *dest, Image *src);
// wrapper for image_resize() to be called via work queue
void * work_resize(void *p)
{
Resize *r = (Resize *) p;
image_resize(&r->dest, r->src->image);
return r->result;
}
// dedicate workqueue workers for resizing
stb_workqueue *resize_workers;
// compute the size to resize an image to given a target window (gw,gh);
// we assume the input window (sw,wh) has already been expanded by its
// frame size.
void compute_size(int gw, int gh, int sw, int sh, int *ox, int *oy)
{
// shrink the target by the padding (the size of the frame)
gw -= FRAME*2;
gh -= FRAME*2;
// shrink the source to remove the frame
sw -= FRAME*2;
sh -= FRAME*2;
// compute the raw pixel resize
if (gw*sh > gh*sw) {
*oy = gh;
*ox = gh * sw/sh;
} else {
*ox = gw;
*oy = gw * sh/sw;
}
}
// resize an image. if immediate=TRUE, we run it from the main thread
// and won't return until it's resized; if !immediate, we hand it to
// a workqueue and return before it's done. (note that if immediate=TRUE,
// we still use the work queue to accelerate, if possible)
void queue_resize(int w, int h, ImageFile *src_c, int immediate)
{
static Resize res; // must be static because we expose (very briefly) to other thread
Image *src = src_c->image;
Image *dest;
int w2,h2;
if (!immediate) assert(pending_resize.size.w);
if (src_c == NULL) return;
// create (w2,h2) matching aspect ratio of w/h
compute_size(w,h,src->x+FRAME*2,src->y+FRAME*2,&w2,&h2);
// create output of the appropriate size
dest = bmp_alloc(w2+FRAME*2,h2+FRAME*2);
assert(dest);
if (!dest) return;
// encode the border around it
frame(dest);
// build the parameter list for image_resize
res.src = src_c;
res.dest = image_region(dest, FRAME, FRAME, w2, h2);
res.result = dest;
if (!immediate) {
// update status to be owned by the resizer (which isn't running yet,
// so there's no thread issues here)
src_c->status = LOAD_resizing;
// store data to come back for later
pending_resize.image = NULL;
pending_resize.image_c = src_c;
pending_resize.filename = strdup(src_c->filename);
// run the resizer in the background (equivalent to the call below)
stb_workq(resize_workers, work_resize, &res, &pending_resize.image);
} else {
// run the resizer in the main thread
pending_resize.image = work_resize(&res);
}
}
// put a resize request in the "queue" (which is only one deep)
void enqueue_resize(int left, int top, int width, int height)
{
if (cur && ((width == cur->x && height >= cur->y) || (height == cur->y && width >= cur->x))) {
// if we have a current image, and that image can satisfy the request (they're
// dragging one side of the image out wider), just immediately update the window
qs.w = 0; // clear the queue
if (!show_frame) left += FRAME, top += FRAME, width -= 2*FRAME, height -= 2*FRAME;
MoveWindow(win, left, top, width, height, TRUE);
InvalidateRect(win, NULL, FALSE);
} else {
// otherwise store the most recent request for processing in the main thread
qs.x = left;
qs.y = top;
qs.w = width;
qs.h = height;
}
}
// do all operations _as if_ we had the frame
void GetAdjustedWindowRect(HWND win, RECT *rect)
{
GetWindowRect(win, rect);
if (!show_frame) {
rect->left -= FRAME;
rect->top -= FRAME;
rect->right += FRAME;
rect->bottom += FRAME;
}
}
int allow_fullsize;