gdgenerate.py 39.1 KB
Newer Older
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# SPDX-FileCopyrightText: 2021 GNOME Foundation
# SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later

import argparse
import jinja2
import markdown
import os
import re
import shutil
import sys

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from typogrify.filters import typogrify

17
from . import config, gir, log
Emmanuele Bassi's avatar
Emmanuele Bassi committed
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


HELP_MSG = "Generates the reference"

CODEBLOCK_START_RE = re.compile(
    r'''
    ^
    \s*
    \|\[
    \s*
    (?P<language>\<\!-- \s* language="\w+" \s* --\>)?
    \s*
    $
    ''',
    re.UNICODE | re.VERBOSE)

LANGUAGE_RE = re.compile(
    r'''
    ^
    \s*
    <!--
    \s*
    language="(?P<language>\w+)"
    \s*
    -->
    \s*
    $
    ''',
    re.UNICODE | re.VERBOSE)

CODEBLOCK_END_RE = re.compile(
    r'''
    ^
    \s*
    \]\|
    \s*
    $
    ''',
    re.UNICODE | re.VERBOSE)

LANGUAGE_MAP = {
    'c': 'c',
    'css': 'css',
    'plain': 'plain',
    'xml': 'xml',
}

TRANSFER_MODES = {
    'none': 'Ownership is not transferred',
67
    'container': 'Ownership of the container type is transferred, but not of the data',
Emmanuele Bassi's avatar
Emmanuele Bassi committed
68
    'full': 'Ownership of the data is transferred',
69
    'floating': 'Data has a floating reference',
Emmanuele Bassi's avatar
Emmanuele Bassi committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
}

DIRECTION_MODES = {
    'in': 'in',
    'inout': 'in-out',
    'out': 'out',
}

SCOPE_MODES = {
    'none': '-',
    'call': 'Arguments are valid during the call',
    'notified': 'Arguments are valid until the notify function is called',
    'async': 'Arguments are valid until the call is completed',
}

MD_EXTENSIONS = [
    'def_list',
    'fenced_code',
    'tables',
]

91

Emmanuele Bassi's avatar
Emmanuele Bassi committed
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
def process_language(lang):
    if lang is None:
        return "plain"

    res = LANGUAGE_RE.match(lang)
    if res:
        language = res.group("language") or "plain"
    else:
        language = "plain"

    return LANGUAGE_MAP[language.lower()]


def preprocess_gtkdoc(text):
    processed_text = []

    code_block_text = []
    code_block_language = None
    inside_code_block = False
    for line in text.split("\n"):
        res = CODEBLOCK_START_RE.match(line)
        if res:
            code_block_language = process_language(res.group("language"))
            inside_code_block = True
            continue

        res = CODEBLOCK_END_RE.match(line)
        if res and inside_code_block:
            if code_block_language == "plain":
                processed_text += ["```"]
                processed_text.extend(code_block_text)
                processed_text += ["```"]
            else:
                lexer = get_lexer_by_name(code_block_language)
                formatter = HtmlFormatter()
                code_block = highlight("\n".join(code_block_text), lexer, formatter)
                processed_text += [""]
                processed_text.extend(code_block.split("\n"))
                processed_text += [""]

            code_block_language = None
            code_block_text = []
            inside_code_block = False
            continue

        if inside_code_block:
            code_block_text += [line]
        else:
            processed_line = line
            processed_line = re.sub(r'#([A-Z][A-Za-z0-9:]+)', r'<code>\1</code>', processed_line)
            processed_line = re.sub(r'@(\w+)', r'<code>\1</code>', processed_line)
            processed_line = re.sub(r'%([A-Za-z0-9_]+)', r'<code>\1</code>', processed_line)
144
            processed_line = re.sub(r'#+\s+([\w\-_\s]+)(#+\s+[\w\{\}#-_]+)?', r'##### \1', processed_line)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
145
146
            processed_text += [processed_line]

147
148
    text = markdown.markdown("\n".join(processed_text), extensions=MD_EXTENSIONS)
    return typogrify(text)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
149
150


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
class TemplateConstant:
    def __init__(self, namespace, const):
        self.name = const.name
        self.value = const.value
        self.identifier = const.ctype
        self.type_cname = const.target.ctype
        self.description = "No description available."
        if const.doc is not None:
            self.description = preprocess_gtkdoc(const.doc.content)

    @property
    def c_decls(self):
        return f"#define {self.identifier} {self.value}"


Emmanuele Bassi's avatar
Emmanuele Bassi committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class TemplateProperty:
    def __init__(self, namespace, cls, prop):
        self.name = prop.name
        self.type_name = prop.target.name
        self.type_cname = prop.target.ctype
        self.description = "No description available."
        self.readable = prop.readable
        self.writable = prop.writable
        self.construct = prop.construct
        self.construct_only = prop.construct_only
        if prop.doc is not None:
            self.description = preprocess_gtkdoc(prop.doc.content)


