about summary refs log tree commit diff
path: root/editor/specialty/pnmindex.c
blob: 0a8e35cc6d491068a7a41067ca7cec9ce81d3d3b (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
/*============================================================================
                              pnmindex   
==============================================================================

  build a visual index of a bunch of PNM images

  This used to be a C shell program, and then a BASH program.  Neither
  were portable enough, and the program is too complex for either of
  those languages anyway, so now it's in C.

  By Bryan Henderson 2005.04.24.

  Contributed to the public domain by its author.

============================================================================*/

#define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
#define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
#define _BSD_SOURCE   /* Make sure strdup is in string.h */

#include <assert.h>
#include <unistd.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/stat.h>


#include "pm_config.h"
#include "pm_c_util.h"
#include "shhopt.h"
#include "mallocvar.h"
#include "nstring.h"
#include "pnm.h"

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    unsigned int  inputFileCount;
    const char ** inputFileName;
    unsigned int  size;
    unsigned int  across;
    unsigned int  colors;
    unsigned int  black;
    unsigned int  noquant;
    const char *  title;
    unsigned int  verbose;
};

static bool verbose;



static void PM_GNU_PRINTF_ATTR(1,2)
systemf(const char * const fmt,
        ...) {

    va_list varargs;
    
    size_t dryRunLen;
    
    va_start(varargs, fmt);
    
    pm_vsnprintf(NULL, 0, fmt, varargs, &dryRunLen);

    va_end(varargs);

    if (dryRunLen + 1 < dryRunLen)
        /* arithmetic overflow */
        pm_error("Command way too long");
    else {
        size_t const allocSize = dryRunLen + 1;
        char * shellCommand;
        shellCommand = malloc(allocSize);
        if (shellCommand == NULL)
            pm_error("Can't get storage for %u-character command",
                     (unsigned)allocSize);
        else {
            va_list varargs;
            size_t realLen;
            int rc;

            va_start(varargs, fmt);

            pm_vsnprintf(shellCommand, allocSize, fmt, varargs, &realLen);
                
            assert(realLen == dryRunLen);
            va_end(varargs);

            if (verbose)
                pm_message("shell cmd: %s", shellCommand);

            rc = system(shellCommand);
            if (rc != 0)
                pm_error("shell command '%s' failed.  rc %d",
                         shellCommand, rc);
            
            pm_strfree(shellCommand);
        }
    }
}
        


static void
parseCommandLine(int argc, char ** argv, 
                 struct cmdlineInfo * const cmdlineP) {

    unsigned int option_def_index;
    optEntry *option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int quant;
    unsigned int sizeSpec, colorsSpec, acrossSpec, titleSpec;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "black",       OPT_FLAG,   NULL,                  
            &cmdlineP->black,         0);
    OPTENT3(0, "noquant",     OPT_FLAG,   NULL,                  
            &cmdlineP->noquant,       0);
    OPTENT3(0, "quant",       OPT_FLAG,   NULL,                  
            &quant,                   0);
    OPTENT3(0, "verbose",     OPT_FLAG,   NULL,                  
            &cmdlineP->verbose,       0);
    OPTENT3(0, "size",        OPT_UINT,   &cmdlineP->size,
            &sizeSpec,                0);
    OPTENT3(0, "colors",      OPT_UINT,   &cmdlineP->colors,
            &colorsSpec,              0);
    OPTENT3(0, "across",      OPT_UINT,   &cmdlineP->across,
            &acrossSpec,              0);
    OPTENT3(0, "title",       OPT_STRING, &cmdlineP->title,
            &titleSpec,               0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE; 

    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
        /* Uses and sets argc, argv, and some of *cmdline_p and others. */

    if (quant && cmdlineP->noquant)
        pm_error("You can't specify both -quant and -noquat");

    if (!colorsSpec)
        cmdlineP->colors = 256;
    
    if (!sizeSpec)
        cmdlineP->size = 100;

    if (!acrossSpec)
        cmdlineP->across = 6;

    if (!titleSpec)
        cmdlineP->title = NULL;

    if (colorsSpec && cmdlineP->noquant)
        pm_error("-colors doesn't make any sense with -noquant");

    if (argc-1 < 1)
        pm_error("You must name at least one file that contains an image "
                 "to go into the index");

    cmdlineP->inputFileCount = argc-1;

    MALLOCARRAY_NOFAIL(cmdlineP->inputFileName, cmdlineP->inputFileCount);

    {
        unsigned int i;
        for (i = 0; i < cmdlineP->inputFileCount; ++i) {
            cmdlineP->inputFileName[i] = strdup(argv[i+1]);
            if (cmdlineP->inputFileName[i] == NULL)
                pm_error("Unable to allocate memory for a file name");
        }
    }
}



