summaryrefslogtreecommitdiff
path: root/backend/pixma/scripts/pixma_gen_options.py
blob: c4c75e059b5064c428d831f62a307c4883e16913 (plain)
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
#!/usr/bin/env python

import sys,os,re

class Error(Exception):
    pass


class ParseError(Error):
    def __init__(self, errline):
        Error.__init__(self, errline)


class Struct:
    pass


def createCNameMap():
    t = ''
    for i in range(256):
        if ((ord('A') <= i) and (i <= ord('Z'))) or \
               ((ord('a') <= i) and (i <= ord('z'))) or \
               ((ord('0') <= i) and (i <= ord('9'))):
            t += chr(i)
        else:
            t += '_'
    return t


def seekBegin(f):
    while True:
        line = f.readline()
        if not line:
            return False
        if line.startswith('BEGIN SANE_Option_Descriptor'):
            return True


def parseVerbatim(o, line):
    words = line.split(None, 1)
    if (len(words) < 2) or (words[1][0] != '@'):
        return False
    o[words[0]] = words[1]
    return True


def parseLine_type(o, line):
    words = line.split(None, 2)
    otype = words[1]
    o['type'] = 'SANE_TYPE_' + otype.upper()
    if otype == 'group':
        g.ngroups += 1
        oname = '_group_%d' % g.ngroups
        o['size'] = 0
    else:
        temp = words[2]
        idx = temp.find('[')
        if idx == -1:
            oname = temp
            o['size'] = 1
        else:
            oname = temp[0:idx]
            o['size'] = int(temp[idx+1:-1])
    o['name'] = oname


def parseLine_title(o, line):
    o['title'] = line.split(None, 1)[1]


def parseLine_desc(o, line):
    o['desc'] = line.split(None, 1)[1]


def parseLine_unit(o, line):
    o['unit'] = 'SANE_UNIT_' + line.split(None, 1)[1].upper()


def parseLine_default(o, line):
    o['default'] = line.split(None, 1)[1]


def parseLine_cap(o, line):
    words = line.split()
    o['cap'] = ['SANE_CAP_' + s.upper() for s in words[1:]]


def parseLine_constraint(o, line):
    c = line.split(None,1)[1]
    if c[0] == '{':
        o['constraint'] = c[1:-1].split('|')
    elif c[0] == '(':
        o['constraint'] = tuple(c[1:-1].split(','))
    else:
        sys.stderr.write('Ignored: %s\n' % line)


def parseLine_info(o, line):
    words = line.split()
    o['info'] = ['SANE_INFO_' + s.upper() for s in words[1:]]

def parseLine_rem(o, line):
    pass

def normalize(o):
    if 'cname' not in o:
        cname = o['name'].translate(cnameMap)
        o['cname'] = cname
    else:
        cname = o['cname']
    o['cname_opt'] = 'opt_' + cname
    o['cname_con'] = 'constraint_' + cname
    if 'title' not in o:
        o['title'] = 'NO TITLE'
    if 'desc' not in o:
        o['desc'] = '@sod->title' % o
    if 'unit' not in o:
        o['unit'] = 'SANE_UNIT_NONE'
    if 'constraint_type' not in o:
        if 'constraint' not in o:
            ct = 'SANE_CONSTRAINT_NONE'
        elif isinstance(o['constraint'], list):
            if o['type'] == 'SANE_TYPE_STRING':
                ct = 'SANE_CONSTRAINT_STRING_LIST'
            else:
                ct = 'SANE_CONSTRAINT_WORD_LIST'
        elif isinstance(o['constraint'], tuple):
            ct = 'SANE_CONSTRAINT_RANGE'
        elif isinstance(o['constraint'], str):
            oc = o['constraint']
            if oc.startswith('@range'):
                ct = 'SANE_CONSTRAINT_RANGE'
            elif oc.startswith('@word_list'):
                ct = 'SANE_CONSTRAINT_WORD_LIST'
            elif oc.startswith('@string_list'):
                ct = 'SANE_CONSTRAINT_STRING_LIST'
        o['constraint_type'] = ct
    return o


