de3f5a378464bb6c8b44b02d9a4acb706d5f47dc
[vrfileman] / src / opt.cc
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <optcfg.h>
5 #include "opt.h"
6
7 Options opt;
8
9 enum {
10         OPT_SIZE,
11         OPT_VR,
12         OPT_SRGB,
13         OPT_FULLSCREEN,
14         OPT_WINDOWED,
15         OPT_HELP
16 };
17
18 static optcfg_option options[] = {
19         // short, long, id, desc
20         {'s', "size", OPT_SIZE, "window size (WxH)"},
21         {0, "vr", OPT_VR, "enable VR mode"},
22         {0, "srgb", OPT_SRGB, "use linear color space"},
23         {'f', "fullscreen", OPT_FULLSCREEN, "run in fullscreen mode"},
24         {'w', "windowed", OPT_WINDOWED, "run in windowed mode"},
25         {'h', "help", OPT_HELP, "print usage and exit"},
26         OPTCFG_OPTIONS_END
27 };
28
29 static int opt_handler(optcfg *oc, int opt, void *cls);
30
31 bool init_options(int argc, char **argv, const char *cfgfile)
32 {
33         // default options
34         memset(&opt, 0, sizeof opt);
35         opt.width = 1280;
36         opt.height = 800;
37         opt.srgb = true;
38
39         optcfg *oc = optcfg_init(options);
40         optcfg_set_opt_callback(oc, opt_handler, 0);
41
42         if(cfgfile) {
43                 optcfg_parse_config_file(oc, cfgfile);
44         }
45
46         if(argv && optcfg_parse_args(oc, argc, argv) == -1) {
47                 fprintf(stderr, "invalid option\n");
48                 optcfg_destroy(oc);
49                 return false;
50         }
51
52         optcfg_destroy(oc);
53         return true;
54 }
55
56 static bool is_enabled(optcfg *oc)
57 {
58         int res;
59         optcfg_enabled_value(oc, &res);
60         return res != 0;
61 }
62
63 static int opt_handler(optcfg *oc, int optid, void *cls)
64 {
65         switch(optid) {
66         case OPT_SIZE:
67                 {
68                         char *valstr = optcfg_next_value(oc);
69                         if(!valstr || sscanf(valstr, "%dx%d", &opt.width, &opt.height) != 2) {
70                                 fprintf(stderr, "size must be in the form: WIDTHxHEIGHT\n");
71                                 return -1;
72                         }
73                 }
74                 break;
75
76         case OPT_VR:
77                 opt.vr = is_enabled(oc);
78                 break;
79
80         case OPT_SRGB:
81                 opt.srgb = is_enabled(oc);
82                 break;
83
84         case OPT_FULLSCREEN:
85                 opt.fullscreen = is_enabled(oc);
86                 break;
87
88         case OPT_WINDOWED:
89                 opt.fullscreen = !is_enabled(oc);
90                 break;
91
92         case OPT_HELP:
93                 printf("Usage: vrfileman [options]\nOptions:\n");
94                 optcfg_print_options(oc);
95                 exit(0);
96         }
97         return true;
98 }