static void
freeCmdline(struct cmdlineInfo const cmdline) {

    unsigned int i;

    for (i = 0; i < cmdline.inputFileCount; ++i)
        pm_strfree(cmdline.inputFileName[i]);

    free(cmdline.inputFileName);

}



static void
makeTempDir(const char ** const tempDirP) {

    const char * const tmpdir = getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp";

    const char * mytmpdir;
    int rc;

    pm_asprintf(&mytmpdir, "%s/pnmindex_%d", tmpdir, getpid());

    rc = pm_mkdir(mytmpdir, 0700);
    if (rc != 0)
        pm_error("Unable to create temporary file directory '%s'.  mkdir() "
                 "fails with errno %d (%s)",
                 mytmpdir, errno, strerror(errno));

    *tempDirP = mytmpdir;
}



static void
removeTempDir(const char * const tempDir) {

    int rc;

    rc = rmdir(tempDir);
    if (rc != 0)
        pm_error("Failed to remove temporary file directory '%s'.  "
                 "rmdir() fails with errno %d (%s)",
                 tempDir, errno, strerror(errno));
}


static const char *
rowFileName(const char * const dirName,
            unsigned int const row) {

    const char * fileName;
    
    pm_asprintf(&fileName, "%s/pi.%u", dirName, row);
    
    return fileName;
}



static void
makeTitle(const char * const title,
          unsigned int const rowNumber,
          bool         const blackBackground,
          const char * const tempDir) {

    const char * const invertStage = blackBackground ? "| pnminvert " : "";

    const char * fileName;

    fileName = rowFileName(tempDir, rowNumber);

    /* This quoting is not adequate.  We really should do this without
       a shell at all.
    */
    systemf("pbmtext \"%s\" "
            "%s"
            "> %s", 
            title, invertStage, fileName);

    pm_strfree(fileName);
}



static void
copyImage(const char * const inputFileName,
          const char * const outputFileName) {

    systemf("cat %s > %s", inputFileName, outputFileName);
} 



static void
copyScaleQuantImage(const char * const inputFileName,
                    const char * const outputFileName,
                    int          const format,
                    unsigned int const size,
                    unsigned int const quant,
                    unsigned int const colors) {

    const char * scaleCommand;

    switch (PNM_FORMAT_TYPE(format)) {
    case PBM_TYPE:
        pm_asprintf(&scaleCommand, 
                    "pamscale -quiet -xysize %u %u %s "
                    "| pgmtopbm > %s",
                    size, size, inputFileName, outputFileName);
        break;
        
    case PGM_TYPE:
        pm_asprintf(&scaleCommand, 
                    "pamscale -quiet -xysize %u %u %s >%s",
                    size, size, inputFileName, outputFileName);
        break;
        
    case PPM_TYPE:
        if (quant)
            pm_asprintf(&scaleCommand, 
                        "pamscale -quiet -xysize %u %u %s "
                        "| pnmquant -quiet %u > %s",
                        size, size, inputFileName, colors, outputFileName);
        else
            pm_asprintf(&scaleCommand, 
                        "pamscale -quiet -xysize %u %u %s >%s",
                        size, size, inputFileName, outputFileName);
        break;
    default:
        pm_error("Unrecognized Netpbm format: %d", format);
    }

    systemf("%s", scaleCommand);

    pm_strfree(scaleCommand);
}