class TemplateArgument:
    def __init__(self, call, argument):
        self.name = argument.name
        self.type_name = argument.target.name
        self.type_cname = argument.target.ctype
185
186
        self.transfer = TRANSFER_MODES[argument.transfer]
        self.direction = DIRECTION_MODES[argument.direction]
Emmanuele Bassi's avatar
Emmanuele Bassi committed
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
        self.nullable = argument.nullable
        self.scope = SCOPE_MODES[argument.scope or 'none']
        if argument.closure != -1:
            self.closure = call.parameters[argument.closure]
        else:
            self.closure = None
        self.description = "No description available."
        if argument.doc is not None:
            self.description = preprocess_gtkdoc(argument.doc.content)

    @property
    def is_pointer(self):
        return '*' in self.type_cname


class TemplateReturnValue:
    def __init__(self, call, retval):
        self.name = retval.name
        self.type_name = retval.target.name
        self.type_cname = retval.target.ctype
        self.transfer = TRANSFER_MODES[retval.transfer or 'none']
        self.nullable = retval.nullable
        self.description = "No description available."
        if retval.doc is not None:
            self.description = preprocess_gtkdoc(retval.doc.content)

    @property
    def is_pointer(self):
        return '*' in self.type_cname


class TemplateSignal:
    def __init__(self, namespace, cls, signal):
        self.name = signal.name
221
        self.class_type_cname = cls.type_cname
Emmanuele Bassi's avatar
Emmanuele Bassi committed
222
        self.description = "No description available."
223
        self.identifier = signal.name.replace("-", "_")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
224
225
226
227
228
229
230
231
232

        if signal.doc is not None:
            self.description = preprocess_gtkdoc(signal.doc.content)

        self.arguments = []
        for arg in signal.parameters:
            self.arguments.append(TemplateArgument(signal, arg))

        self.return_value = None
233
        if not isinstance(signal.return_value.target, gir.VoidType):
Emmanuele Bassi's avatar
Emmanuele Bassi committed
234
235
            self.return_value = TemplateReturnValue(signal, signal.return_value)

236
237
238
239
    @property
    def c_decl(self):
        res = []
        if self.return_value is None:
240
            res += ["void"]
241
        else:
242
243
244
            res += [f"{self.return_value.type_cname}"]
        res += [f"{self.identifier} ("]
        res += [f"  {self.class_type_cname} self,"]
245
        for arg in self.arguments:
246
247
248
            res += [f"  {arg.type_cname} {arg.name},"]
        res += ["  gpointer user_data"]
        res += [")"]
249
250
        return "\n".join(res)

Emmanuele Bassi's avatar
Emmanuele Bassi committed
251
252
253
254
255
256
257

class TemplateMethod:
    def __init__(self, namespace, cls, method):
        self.name = method.name
        self.identifier = method.identifier
        self.description = "No description available."

258
259
260
261
262
263
264
265
266
267
        if method.doc is not None:
            self.description = preprocess_gtkdoc(method.doc.content)

        self.instance_parameter = TemplateArgument(method, method.instance_param)

        self.arguments = []
        for arg in method.parameters:
            self.arguments.append(TemplateArgument(method, arg))

        self.return_value = None
268
        if not isinstance(method.return_value.target, gir.VoidType):
269
270
271
272
273
274
            self.return_value = TemplateReturnValue(method, method.return_value)

    @property
    def c_decl(self):
        res = []
        if self.return_value is None:
275
            res += ["void"]
276
        else:
277
278
            res += [f"{self.return_value.type_cname}"]
        res += [f"{self.identifier} ("]
279
280
        n_args = len(self.arguments)
        if n_args == 0:
281
            res += [f"  {self.instance_parameter.type_cname} self"]
282
        else:
283
            res += [f"  {self.instance_parameter.type_cname} self,"]
284
285
            for (idx, arg) in enumerate(self.arguments):
                if idx < n_args - 1:
286
                    res += [f"  {arg.type_cname} {arg.name},"]
287
                else:
288
289
                    res += [f"  {arg.type_cname} {arg.name}"]
        res += [")"]
290
291
292
293
294
295
296
297
298
299
        return "\n".join(res)


class TemplateClassMethod:
    def __init__(self, namespace, cls, method):
        self.name = method.name
        self.identifier = method.identifier
        self.class_type_cname = cls.class_struct.type_struct
        self.description = "No description available."

Emmanuele Bassi's avatar
Emmanuele Bassi committed
300
301
302
303
304
305
306
307
        if method.doc is not None:
            self.description = preprocess_gtkdoc(method.doc.content)

        self.arguments = []
        for arg in method.parameters:
            self.arguments.append(TemplateArgument(method, arg))

        self.return_value = None
