b25edc5a17246f24a0b5889c7e4690ba8ca91e03
[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 && optcfg_parse_config_file(oc, cfgfile) == -1) {
43                 optcfg_destroy(oc);
44                 return false;
45         }
46
47         if(argv && optcfg_parse_args(oc, argc, argv) == -1) {
48                 fprintf(stderr, "invalid option\n");
49                 optcfg_destroy(oc);
50                 return false;
51         }
52
53         optcfg_destroy(oc);
54         return true;
55 }
56
57 static bool is_enabled(optcfg *oc)
58 {
59         int res;
60         optcfg_enabled_value(oc, &res);
61         return res != 0;
62 }
63
64 static int opt_handler(optcfg *oc, int optid, void *cls)
65 {
66         switch(optid) {
67         case OPT_SIZE:
68                 {
69                         char *valstr = optcfg_next_value(oc);
70                         if(!valstr || sscanf(valstr, "%dx%d", &opt.width, &opt.height) != 2) {
71                                 fprintf(stderr, "size must be in the form: WIDTHxHEIGHT\n");
72                                 return -1;
73                         }
74                 }
75                 break;
76
77         case OPT_VR:
78                 opt.vr = is_enabled(oc);
79                 break;
80
81         case OPT_SRGB:
82                 opt.srgb = is_enabled(oc);
83                 break;
84
85         case OPT_FULLSCREEN:
86                 opt.fullscreen = is_enabled(oc);
87                 break;
88
89         case OPT_WINDOWED:
90                 opt.fullscreen = !is_enabled(oc);
91                 break;
92
93         case OPT_HELP:
94                 printf("Usage: vrfileman [options]\nOptions:\n");
95                 optcfg_print_options(oc);
96                 exit(0);
97         }
98         return true;
99 }