static int
formatTypeMax(int const typeA,
              int const typeB) {

    if (typeA == PPM_TYPE || typeB == PPM_TYPE)
        return PPM_TYPE; 
    else if (typeA == PGM_TYPE || typeB == PGM_TYPE)
        return PGM_TYPE;
    else
        return PBM_TYPE;
}



static const char *
thumbnailFileName(const char * const dirName,
                  unsigned int const row,
                  unsigned int const col) {

    const char * fileName;
    
    pm_asprintf(&fileName, "%s/pi.%u.%u", dirName, row, col);
    
    return fileName;
}



static const char *
thumbnailFileList(const char * const dirName,
                  unsigned int const row,
                  unsigned int const cols) {

    unsigned int const maxListSize = 4096;

    char * list;
    unsigned int col;

    list = malloc(maxListSize);
    if (list == NULL)
        pm_error("Unable to allocate %u bytes for file list", maxListSize);

    list[0] = '\0';
    
    for (col = 0; col < cols; ++col) {
        const char * const fileName = thumbnailFileName(dirName, row, col);

        if (strlen(list) + strlen(fileName) + 1 > maxListSize - 1)
            pm_error("File name list too long for this program to handle.");
        else {
            strcat(list, " ");
            strcat(list, fileName);
        }
        pm_strfree(fileName);
    }

    return list;
}



static void
makeImageFile(const char * const thumbnailFileName,
              const char * const inputFileName,
              bool         const blackBackground,
              const char * const outputFileName) {

    const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";
    const char * const invertStage = blackBackground ? "| pnminvert " : "";

    systemf("pbmtext \"%s\" "
            "%s"
            "| pnmcat %s -topbottom %s - "
            "> %s",
            inputFileName, invertStage, blackWhiteOpt, 
            thumbnailFileName, outputFileName);
}    



static void
makeThumbnail(const char *  const inputFileName,
              unsigned int  const size,
              bool          const black,
              bool          const quant,
              unsigned int  const colors,
              const char *  const tempDir,
              unsigned int  const row,
              unsigned int  const col,
              int *         const formatP) {

    FILE * ifP;
    int imageCols, imageRows, format;
    xelval maxval;
    const char * tmpfile;
    const char * fileName;
        
    ifP = pm_openr(inputFileName);
    pnm_readpnminit(ifP, &imageCols, &imageRows, &maxval, &format);
    pm_close(ifP);
    
    pm_asprintf(&tmpfile, "%s/pi.tmp", tempDir);

    if (imageCols < size && imageRows < size)
        copyImage(inputFileName, tmpfile);
    else
        copyScaleQuantImage(inputFileName, tmpfile, format, 
                            size, quant, colors);

    fileName = thumbnailFileName(tempDir, row, col);
        
    makeImageFile(tmpfile, inputFileName, black, fileName);

    unlink(tmpfile);

    pm_strfree(fileName);
    pm_strfree(tmpfile);

    *formatP = format;
}
        


static void
unlinkThumbnailFiles(const char * const dirName,
                     unsigned int const row,
                     unsigned int const cols) {

    unsigned int col;
    
    for (col = 0; col < cols; ++col) {
        const char * const fileName = thumbnailFileName(dirName, row, col);

        unlink(fileName);

        pm_strfree(fileName);
    }
}



static void
unlinkRowFiles(const char * const dirName,
               unsigned int const rows) {

    unsigned int row;
    
    for (row = 0; row < rows; ++row) {
        const char * const fileName = rowFileName(dirName, row);

        unlink(fileName);

        pm_strfree(fileName);
    }
}