308
        if not isinstance(method.return_value.target, gir.VoidType):
Emmanuele Bassi's avatar
Emmanuele Bassi committed
309
310
            self.return_value = TemplateReturnValue(method, method.return_value)

311
312
313
314
    @property
    def c_decl(self):
        res = []
        if self.return_value is None:
315
            res += ["void"]
316
        else:
317
318
            res += [f"{self.return_value.type_cname}"]
        res += [f"{self.identifier} ("]
319
320
        n_args = len(self.arguments)
        if n_args == 1:
321
            res += [f"  {self.class_type_cname}* self"]
322
        else:
323
            res += [f"  {self.class_type_cname}* self,"]
324
325
            for (idx, arg) in enumerate(self.arguments, start=1):
                if idx < n_args - 1:
326
                    res += [f"  {arg.type_cname} {arg.name},"]
327
                else:
328
329
                    res += [f"  {arg.type_cname} {arg.name}"]
        res += [")"]
330
331
        return "\n".join(res)

Emmanuele Bassi's avatar
Emmanuele Bassi committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345

class TemplateFunction:
    def __init__(self, func):
        self.name = func.name
        self.identifier = func.identifier
        self.description = "No description available."
        if func.doc is not None:
            self.description = preprocess_gtkdoc(func.doc.content)

        self.arguments = []
        for arg in func.parameters:
            self.arguments.append(TemplateArgument(func, arg))

        self.return_value = None
346
        if not isinstance(func.return_value.target, gir.VoidType):
Emmanuele Bassi's avatar
Emmanuele Bassi committed
347
348
            self.return_value = TemplateReturnValue(func, func.return_value)

349
350
351
352
    @property
    def c_decl(self):
        res = []
        if self.return_value is None:
353
            res += ["void"]
354
        else:
355
356
            res += [f"{self.return_value.type_cname}"]
        res += [f"{self.identifier} ("]
357
358
        n_args = len(self.arguments)
        if n_args == 0:
359
            res += ["void"]
360
361
362
        else:
            for (idx, arg) in enumerate(self.arguments):
                if idx < n_args - 1:
363
                    res += [f"  {arg.type_cname} {arg.name},"]
364
                else:
365
366
                    res += [f"  {arg.type_cname} {arg.name}"]
        res += [")"]
367
368
        return "\n".join(res)

Emmanuele Bassi's avatar
Emmanuele Bassi committed
369
370
371
372
373

class TemplateCallback:
    def __init__(self, cb):
        self.name = cb.name
        self.description = "No description available."
374
        self.identifier = cb.name.replace("-", "_")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
375
376
377
378
379
380
381
382
        if cb.doc is not None:
            self.description = preprocess_gtkdoc(cb.doc.content)

        self.arguments = []
        for arg in cb.parameters:
            self.arguments.append(TemplateArgument(cb, arg))

        self.return_value = None
383
        if not isinstance(cb.return_value.target, gir.VoidType):
Emmanuele Bassi's avatar
Emmanuele Bassi committed
384
385
            self.return_value = TemplateReturnValue(cb, cb.return_value)

386
387
388
389
    @property
    def c_decl(self):
        res = []
        if self.return_value is None:
390
            res += ["void"]
391
        else:
392
393
            res += [f"{self.return_value.type_cname}"]
        res += [f"{self.identifier} ("]
394
395
        n_args = len(self.arguments)
        if n_args == 0:
396
            res += ["void"]
397
398
399
        else:
            for (idx, arg) in enumerate(self.arguments):
                if idx < n_args - 1:
400
                    res += [f"  {arg.type_cname} {arg.name},"]
401
                else:
402
403
                    res += [f"  {arg.type_cname} {arg.name}"]
        res += [")"]
404
405
        return "\n".join(res)

Emmanuele Bassi's avatar
Emmanuele Bassi committed
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

class TemplateField:
    def __init__(self, field):
        self.name = field.name
        self.type_name = field.target and field.target.name or 'none'
        self.type_cname = field.target and field.target.ctype or 'none'
        self.private = field.private
        self.description = "No description available."
        if field.doc is not None:
            self.description = preprocess_gtkdoc(field.doc.content)


class TemplateInterface:
    def __init__(self, namespace, iface_name):
        interface = namespace.find_interface(iface_name)
        if interface is None:
            self.name = iface_name
            self.requires = "GObject.Object"
            self.link_prefix = "iface"
            return

        self.name = interface.name
        self.requires = interface.prerequisite
        if self.requires is None:
            self.requires = "GObject.Object"

        self.symbol_prefix = f"{namespace.symbol_prefix}_{interface.symbol_prefix}"
        self.type_cname = interface.ctype

        self.link_prefix = "iface"

        self.description = "No description available."
        if interface.doc is not None:
            self.description = preprocess_gtkdoc(interface.doc.content)

        self.class_name = interface.type_struct

        self.class_struct = namespace.find_record(interface.type_struct)
        if self.class_struct is not None:
            self.class_fields = []
            self.class_methods = []

            for field in self.class_struct.fields:
                if not field.private:
                    self.class_fields.append(TemplateField(field))

            for meth in self.class_struct.methods:
