source: projects/paper-tape-project/trunk/visualisator/cli.c @ 78

Last change on this file since 78 was 78, checked in by sven, 11 years ago

Major improvements in making the Paper Tape Projects ready for deploying:

  • Written a 21 page manual in German (LaTeX, PDF)
  • Visualisator is running, export works, lesser bugs
  • some new perl-tools
  • a bin directory with softlinks
  • You can "install" the paper tape projects right now.
File size: 13.8 KB
Line 
1/**
2 * cli.c: An exemplar, but fully functional and highly configurable
3 * command line interface (CLI) to the paper tape low level drawing
4 * routines (lochstreifen.c), which uses the famous cairo graphics
5 * library for drawing.
6 *
7 * See ./program --help for an overview about the self-explanatory
8 * arguments. By default, the program will read in any files in
9 * stdin and print the genereated PNG file on stdout.
10 *
11 * This program is written in english only (but the sourcecode
12 * contains some german comments). See an exemplar usage of this
13 * program in a PHP web program in the web-frontend subproject.
14 *
15 * This program uses the argp.h argument parser from the glibc.
16 * Thus it unfortunately won't compile with any other libc.
17 *
18 * Copyright (C) 2008  Sven Köppel
19 *
20 * This program is free software; you can redistribute it and/or
21 * modify it under the terms of the GNU General Public License as
22 * published by the Free Software Foundation; either version 3 of
23 * the License, or (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, see
32 * <http://www.gnu.org/licenses/>.
33 *
34 **/
35
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <argp.h>
40
41#include "lochstreifen.h"
42
43LOCHSTREIFEN *l;
44lochstreifen_export_type surface_type;
45char *output_file;
46int verbosity = 0;
47int null_bytes_start = 0;
48int null_bytes_end = 0;
49enum {
50        SCALE_BY_LENGTH,
51        SCALE_BY_WIDTH,
52        SCALE_BY_CODE_HOLE,
53} scale_by;
54// scale_target == 0 implies: no scaling!
55int scale_target = 0;
56
57#define DPRINTF(msg...) if(verbosity!=0) fprintf(stderr,msg);
58
59error_t parse_option (int key, char *arg, struct argp_state *state);
60cairo_pattern_t *hex2cairo_pattern(const char *string);
61
62const char *argp_program_version = "Punch card visualisator - CLI frontend";
63
64static struct argp_option options[] = {
65    {"verbose",     'v',   0,      0,  "Produce verbose output on stderr" },
66    //{"quiet",       'q',   0,      0,  "Don't produce any output" },
67    //{"silent",      's',   0,      OPTION_ALIAS },
68
69    {"output",   'o', "FILE", 0,   "Output to FILE (instead of standard output)" },
70    {"image",    'i', 0, OPTION_ALIAS },
71    {"format",   'f', "SVG|PNG",0,  "Set desired output image format (PNG or SVG)" },
72    {"", 0, 0, OPTION_DOC, ""},
73
74    {"Dimensions", 0, 0, OPTION_DOC, "Dimensions are integers without units"},
75    {"width",    'w', "NUM",      0,  "Set desired width for output image (in px or points, according to output format)", 1 },
76    {"height",   'h', "NUM",      0,  "Set desired height for output image (unit like width argument)", 1 },
77    {"diameter", 'd', "NUM",      0,  "Set dimensions for output image by punched hole diameter (pixel)", 1 },
78    {"", 0, 0, OPTION_DOC, "",1},
79
80    {"Empty bytes", 1, 0, OPTION_DOC, "Bytes with value=0x00 which are not content of files", 1},
81    {"empty-start", -1, "NUM", 0,        "Set number of empty bytes at beginning (default=0)", 2 },
82    {"empty-end",   -2, "NUM", 0,        "Set number of empty bytes at end (default=0)", 2 },
83    {"", 0, 0, OPTION_DOC, "",2},
84
85    {"Colors", 0, 0, OPTION_DOC, "Color format: #RGB[A], #RRGGBB[AA]", 2 },
86    {"hide-imagebg",    -3, 0, 0, "Make the image background (space around paper tape) transparent", 3 },
87    {"color-imagebg",   -4, "#RGBA", 0, "Set image background color", 3 },
88    {"hide-tapebg",     -5, 0, 0, "Hide the paper tape background", 3 },
89    {"color-tapebg",    -6, "#RGBA", 0, "Set tape background color", 3 },
90    {"hide-punched",    -7, 0, 0, "Hide the holes (only the punched ones)", 3 },
91    {"color-punched",   -8, "#RGBA", 0, "Set color of holes (punched bits)", 3 },
92    {"hide-notpunched", -9, 0, 0, "Hide the holes which aren't punched on real tapes", 3 },
93    {"color-notpunched",-10, "#RGBA", 0, "Set color of bits with boolean value \"false\"", 3 },
94    {"hide-feedholes",  -11, 0, 0, "Hide the feed holes (which means they wouldn't be punched)", 3 },
95    {"color-feedholes", -12, "#RGBA", 0, "Set color of feed holes (the small ones)", 3 },
96    {"", 0, 0, OPTION_DOC, "",3},
97
98    {"Transformations and Rotations", 0, 0, OPTION_DOC, "", 3},
99    {"rotation",       -13, "right|bottom|left|top", 0, "Rotation of punched tape (alternative short notation: 0=right, 1=bottom, 2=left, 3=top)", 4 },
100    {"reflection-byte-direction",  -14, 0, 0, "Enables horizontal reflecion on the data axis (inverts data direction)", 4 },
101    {"reflection-bit-direction",   -15, 0, 0, "Enables vertical reflection on the other axis (inverts bit direction)", 4 },
102    {"", 0, 0, OPTION_DOC, "",-2},
103
104    { 0 }
105};
106
107static struct argp argp = { options, parse_option, "[FILE TO READ FROM]", // Als Argument in der ersten Zeile
108    "This program uses cairo to draw a punched tape as a PNG or SVG file. Any binary " // Hilfe oben
109    "data are accepted via stdin or read in from the file given as argument. "
110    "The produced image is written into stdout or in the filename given by -o."
111    // mit \v danach koennte man ausfuehrliche Hilfe unten anzeigen.
112}; // static struct argp
113
114
115error_t parse_option (int key, char *arg, struct argp_state *state) {
116        //printf("OPTION %x (%c = %i)...\n", key, key, key);
117        switch(key) {
118                case 'v':
119                        verbosity = 1;
120                        break;
121                case 'o': case 'i':
122                        // Ausgabedatei setzen.
123                        output_file = arg;
124                        break;
125                case 'w':
126                        // set length (yeah, the legacy parameters call this width)
127                        scale_by = SCALE_BY_LENGTH;
128                        scale_target = atoi(arg);
129                        //lochstreifen_set_scaling_by_length(l, atoi(arg));
130                        break;
131                case 'h':
132                        // set width (yeah, the legacy parameters call this height)
133                        scale_by = SCALE_BY_WIDTH;
134                        scale_target = atoi(arg);
135                        //lochstreifen_set_scaling_by_width(l, atoi(arg));
136                        break;
137                case 'd':
138                        // set diameter of code holes
139                        scale_by = SCALE_BY_CODE_HOLE;
140                        scale_target = atoi(arg);
141                        //lochstreifen_set_scaling_by_code_hole(l, atoi(arg));
142                        break;
143                case 'f':
144                        // set file format
145                        if(strcasecmp(arg, "png") == 0)
146                                surface_type = LOCHSTREIFEN_FORMAT_PNG;
147                        else if(strcasecmp(arg, "svg") == 0)
148                                surface_type = LOCHSTREIFEN_FORMAT_SVG;
149                        else
150                                argp_error(state, "Only PNG and SVG are supported as file formats.\n");
151                        break;
152                case -1:
153                        // set empty bytes at start
154                        null_bytes_start = atoi(arg);
155                        break;
156                case -2:
157                        // set empty bytes at end
158                        null_bytes_end = atoi(arg);
159                        break;
160                case -3:
161                        // hide imagebg
162                        l->outer_background_color = NULL;
163                        break;
164                case -4:
165                        // color imagebg
166                        l->outer_background_color = hex2cairo_pattern(arg);
167                        break;
168                case -5:
169                        // hide tape
170                        l->papertape_background_color = NULL;
171                        break;
172                case -6:
173                        // color tapebg
174                        l->papertape_background_color = hex2cairo_pattern(arg);
175                        break;
176                case -7:
177                        // hide punched
178                        l->one_code_hole_color = NULL;
179                        break;
180                case -8:
181                        // color punched
182                        l->one_code_hole_color = hex2cairo_pattern(arg);
183                        break;
184                case -9:
185                        // hide notpunched
186                        l->zero_code_hole_color = NULL;
187                        break;
188                case -10:
189                        // color notpunched
190                        l->zero_code_hole_color = hex2cairo_pattern(arg);
191                        break;
192                case -11:
193                        // hide feedholes
194                        l->feed_hole_color = NULL;
195                        break;
196                case -12:
197                        // color fuerhung
198                        l->feed_hole_color = hex2cairo_pattern(arg);
199                        break;
200                case -13:
201                        // rotation
202                        if     (strcasecmp(arg, "right" ) == 0) arg = "0";
203                        else if(strcasecmp(arg, "bottom") == 0) arg = "1";
204                        else if(strcasecmp(arg, "left"  ) == 0) arg = "2";
205                        else if(strcasecmp(arg, "top"   ) == 0) arg = "3";
206                        arg[1] = '\0'; // shorten string to one character
207                        //lochstreifen_set_direction(l, atoi(arg));
208                        lochstreifen_set_rotation(l, atoi(arg));
209                        break;
210                case -14:
211                        // horizontal spiegeln
212                        //lochstreifen_set_direction(l, -1, 1, -1);
213                        break;
214                case -15:
215                        // vertikal spiegeln
216                        //lochstreifen_set_direction(l, -1, -1, 1);
217                        break;
218                //case ARGP_KEY_END:
219                        //printf("bla...");
220                default:
221                        return ARGP_ERR_UNKNOWN;
222        } // switch
223        return 0; // success
224} // function parse_option
225
226
227/**
228 * Simple helper function to get a SOLID cairo pattern from a hex color string
229 * with formats like
230 *   #RGB          for example:   #FF0
231 *   #RGBA                        #A88F
232 *   #RRGGBB                      #CD438F
233 *   #RRGGBBAA                    #CD438FA0
234 *   RGB                          FF0
235 *   RGBA                         A88F
236 *   RRGGBB                       CD438F
237 *   RRGGBBAA                     CD438FA0
238 *
239 * If this method cannot parse the hex color string, it will print an error message
240 * at stderr and exit the complete program.
241 *
242 * @return a dynamically allocated cairo patern
243 **/
244cairo_pattern_t *hex2cairo_pattern(const char *string) {
245        int string_len;        // length of string without "#"
246        int x, color;          // iterators
247        long color_value[4]; // interpreted numbers
248        char buf[3] = "xy";       // Buffer for strtol <- one color value
249       
250        // remove a "#" char if present
251        if(string[0] == '#')
252                string++;
253        string_len = strlen(string);
254       
255        // go throught string
256        for(x=0,color=0; x < string_len && color < 5; x++,color++) {
257                // copy the current character to buffer, first position
258                buf[0] = string[x];
259                // if short notation (shorter than AABBCC), dublicate
260                // current character to buffer second position, else
261                // copy next character to second position
262                buf[1] = string_len < 6 ? string[x] : string[++x];
263                // parse buffer contents and save them as one color
264                color_value[color] = strtol(buf, NULL, 16);
265        }
266       
267        DPRINTF("Allocating '%s' as #%02x%02x%02x%02x\n", string,
268                (unsigned int) color_value[0], (unsigned int) color_value[1], (unsigned int)color_value[2], (color == 4) ? (unsigned int) color_value[3] : 0xFF);
269       
270        return cairo_pattern_create_rgba(
271                (double) color_value[0] / (double) 0xFF,
272                (double) color_value[1] / (double) 0xFF,
273                (double) color_value[2] / (double) 0xFF,
274                (color == 4) ? (double) color_value[3] / (double) 0xFF : 1
275        );
276}
277
278/**
279 * Helper function: Read contents from a stream (e.g. stdin or a file) into
280 * a byte array.
281 * Expects: stream (FILE) and a pointer to a pointer (for the target array)
282 * It will allocate an array whereby you get the pointer back.
283 * @return length of data array, counting from 1
284 *
285 * I've inspired a bit from glib's g_file_get_contents because my first
286 * version was quite buggy:
287 *****
288     * Neugeschrieben nach etwas Inspiration von der glib am 05.04.2008.
289     * Funktion get_contents_stdio, gfileutils.c im Sourcecode von glib-2.14.3.
290     * Router natürlich aus (03:11!), aber da sieht man mal wieder den Vorteil von Gentoo:
291     * Gleich alle Sourcecodes auf der Platte =)
292 *****
293 *
294 **/
295int file_get_contents(FILE *stream, byte_t **content) {
296        byte_t buf[4096];
297        size_t bytes; // gerade eben eingelesene bytes
298        byte_t *str = NULL;
299        size_t total_bytes = 0;     // alle bis jetzt eingelesenen bytes
300        size_t total_allocated = 0;
301        byte_t *tmp; // fuers realloc
302
303        while(!feof(stream)) {
304                bytes = fread(buf, 1, sizeof(buf), stream);
305
306                while( (total_bytes + bytes) > total_allocated) {
307                        if(str)
308                                total_allocated *= 2;
309                        else
310                                total_allocated = bytes > sizeof(buf) ? bytes : sizeof(buf);
311
312                        tmp = realloc(str, total_allocated);
313
314                        if(tmp == NULL) {
315                                fprintf(stderr, "*** file_get_contents ERROR*** Could not reallocate\n");
316                                //return length; // Fehler - das eingelesene zumindest zurueckgeben.
317                                // nee, gar nichts zurückgeben. Das geht so nicht.
318                                return 0;
319                        }
320
321                        str = tmp;
322                } // while innen
323
324                memcpy(str + total_bytes, buf, bytes);
325                total_bytes += bytes;
326        } // while
327
328        if(total_allocated == 0)
329                str = malloc(1); // something empty. Just to be not NULL...
330        //str[total_bytes] = '\0'; // wenns ein string wäre.
331
332        *content = str;
333        return total_bytes;
334}
335
336
337/**
338 * The main routine.
339 **/
340int main(int argc, char *argv[]) {
341        byte_t *data;               ///< the data array, will be filled by file_get_contents
342        int length;                 ///< the length of that data array
343        FILE *out;                  ///< an output stream handle (stdout or a file)
344        int input_argc;             ///< argp: index of argv argument where the filenames are stored
345       
346        // now starting...
347        l = lochstreifen_new();
348        argp_parse(&argp, argc, argv, 0, &input_argc, NULL);
349       
350        // read input data to data array
351        if(input_argc < argc && argv[input_argc][0] != '-') {
352                // open a file (which name is not "-", because this shall read from STDIN)
353                FILE *fh;
354                DPRINTF("Reading from file %s\n", argv[input_argc]);
355                fh = fopen(argv[input_argc], "r");
356
357                if(fh == NULL) {
358                        perror("opening input file");
359                        exit(1);
360                }
361
362                length = file_get_contents(fh, &data);
363                fclose(fh);
364        } else {
365                DPRINTF("Reading from stdin, type [STRG]+[D] to generate paper tape from data\n");
366                length = file_get_contents(stdin, &data);
367        }
368
369        DPRINTF("Successfully read in %d bytes to RAM\n", length);
370       
371        // now after bytes are read in, we can setup the LOCHSTREIFEN
372        // correctly:
373        lochstreifen_set_data(l, length, data);
374        if(scale_target != 0) { // initialized
375                switch(scale_by) {
376                        case SCALE_BY_LENGTH:
377                                lochstreifen_set_scaling_by_length(l, scale_target);
378                                break;
379                        case SCALE_BY_WIDTH:
380                                lochstreifen_set_scaling_by_width(l, scale_target);
381                                break;
382                        case SCALE_BY_CODE_HOLE:
383                                lochstreifen_set_scaling_by_code_hole(l, scale_target);
384                }
385        }
386        // add null bytes
387        lochstreifen_add_null_bytes(l, null_bytes_start, null_bytes_end);
388
389        // open output stream
390        if(output_file != NULL) { // check if there was an argv argument
391                out = fopen(output_file, "w");
392
393                if(out == NULL) {
394                        perror("opening output file");
395                        exit(1);
396                }
397                DPRINTF("Opened file '%s' for writing\n", output_file);
398        } else {
399                DPRINTF("Writing output data to stdout\n");
400                out = stdout;
401        }
402       
403        if(verbosity!=0)
404                lochstreifen_print_debug(l);
405
406        cairo_status_t status = lochstreifen_export(l, surface_type, out);
407       
408        DPRINTF("%s file generated: %s\n", surface_type == LOCHSTREIFEN_FORMAT_PNG ? "PNG" : "SVG",
409                cairo_status_to_string(status));
410} // main
Note: See TracBrowser for help on using the repository browser.
© 2008 - 2013 technikum29 • Sven Köppel • Some rights reserved
Powered by Trac
Expect where otherwise noted, content on this site is licensed under a Creative Commons 3.0 License