static void
combineIntoRowAndDelete(unsigned int const row,
                        unsigned int const cols,
                        int          const maxFormatType,
                        bool         const blackBackground,
                        bool         const quant,
                        unsigned int const colors,
                        const char * const tempDir) {

    const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";

    const char * fileName;
    const char * quantStage;
    const char * fileList;
    
    fileName = rowFileName(tempDir, row);

    unlink(fileName);

    if (maxFormatType == PPM_TYPE && quant)
        pm_asprintf(&quantStage, "| pnmquant -quiet %u ", colors);
    else
        quantStage = strdup("");

    fileList = thumbnailFileList(tempDir, row, cols);

    systemf("pnmcat %s -leftright -jbottom %s "
            "%s"
            ">%s",
            blackWhiteOpt, fileList, quantStage, fileName);

    pm_strfree(fileList);
    pm_strfree(quantStage);
    pm_strfree(fileName);

    unlinkThumbnailFiles(tempDir, row, cols);
}



static const char *
rowFileList(const char * const dirName,
            unsigned int const rows) {

    unsigned int const maxListSize = 4096;

    unsigned int row;
    char * list;

    list = malloc(maxListSize);
    if (list == NULL)
        pm_error("Unable to allocate %u bytes for file list", maxListSize);

    list[0] = '\0';

    for (row = 0; row < rows; ++row) {
        const char * const fileName = rowFileName(dirName, row);

        if (strlen(list) + strlen(fileName) + 1 > maxListSize - 1)
            pm_error("File name list too long for this program to handle.");
        
        else {
            strcat(list, " ");
            strcat(list, fileName);
        }
        pm_strfree(fileName);
    }

    return list;
}



static void
writeRowsAndDelete(unsigned int const rows,
                   int          const maxFormatType,
                   bool         const blackBackground,
                   bool         const quant,
                   unsigned int const colors,
                   const char * const tempDir) {

    const char * const blackWhiteOpt = blackBackground ? "-black" : "-white";

    const char * quantStage;
    const char * fileList;
    
    if (maxFormatType == PPM_TYPE && quant)
        pm_asprintf(&quantStage, "| pnmquant -quiet %u ", colors);
    else
        quantStage = strdup("");

    fileList = rowFileList(tempDir, rows);

    systemf("pnmcat %s -topbottom %s %s",
            blackWhiteOpt, fileList, quantStage);

    pm_strfree(fileList);
    pm_strfree(quantStage);

    unlinkRowFiles(tempDir, rows);
}



int
main(int argc, char *argv[]) {
    struct cmdlineInfo cmdline;
    const char * tempDir;
    int maxFormatType;
    unsigned int colsInRow;
    unsigned int rowsDone;
    unsigned int i;

    pnm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    verbose = cmdline.verbose;
    
    makeTempDir(&tempDir);

    maxFormatType = PBM_TYPE;
    colsInRow = 0;
    rowsDone = 0;

    if (cmdline.title)
        makeTitle(cmdline.title, rowsDone++, cmdline.black, tempDir);

    for (i = 0; i < cmdline.inputFileCount; ++i) {
        const char * const inputFileName = cmdline.inputFileName[i];

        int format;

        makeThumbnail(inputFileName, cmdline.size, cmdline.black, 
                      !cmdline.noquant, cmdline.colors, tempDir,
                      rowsDone, colsInRow, &format);

        maxFormatType = formatTypeMax(maxFormatType, PNM_FORMAT_TYPE(format));

        ++colsInRow;
        if (colsInRow >= cmdline.across || i == cmdline.inputFileCount-1) {
            combineIntoRowAndDelete(
                rowsDone, colsInRow, maxFormatType,
                cmdline.black, !cmdline.noquant, cmdline.colors,
                tempDir);
            ++rowsDone;
            colsInRow = 0;
        }
    }

    writeRowsAndDelete(rowsDone, maxFormatType, cmdline.black,
                       !cmdline.noquant, cmdline.colors, tempDir);

    removeTempDir(tempDir);

    freeCmdline(cmdline);

    pm_close(stdout);

    return 0;
}