453
                self.class_methods.append(TemplateClassMethod(namespace, self, meth))
Emmanuele Bassi's avatar
Emmanuele Bassi committed
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

        if len(interface.properties) != 0:
            self.properties = []
            for prop in interface.properties:
                self.properties.append(TemplateProperty(namespace, self, prop))

        if len(interface.signals) != 0:
            self.signals = []
            for sig in interface.signals:
                self.signals.append(TemplateSignal(namespace, self, sig))

        if len(interface.methods) != 0:
            self.methods = []
            for meth in interface.methods:
                self.methods.append(TemplateMethod(namespace, self, meth))

        if len(interface.virtual_methods) != 0:
            self.virtual_methods = []
            for vfunc in self.virtual_methods:
                self.virtual_methods.append(TemplateMethod(namespace, self, vfunc))


class TemplateClass:
    def __init__(self, namespace, cls):
        self.name = cls.name
        self.symbol_prefix = f"{namespace.symbol_prefix}_{cls.symbol_prefix}"
        self.type_cname = cls.ctype
        self.link_prefix = "class"

        self.description = "No description available."
        if cls.parent is None:
            self.parent = 'GObject.TypeInstance'
        elif '.' in cls.parent:
            self.parent = cls.parent
        else:
            self.parent = f"{namespace.name}.{cls.parent}"

        if cls.doc is not None:
            self.description = preprocess_gtkdoc(cls.doc.content)

        if len(cls.properties) != 0:
            self.properties = []
            for prop in cls.properties:
                self.properties.append(TemplateProperty(namespace, self, prop))

        if len(cls.signals) != 0:
            self.signals = []
            for sig in cls.signals:
                self.signals.append(TemplateSignal(namespace, self, sig))

504
505
506
507
508
        if len(cls.constructors) != 0:
            self.ctors = []
            for ctor in cls.constructors:
                self.ctors.append(TemplateFunction(ctor))

Emmanuele Bassi's avatar
Emmanuele Bassi committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        if len(cls.methods) != 0:
            self.methods = []
            for meth in cls.methods:
                self.methods.append(TemplateMethod(namespace, self, meth))

        self.class_name = cls.type_struct

        self.instance_struct = None
        if len(cls.fields) != 0:
            self.instance_struct = self.class_name

        self.class_struct = namespace.find_record(cls.type_struct)
        if self.class_struct is None:
            return

        if self.class_struct:
            self.class_fields = []
            self.class_methods = []

            for field in self.class_struct.fields:
                if not field.private:
                    self.class_fields.append(TemplateField(field))

            for meth in self.class_struct.methods:
533
                self.class_methods.append(TemplateClassMethod(namespace, self, meth))
Emmanuele Bassi's avatar
Emmanuele Bassi committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

        if len(cls.implements) != 0:
            self.interfaces = []
            for iface in cls.implements:
                self.interfaces.append(TemplateInterface(namespace, iface))

        if len(cls.virtual_methods) != 0:
            self.virtual_methods = []
            for vfunc in cls.virtual_methods:
                self.virtual_methods.append(TemplateMethod(namespace, self, vfunc))

        if len(cls.functions) != 0:
            self.type_funcs = []
            for func in cls.functions:
                self.type_funcs.append(TemplateFunction(func))


class TemplateMember:
    def __init__(self, enum, member):
        self.name = member.identifier
        self.nick = member.nick
        self.value = member.value
        self.description = "No description available."
        if member.doc is not None:
558
            self.description = preprocess_gtkdoc(member.doc.content)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
559
560
561
562
563
564
565
566
567
568
569


class TemplateEnum:
    def __init__(self, namespace, enum):
        self.name = enum.name
        self.symbol_prefix = None
        self.type_cname = enum.ctype
        self.bitfield = False
        self.error = False
        self.domain = None

570
        if isinstance(enum, gir.BitField):
Emmanuele Bassi's avatar
Emmanuele Bassi committed
571
572
            self.link_prefix = "flags"
            self.bitfield = True
573
        elif isinstance(enum, gir.ErrorDomain):
Emmanuele Bassi's avatar
Emmanuele Bassi committed
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
            self.link_prefix = "error"
            self.error = True
            self.domain = enum.domain
        else:
            self.link_prefix = "enum"

        if len(enum.members) != 0:
            self.members = []
            for member in enum.members:
                self.members.append(TemplateMember(enum, member))

        if len(enum.functions) != 0:
            self.type_funcs = []
            for func in enum.functions:
                self.type_funcs.append(TemplateFunction(func))