def parseFile(f):
    if not seekBegin(f):
        return None
    options = [ {
        'name' : '',
        'cname' : 'opt_num_opts',
        'title' : '@SANE_TITLE_NUM_OPTIONS',
        'desc' : '@SANE_DESC_NUM_OPTIONS',
        'type' : 'SANE_TYPE_INT',
        'unit' : 'SANE_UNIT_NONE',
        'size' : 1,
        'cap' : ['SANE_CAP_SOFT_DETECT'],
        'constraint_type' : 'SANE_CONSTRAINT_NONE',
        'default' : '@w = ' + opt_prefix + 'last'
        } ]
    o = {}
    while True:
        line = f.readline()
        if not line:
            break
        line = line.strip()
        if not line:
            continue
        token = line.split(None, 1)[0].lower()
        if token == 'end':
            break
        if token == 'type':
            if 'name' in o:
                options.append(o)
            o = {}
        funcName = 'parseLine_' + token
        if funcName in globals():
            if not parseVerbatim(o, line):
                func = globals()[funcName]
                func(o, line)
        else:
            sys.stderr.write('Skip: %s\n' % line)
    if 'name' in o:
        options.append(o)
    return [normalize(o) for o in options]


def genHeader(options):
    print """
typedef union {
  SANE_Word w;
  SANE_Int  i;
  SANE_Bool b;
  SANE_Fixed f;
  SANE_String s;
  void *ptr;
} option_value_t;
"""
    print 'typedef enum {'
    for o in options:
        print '  %(cname_opt)s,' % o
    print '  ' + opt_prefix + 'last'
    print '} option_t;'
    print """

typedef struct {
  SANE_Option_Descriptor sod;
  option_value_t val,def;
  SANE_Word info;
} option_descriptor_t;


struct pixma_sane_t;
static int build_option_descriptors(struct pixma_sane_t *ss);
"""


def genMinMaxRange(n, t, r):
    if t == 'SANE_TYPE_FIXED':
        r = ['SANE_FIX(%s)' % x for x in r]
    print 'static const SANE_Range ' + n + ' = '
    print '  { ' + r[0] + ',' + r[1] + ',' + r[2] + ' };'


def genList(n, t, l):
    if t == 'SANE_TYPE_INT':
        etype = 'SANE_Word'
        l = [str(len(l))] + l
    elif t == 'SANE_TYPE_FIXED':
        etype = 'SANE_Word'
        l = [str(len(l))] + ['SANE_FIX(%s)' % x for x in l]
    elif t == 'SANE_TYPE_STRING':
        etype = 'SANE_String_Const'
        l = ['SANE_I18N("%s")' % x for x in l] + ['NULL']
    print 'static const %s %s[%d] = {' % (etype, n, len(l))
    for x in l[0:-1]:
        print '\t' + x + ','
    print '\t' + l[-1] + ' };'


def genConstraints(options):
    for o in options:
        if 'constraint' not in o: continue
        c = o['constraint']
        oname = o['cname_con']
        otype = o['type']
        if isinstance(c, tuple):
            genMinMaxRange(oname, otype, c)
        elif isinstance(c, list):
            genList(oname, otype, c)
    print

def buildCodeVerbatim(o):
    for f in ('name', 'title', 'desc', 'type', 'unit', 'size', 'cap',
              'constraint_type', 'constraint', 'default'):
        if (f not in o): continue
        temp = o[f]
        if (not isinstance(temp,str)) or \
           (len(temp) < 1) or (temp[0] != '@'):
            continue
        o['code_' + f] = temp[1:]