class TemplateNamespace:
    def __init__(self, namespace):
        self.name = namespace.name
        self.version = namespace.version
        self.prefix = f"{namespace.symbol_prefix}"


def _gen_classes(config, theme_config, output_dir, jinja_env, namespace, all_classes):
    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")

    class_tmpl = jinja_env.get_template(theme_config.class_template)
    method_tmpl = jinja_env.get_template('method.html')
    property_tmpl = jinja_env.get_template('property.html')
    signal_tmpl = jinja_env.get_template('signal.html')
    class_method_tmpl = jinja_env.get_template('class_method.html')
    type_func_tmpl = jinja_env.get_template('type_func.html')
    vfunc_tmpl = jinja_env.get_template('vfunc.html')

    for cls in all_classes:
        class_file = os.path.join(ns_dir, f"class.{cls.name}.html")
        log.info(f"Creating class file for {namespace.name}.{cls.name}: {class_file}")

        tmpl = TemplateClass(namespace, cls)

        with open(class_file, "w") as out:
            content = class_tmpl.render({
                'CONFIG': config,
                'namespace': namespace,
                'class': tmpl,
            })

622
            out.write(content)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
623

624
625
626
627
628
629
630
631
632
633
634
635
        for ctor in getattr(tmpl, 'ctors', []):
            ctor_file = os.path.join(ns_dir, f"ctor.{cls.name}.{ctor.name}.html")
            log.debug(f"Creating ctor file for {namespace.name}.{cls.name}.{ctor.name}: {ctor_file}")

            with open(ctor_file, "w") as out:
                out.write(type_func_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'type_func': ctor,
                }))

Emmanuele Bassi's avatar
Emmanuele Bassi committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
        for method in getattr(tmpl, 'methods', []):
            method_file = os.path.join(ns_dir, f"method.{cls.name}.{method.name}.html")
            log.debug(f"Creating method file for {namespace.name}.{cls.name}.{method.name}: {method_file}")

            with open(method_file, "w") as out:
                out.write(method_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'method': method,
                }))

        for prop in getattr(tmpl, 'properties', []):
            prop_file = os.path.join(ns_dir, f"property.{cls.name}.{prop.name}.html")
            log.debug(f"Creating property file for {namespace.name}.{cls.name}.{prop.name}: {prop_file}")

            with open(prop_file, "w") as out:
                out.write(property_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'property': prop,
                }))

        for signal in getattr(tmpl, 'signals', []):
            signal_file = os.path.join(ns_dir, f"signal.{cls.name}.{signal.name}.html")
            log.debug(f"Creating signal file for {namespace.name}.{cls.name}.{signal.name}: {signal_file}")

            with open(signal_file, "w") as out:
                out.write(signal_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'signal': signal,
                }))

        for cls_method in getattr(tmpl, 'class_methods', []):
            cls_method_file = os.path.join(ns_dir, f"class_method.{cls.name}.{cls_method.name}.html")
            log.debug(f"Creating class method file for {namespace.name}.{cls.name}.{cls_method.name}: {cls_method_file}")

            with open(cls_method_file, "w") as out:
                out.write(class_method_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'class_method': cls_method,
                }))

        for vfunc in getattr(tmpl, 'virtual_methods', []):
            vfunc_file = os.path.join(ns_dir, f"vfunc.{cls.name}.{vfunc.name}.html")
            log.debug(f"Creating vfunc file for {namespace.name}.{cls.name}.{vfunc.name}: {vfunc_file}")

            with open(vfunc_file, "w") as out:
                out.write(vfunc_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'vfunc': vfunc,
                }))

        for type_func in getattr(tmpl, 'type_funcs', []):
            type_func_file = os.path.join(ns_dir, f"type_func.{cls.name}.{type_func.name}.html")
            log.debug(f"Creating type func file for {namespace.name}.{cls.name}.{type_func.name}: {type_func_file}")

            with open(type_func_file, "w") as out:
                out.write(type_func_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'type_func': type_func,
                }))


def _gen_interfaces(config, theme_config, output_dir, jinja_env, namespace, all_interfaces):
    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")

    iface_tmpl = jinja_env.get_template(theme_config.interface_template)
    method_tmpl = jinja_env.get_template('method.html')
    property_tmpl = jinja_env.get_template('property.html')
    signal_tmpl = jinja_env.get_template('signal.html')
    class_method_tmpl = jinja_env.get_template('class_method.html')
    type_func_tmpl = jinja_env.get_template('type_func.html')
    vfunc_tmpl = jinja_env.get_template('vfunc.html')

    for iface in all_interfaces:
        iface_file = os.path.join(ns_dir, f"iface.{iface.name}.html")
        log.info(f"Creating interface file for {namespace.name}.{iface.name}: {iface_file}")

        tmpl = TemplateInterface(namespace, iface)

        with open(iface_file, "w") as out:
            out.write(iface_tmpl.render({
                'CONFIG': config,
                'namespace': namespace,
                'interface': tmpl,
            }))

        for method in getattr(tmpl, 'methods', []):
            method_file = os.path.join(ns_dir, f"method.{iface.name}.{method.name}.html")
            log.debug(f"Creating method file for {namespace.name}.{iface.name}.{method.name}: {method_file}")

            with open(method_file, "w") as out:
                out.write(method_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'method': method,
                }))

        for prop in getattr(tmpl, 'properties', []):
            prop_file = os.path.join(ns_dir, f"property.{iface.name}.{prop.name}.html")
            log.debug(f"Creating property file for {namespace.name}.{iface.name}.{prop.name}: {prop_file}")

            with open(prop_file, "w") as out:
                out.write(property_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'property': prop,
                }))

        for signal in getattr(tmpl, 'signals', []):
            signal_file = os.path.join(ns_dir, f"signal.{iface.name}.{signal.name}.html")
            log.debug(f"Creating signal file for {namespace.name}.{iface.name}.{signal.name}: {signal_file}")

            with open(signal_file, "w") as out:
                out.write(signal_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'signal': signal,
                }))

        for cls_method in getattr(tmpl, 'class_methods', []):
770
771
            class_method_file = os.path.join(ns_dir, f"class_method.{iface.name}.{cls_method.name}.html")
            log.debug(f"Creating class method file for {namespace.name}.{iface.name}.{cls_method.name}: {class_method_file}")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
772

773
            with open(class_method_file, "w") as out:
Emmanuele Bassi's avatar
Emmanuele Bassi committed
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
                out.write(class_method_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'class_method': cls_method,
                }))

        for vfunc in getattr(tmpl, 'virtual_methods', []):
            vfunc_file = os.path.join(ns_dir, f"vfunc.{iface.name}.{vfunc.name}.html")
            log.debug(f"Creating vfunc file for {namespace.name}.{iface.name}.{vfunc.name}: {vfunc_file}")

            with open(vfunc_file, "w") as out:
                out.write(vfunc_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'vfunc': vfunc,
                }))

        for type_func in getattr(tmpl, 'type_funcs', []):
            type_func_file = os.path.join(ns_dir, f"type_func.{iface.name}.{type_func.name}.html")
            log.debug(f"Creating type func file for {namespace.name}.{iface.name}.{type_func.name}: {type_func_file}")

            with open(type_func_file, "w") as out:
                out.write(type_func_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'type_func': type_func,
                }))


def _gen_enums(config, theme_config, output_dir, jinja_env, namespace, all_enums):
    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")

    enum_tmpl = jinja_env.get_template(theme_config.enum_template)
    type_func_tmpl = jinja_env.get_template('type_func.html')

    for enum in all_enums:
        enum_file = os.path.join(ns_dir, f"enum.{enum.name}.html")
        log.info(f"Creating enum file for {namespace.name}.{enum.name}: {enum_file}")

        tmpl = TemplateEnum(namespace, enum)

        with open(enum_file, "w") as out:
            out.write(enum_tmpl.render({
                'CONFIG': config,
                'namespace': namespace,
                'enum': tmpl,
            }))

        for type_func in getattr(tmpl, 'type_funcs', []):
            type_func_file = os.path.join(ns_dir, f"type_func.{enum.name}.{type_func.name}.html")
            log.debug(f"Creating type func file for {namespace.name}.{enum.name}.{type_func.name}: {type_func_file}")

            with open(type_func_file, "w") as out:
                out.write(type_func_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'type_func': type_func,
                }))


def _gen_bitfields(config, theme_config, output_dir, jinja_env, namespace, all_enums):
    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")

    enum_tmpl = jinja_env.get_template(theme_config.flags_template)
    type_func_tmpl = jinja_env.get_template('type_func.html')

    for enum in all_enums:
        enum_file = os.path.join(ns_dir, f"flags.{enum.name}.html")
        log.info(f"Creating enum file for {namespace.name}.{enum.name}: {enum_file}")

        tmpl = TemplateEnum(namespace, enum)

        with open(enum_file, "w") as out:
            out.write(enum_tmpl.render({
                'CONFIG': config,
                'namespace': namespace,
                'enum': tmpl,
            }))

        for type_func in getattr(tmpl, 'type_funcs', []):
            type_func_file = os.path.join(ns_dir, f"type_func.{enum.name}.{type_func.name}.html")
            log.debug(f"Creating type func file for {namespace.name}.{enum.name}.{type_func.name}: {type_func_file}")

            with open(type_func_file, "w") as out:
                out.write(type_func_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'type_func': type_func,
                }))