def ccode(o):
    buildCodeVerbatim(o)
    if 'code_name' not in o:
        o['code_name'] = '"' + o['name'] + '"'
    for f in ('title', 'desc'):
        cf = 'code_' + f
        if cf in o: continue
        o[cf] = 'SANE_I18N("' + o[f] + '")'

    for f in ('type', 'unit', 'constraint_type'):
        cf = 'code_' + f
        if cf in o: continue
        o[cf] = o[f]

    if 'code_size' not in o:
        otype = o['type']
        osize = o['size']
        if otype == 'SANE_TYPE_STRING':
            code = str(osize + 1)
        elif otype == 'SANE_TYPE_INT' or otype == 'SANE_TYPE_FIXED':
            code = str(osize) + ' * sizeof(SANE_Word)'
        elif otype == 'SANE_TYPE_BUTTON':
            code = '0'
        else:
            code = 'sizeof(SANE_Word)'
        o['code_size'] = code

    if ('code_cap' not in o) and ('cap' in o):
        o['code_cap'] = reduce(lambda a,b: a+'|'+b, o['cap'])
    else:
        o['code_cap'] = '0'

    if ('code_info' not in o) and ('info' in o):
        o['code_info'] = reduce(lambda a,b: a+'|'+b, o['info'])
    else:
        o['code_info'] = '0'

    if ('code_default' not in o) and ('default' in o):
        odefault = o['default']
        otype = o['type']
        if odefault == '_MIN':
            rhs = 'w = sod->constraint.range->min'
        elif odefault == '_MAX':
            rhs = 'w = sod->constraint.range->max'
        elif otype in ('SANE_TYPE_INT', 'SANE_TYPE_BOOL'):
            rhs = 'w = %(default)s'
        elif otype == 'SANE_TYPE_FIXED':
            rhs = 'w = SANE_FIX(%(default)s)'
        elif otype == 'SANE_TYPE_STRING':
            rhs = 's = SANE_I18N("%(default)s")'
        o['code_default'] = rhs % o
    if 'code_default' in o:
        code = '  opt->def.%(code_default)s;\n'
        if o['constraint_type'] != 'SANE_CONSTRAINT_STRING_LIST':
            code += '  opt->val.%(code_default)s;\n'
        else:
            code += '  opt->val.w = find_string_in_list' \
                    '(opt->def.s, sod->constraint.string_list);\n'
        o['full_code_default'] = code % o
    else:
        o['full_code_default'] = ''

    if ('code_constraint' not in o) and ('constraint' in o):
        ct = o['constraint_type']
        idx = len('SANE_CONSTRAINT_')
        ctype = ct[idx:].lower()
        if ctype == 'range':
            rhs = '&%(cname_con)s' % o
        else:
            rhs = '%(cname_con)s' % o
        o['code_constraint'] = ctype + ' = ' + rhs
    if 'code_constraint' in o:
        code = '  sod->constraint.%(code_constraint)s;\n'
        o['full_code_constraint'] = code % o
    else:
        o['full_code_constraint'] = ''

    return o

def genBuildOptions(options):
  print """
static
int find_string_in_list(SANE_String_Const str, const SANE_String_Const *list)
{
  int i;
  for (i = 0; list[i] && strcmp(str, list[i]) != 0; i++) {}
  return i;
}

static
int build_option_descriptors(struct pixma_sane_t *ss)
{
  SANE_Option_Descriptor *sod;
  option_descriptor_t *opt;

  memset(OPT_IN_CTX, 0, sizeof(OPT_IN_CTX));"""

  for o in options:
      o = ccode(o)
      otype = o['type']
      code = '\n  opt = &(OPT_IN_CTX[%(cname_opt)s]);\n' \
             '  sod = &opt->sod;\n' \
             '  sod->type = %(code_type)s;\n' \
             '  sod->title = %(code_title)s;\n' \
             '  sod->desc = %(code_desc)s;\n'
      if otype != 'SANE_TYPE_GROUP':
          code += '  sod->name = %(code_name)s;\n' \
                  '  sod->unit = %(code_unit)s;\n' \
                  '  sod->size = %(code_size)s;\n' \
                  '  sod->cap  = %(code_cap)s;\n' \
                  '  sod->constraint_type = %(code_constraint_type)s;\n' \
                  '%(full_code_constraint)s' \
                  '  OPT_IN_CTX[%(cname_opt)s].info = %(code_info)s;\n' \
                  '%(full_code_default)s'
      sys.stdout.write(code % o)
  print
  print '  return 0;\n'
  print '}'
  print

g = Struct()
g.ngroups = 0
opt_prefix = 'opt_'
con_prefix = 'constraint_'
cnameMap = createCNameMap()
options = parseFile(sys.stdin)
print "/* Automatically generated from pixma_sane.c */"
if (len(sys.argv) == 2) and (sys.argv[1] == 'h'):
    genHeader(options)
else:
    genConstraints(options)
    genBuildOptions(options)