def _gen_domains(config, theme_config, output_dir, jinja_env, namespace, all_enums):
    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")

    enum_tmpl = jinja_env.get_template(theme_config.error_template)
    type_func_tmpl = jinja_env.get_template('type_func.html')

    for enum in all_enums:
        enum_file = os.path.join(ns_dir, f"error.{enum.name}.html")
        log.info(f"Creating enum file for {namespace.name}.{enum.name}: {enum_file}")

        tmpl = TemplateEnum(namespace, enum)

        with open(enum_file, "w") as out:
            out.write(enum_tmpl.render({
                'CONFIG': config,
                'namespace': namespace,
                'enum': tmpl,
            }))

        for type_func in getattr(tmpl, 'type_funcs', []):
            type_func_file = os.path.join(ns_dir, f"type_func.{enum.name}.{type_func.name}.html")
            log.debug(f"Creating type func file for {namespace.name}.{enum.name}.{type_func.name}: {type_func_file}")

            with open(type_func_file, "w") as out:
                out.write(type_func_tmpl.render({
                    'CONFIG': config,
                    'namespace': namespace,
                    'class': tmpl,
                    'type_func': type_func,
                }))


902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
def _gen_constants(config, theme_config, output_dir, jinja_env, namespace, all_constants):
    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")

    const_tmpl = jinja_env.get_template('constant.html')

    for const in all_constants:
        const_file = os.path.join(ns_dir, f"const.{const.name}.html")
        log.info(f"Creating constant file for {namespace.name}.{const.name}: {const_file}")

        tmpl = TemplateConstant(namespace, const)

        with open(const_file, "w") as out:
            out.write(const_tmpl.render({
                'CONFIG': config,
                'namespace': namespace,
917
                'constant': tmpl,
918
919
920
            }))


Emmanuele Bassi's avatar
Emmanuele Bassi committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def _gen_content_files(config, content_dir, output_dir):
    content_files = []

    for (file_name, content_title) in config.content_files:
        content_file = file_name.replace('.md', '.html')
        infile = os.path.join(content_dir, file_name)
        outfile = os.path.join(output_dir, content_file)
        log.debug(f"Adding extra content file: {infile} -> {outfile} ('{content_title}')")
        content_files += [(infile, outfile, content_file, content_title)]

    return content_files


def gen_reference(config, options, repository, templates_dir, theme_config, content_dir, output_dir):
    theme_dir = os.path.join(templates_dir, theme_config.name.lower())
    log.debug(f"Loading jinja templates from {theme_dir}")

    fs_loader = jinja2.FileSystemLoader(theme_dir)
    jinja_env = jinja2.Environment(loader=fs_loader, autoescape=jinja2.select_autoescape(['html']))

941
    namespace = repository.namespace
Emmanuele Bassi's avatar
Emmanuele Bassi committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957

    symbols = {
        "aliases": sorted(namespace.get_aliases(), key=lambda alias: alias.name.lower()),
        "bitfields": sorted(namespace.get_bitfields(), key=lambda bitfield: bitfield.name.lower()),
        "classes": sorted(namespace.get_classes(), key=lambda cls: cls.name.lower()),
        "constants": sorted(namespace.get_constants(), key=lambda const: const.name.lower()),
        "domains": sorted(namespace.get_error_domains(), key=lambda domain: domain.name.lower()),
        "enums": sorted(namespace.get_enumerations(), key=lambda enum: enum.name.lower()),
        "functions": sorted(namespace.get_functions(), key=lambda func: func.name.lower()),
        "interfaces": sorted(namespace.get_interfaces(), key=lambda interface: interface.name.lower()),
        "records": sorted(namespace.get_records(), key=lambda record: record.name.lower()),
        "unions": sorted(namespace.get_unions(), key=lambda union: union.name.lower()),
    }

    all_indices = {
        "bitfields": _gen_bitfields,
958
959
        "classes": _gen_classes,
        "constants": _gen_constants,
Emmanuele Bassi's avatar
Emmanuele Bassi committed
960
        "domains": _gen_domains,
961
962
        "enums": _gen_enums,
        "interfaces": _gen_interfaces,
Emmanuele Bassi's avatar
Emmanuele Bassi committed
963
964
965
966
967
968
969
970
971
972
973
974
975
976
    }

    ns_dir = os.path.join(output_dir, f"{namespace.name}", f"{namespace.version}")
    log.debug(f"Creating output path for the namespace: {ns_dir}")
    os.makedirs(ns_dir, exist_ok=True)

    content_files = _gen_content_files(config, content_dir, ns_dir)

    ns_tmpl = jinja_env.get_template(theme_config.namespace_template)
    ns_file = os.path.join(ns_dir, "index.html")
    log.info(f"Creating namespace index file for {namespace.name}.{namespace.version}: {ns_file}")
    with open(ns_file, "w") as out:
        out.write(ns_tmpl.render({
            "CONFIG": config,
977
            "repository": repository,
Emmanuele Bassi's avatar
Emmanuele Bassi committed
978
979
980
981
982
983
            "namespace": namespace,
            "symbols": symbols,
            "content_files": content_files,
        }))

    if options.sections == [] or options.sections == ["all"]:
984
        gen_indices = list(all_indices.keys())
Emmanuele Bassi's avatar
Emmanuele Bassi committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
    else:
        gen_indices = options.sections

    log.info(f"Generating references for: {gen_indices}")

    for section in gen_indices:
        generator = all_indices.get(section, None)
        if generator is None:
            log.debug(f"No generator for section {section}")
            continue

        s = symbols.get(section, [])
        if s is None:
            log.debug(f"No symbols for section {section}")
            continue

        generator(config, theme_config, output_dir, jinja_env, namespace, s)

    if len(content_files) != 0:
        content_tmpl = jinja_env.get_template(theme_config.content_template)
        for (src, dst, filename, title) in content_files:
            log.info(f"Generating content file {filename} for '{title}': {dst}")

            src_data = ""
            with open(src, "r") as infile:
                source = []
                for line in infile:
                    source += [line]
                src_data = "".join(source)

1015
            dst_data = preprocess_gtkdoc(src_data)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
            with open(dst, "w") as outfile:
                outfile.write(content_tmpl.render({
                    "CONFIG": config,
                    "namespace": namespace,
                    "symbols": symbols,
                    "content_files": content_files,
                    "content_title": title,
                    "content_data": dst_data,
                }))

    if theme_config.css is not None:
        log.info(f"Copying style from {theme_dir} to {ns_dir}")
        style_src = os.path.join(theme_dir, theme_config.css)
        style_dst = os.path.join(ns_dir, theme_config.css)
        shutil.copyfile(style_src, style_dst)

    for extra_file in theme_config.extra_files:
        log.debug(f"Copying extra file {extra_file} from {theme_dir} to {ns_dir}")
        src = os.path.join(theme_dir, extra_file)
        dst = os.path.join(ns_dir, extra_file)
        shutil.copyfile(src, dst)


def add_args(parser):
1040
1041
    parser.add_argument("--add-include-path", action="append", dest="include_paths", default=[],
                        help="include paths for other GIR files")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1042
1043
1044
1045
1046
1047
1048
    parser.add_argument("-C", "--config", metavar="FILE", help="the configuration file")
    parser.add_argument("--dry-run", action="store_true", help="parses the GIR file without generating files")
    parser.add_argument("--templates-dir", default=None, help="the base directory with the theme templates")
    parser.add_argument("--content-dir", default=None, help="the base directory with the extra content")
    parser.add_argument("--theme-name", default="basic", help="the theme to use")
    parser.add_argument("--output-dir", default=None, help="the output directory for the index files")
    parser.add_argument("--section", action="append", dest="sections", default=[], help="the sections to generate, or 'all'")
1049
1050
    parser.add_argument("infile", metavar="GIRFILE", type=argparse.FileType('r', encoding='UTF-8'),
                        default=sys.stdin, help="the GIR file to parse")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1051
1052
1053
1054
1055
1056
1057
1058
1059


def run(options):
    xdg_data_dirs = os.environ.get("XDG_DATA_DIRS", "/usr/share:/usr/local/share").split(":")
    xdg_data_home = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))

    paths = []
    paths.append(os.getcwd())
    paths.append(os.path.join(xdg_data_home, "gir-1.0"))
1060
    paths.extend([os.path.join(x, "gir-1.0") for x in xdg_data_dirs])
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1061
1062
1063
1064
1065
1066
1067
1068

    log.info(f"Loading config file: {options.config}")

    conf = config.GIDocConfig(options.config)

    output_dir = options.output_dir or os.getcwd()
    content_dir = options.content_dir or os.getcwd()

1069
1070
1071
1072
1073
1074
1075
    if options.templates_dir is not None:
        templates_dir = options.templates_dir
    else:
        templates_dir = conf.get_templates_dir()
        if templates_dir is None:
            templates_dir = os.path.join(os.path.dirname(__file__), 'templates')

Emmanuele Bassi's avatar
Emmanuele Bassi committed
1076
1077
1078
    theme_name = conf.get_theme_name(default=options.theme_name)
    theme_conf = config.GITemplateConfig(templates_dir, theme_name)

1079
1080
    log.debug(f"Search paths: {paths}")
    log.debug(f"Templates directory: {templates_dir}")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1081
    log.info(f"Theme name: {theme_conf.name}")
1082
    log.info(f"Output directory: {output_dir}")
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1083
1084

    log.info("Parsing GIR file")
1085
    parser = gir.GirParser(search_paths=paths)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1086
1087
1088
1089
1090
1091
    parser.parse(options.infile)

    if not options.dry_run:
        gen_reference(conf, options, parser.get_repository(), templates_dir, theme_conf, content_dir, output_dir)

    return 0