This file is indexed.

/usr/share/pyshared/kivy/uix/rst.py is in python-kivy 1.7.2-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 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
 453
 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
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 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
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 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
 770
 771
 772
 773
 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
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
'''
reStructuredText renderer
=========================

.. versionadded:: 1.1.0

`reStructuredText <http://docutils.sourceforge.net/rst.html>`_ is an
easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser
system.

.. warning::

    This widget is highly experimental. The whole styling and implementation are
    not stable until this warning has been removed.

Usage with Text
---------------

::

    text = """
    .. _top:

    Hello world
    ===========

    This is an **emphased text**, some ``interpreted text``.
    And this is a reference to top_::

        $ print "Hello world"

    """
    document = RstDocument(text=text)

The rendering will output:

.. image:: images/rstdocument.png

Usage with Source
-----------------

You can also render a rst file by using :data:`RstDocument.source`::

    document = RstDocument(source='index.rst')

You can reference other documents with the role ``:doc:``. For example, in the
document ``index.rst`` you can write::

    Go to my next document: :doc:`moreinfo.rst`

It will generate a link that, when clicked, the document ``moreinfo.rst``
will be loaded.

'''

__all__ = ('RstDocument', )

import os
from os.path import dirname, join, exists
from kivy.clock import Clock
from kivy.properties import ObjectProperty, NumericProperty, \
        DictProperty, ListProperty, StringProperty, \
        BooleanProperty
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.image import AsyncImage, Image
from kivy.uix.videoplayer import VideoPlayer
from kivy.uix.anchorlayout import AnchorLayout
from kivy.animation import Animation
from kivy.logger import Logger
from docutils.parsers import rst
from docutils.parsers.rst import roles
from docutils import nodes, frontend, utils
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.roles import set_classes


#
# Handle some additional roles
#
if 'KIVY_DOC' not in os.environ:

    class role_doc(nodes.Inline, nodes.TextElement):
        pass

    class role_video(nodes.General, nodes.TextElement):
        pass

    class VideoDirective(Directive):
        has_content = False
        required_arguments = 1
        optional_arguments = 0
        final_argument_whitespace = True
        option_spec = {'width': directives.nonnegative_int,
                       'height': directives.nonnegative_int}

        def run(self):
            set_classes(self.options)
            node = role_video(source=self.arguments[0], **self.options)
            return [node]

    generic_docroles = {
        'doc': role_doc}

    for rolename, nodeclass in generic_docroles.iteritems():
        generic = roles.GenericRole(rolename, nodeclass)
        role = roles.CustomRole(rolename, generic, {'classes': [rolename]})
        roles.register_local_role(rolename, role)

    directives.register_directive('video', VideoDirective)

Builder.load_string('''
#:import parse_color kivy.parser.parse_color



<RstDocument>:
    content: content
    scatter: scatter
    do_scroll_x: False
    canvas:
        Color:
            rgb: parse_color(root.colors['background'])
        Rectangle:
            pos: self.pos
            size: self.size

    Scatter:
        id: scatter
        size_hint_y: None
        height: content.minimum_height
        width: root.width
        scale: 1
        do_translation: False, False
        do_scale: False
        do_rotation: False

        GridLayout:
            id: content
            cols: 1
            height: self.minimum_height
            width: root.width
            padding: 10

<RstTitle>:
    markup: True
    valign: 'top'
    font_size: sp(31 - self.section * 2)
    size_hint_y: None
    height: self.texture_size[1] + dp(20)
    text_size: self.width, None
    bold: True

    canvas:
        Color:
            rgba: parse_color('204a9699')
        Rectangle:
            pos: self.x, self.y + 5
            size: self.width, 1


<RstParagraph>:
    markup: True
    valign: 'top'
    size_hint_y: None
    height: self.texture_size[1] + self.my
    text_size: self.width - self.mx, None

<RstTerm>:
    size_hint: None, None
    height: label.height
    anchor_x: 'left'
    Label:
        id: label
        text: root.text
        markup: True
        valign: 'top'
        size_hint: None, None
        size: self.texture_size[0] + dp(10), self.texture_size[1] + dp(10)

<RstBlockQuote>:
    cols: 2
    content: content
    size_hint_y: None
    height: content.height
    Widget:
        size_hint_x: None
        width: 20
    GridLayout:
        id: content
        cols: 1
        size_hint_y: None
        height: self.minimum_height

<RstLiteralBlock>:
    cols: 1
    content: content
    size_hint_y: None
    height: content.texture_size[1] + dp(20)
    canvas:
        Color:
            rgb: parse_color('#cccccc')
        Rectangle:
            pos: self.x - 1, self.y - 1
            size: self.width + 2, self.height + 2
        Color:
            rgb: parse_color('#eeeeee')
        Rectangle:
            pos: self.pos
            size: self.size
    Label:
        id: content
        markup: True
        valign: 'top'
        text_size: self.width - 20, None
        font_name: 'data/fonts/DroidSansMono.ttf'
        color: (0, 0, 0, 1)

<RstList>:
    cols: 2
    size_hint_y: None
    height: self.minimum_height

<RstListItem>:
    cols: 1
    size_hint_y: None
    height: self.minimum_height

<RstSystemMessage>:
    cols: 1
    size_hint_y: None
    height: self.minimum_height
    canvas:
        Color:
            rgba: 1, 0, 0, .3
        Rectangle:
            pos: self.pos
            size: self.size

<RstWarning>:
    content: content
    cols: 1
    padding: 20
    size_hint_y: None
    height: self.minimum_height
    canvas:
        Color:
            rgba: 1, 0, 0, .5
        Rectangle:
            pos: self.x + 10, self.y + 10
            size: self.width - 20, self.height - 20
    GridLayout:
        cols: 1
        id: content
        size_hint_y: None
        height: self.minimum_height

<RstNote>:
    content: content
    cols: 1
    padding: 20
    size_hint_y: None
    height: self.minimum_height
    canvas:
        Color:
            rgba: 0, 1, 0, .5
        Rectangle:
            pos: self.x + 10, self.y + 10
            size: self.width - 20, self.height - 20
    GridLayout:
        cols: 1
        id: content
        size_hint_y: None
        height: self.minimum_height

<RstImage>:
    size_hint: None, None
    size: self.texture_size[0], self.texture_size[1] + dp(10)

<RstAsyncImage>:
    size_hint: None, None
    size: self.texture_size[0], self.texture_size[1] + dp(10)

<RstDefinitionList>:
    cols: 1
    size_hint_y: None
    height: self.minimum_height

<RstDefinition>:
    cols: 2
    size_hint_y: None
    height: self.minimum_height

<RstFieldList>:
    cols: 2
    size_hint_y: None
    height: self.minimum_height

<RstFieldName>:
    markup: True
    valign: 'top'
    size_hint: None, 1
    color: (0, 0, 0, 1)
    bold: True
    text_size: self.width - 10, self.height - 10
    valign: 'top'

<RstFieldBody>:
    cols: 1
    size_hint_y: None
    height: self.minimum_height

<RstTable>:
    size_hint_y: None
    height: self.minimum_height

<RstEntry>:
    cols: 1
    size_hint_y: None
    height: self.minimum_height

    canvas:
        Color:
            rgb: .2, .2, .2
        Line:
            points: [\
            self.x,\
            self.y,\
            self.right,\
            self.y,\
            self.right,\
            self.top,\
            self.x,\
            self.top,\
            self.x,\
            self.y]

<RstTransition>:
    size_hint_y: None
    height: 20
    canvas:
        Color:
            rgb: .2, .2, .2
        Line:
            points: [self.x, self.center_y, self.right, self.center_y]

<RstListBullet>:
    markup: True
    valign: 'top'
    size_hint_x: None
    width: self.texture_size[0] + dp(10)
    text_size: None, self.height - dp(10)

<RstEmptySpace>:
    size_hint: 0.01, 0.01

<RstDefinitionSpace>:
    size_hint: None, 0.1
    width: 50

<RstVideoPlayer>:
    options: {'allow_stretch': True}
    canvas.before:
        Color:
            rgba: (1, 1, 1, 1)
        BorderImage:
            source: 'atlas://data/images/defaulttheme/player-background'
            pos: self.x - 25, self.y - 25
            size: self.width + 50, self.height + 50
            border: (25, 25, 25, 25)
''')


class RstVideoPlayer(VideoPlayer):
    pass


class RstDocument(ScrollView):
    '''Base widget used to store an Rst document. See module documentation for
    more information.
    '''
    source = StringProperty(None)
    '''Filename of the RST document.

    :data:`source` is a :class:`~kivy.properties.StringProperty`, default to
    None.
    '''

    text = StringProperty(None)
    '''RST markup text of the document.

    :data:`text` is a :class:`~kivy.properties.StringProperty`, default to None.
    '''

    document_root = StringProperty(None)
    '''Root path where :doc: will search any rst document. If no path is
    given, then it will use the directory of the first loaded source.

    :data:`document_root` is a :class:`~kivy.properties.StringProperty`, default
    to None.
    '''

    show_errors = BooleanProperty(False)
    '''Indicate if RST parsers errors must be shown on the screen or not.

    :data:`show_errors` is a :class:`~kivy.properties.BooleanProperty`, default
    to False
    '''

    colors = DictProperty({
        'background': 'e5e6e9',
        'link': 'ce5c00',
        'paragraph': '202020',
        'title': '204a87',
        'bullet': '000000'})
    '''Dictionary of all the colors used in the RST rendering.

    .. warning::

        This dictionary is needs special handling. You also need to call
        :meth:`RstDocument.render` if you change them after loading.

    :data:`colors` is a :class:`~kivy.properties.DictProperty`.
    '''

    title = StringProperty('')
    '''Title of the current document.

    :data:`title` is a :class:`~kivy.properties.StringProperty`, default to ''
    in read-only.
    '''

    toctrees = DictProperty({})
    '''Toctree of all loaded or preloaded documents. This dictionary is filled
    when a rst document is explicitly loaded, or where :meth:`preload` has been
    called.

    If the document has no filename, e.g., when the document is loaded from a
    text file, the key will be ''.

    :data:`toctrees` is a :class:`~kivy.properties.DictProperty`, default to {}.
    '''

    # internals.
    content = ObjectProperty(None)
    scatter = ObjectProperty(None)
    anchors_widgets = ListProperty([])
    refs_assoc = DictProperty({})

    def __init__(self, **kwargs):
        self._trigger_load = Clock.create_trigger(self._load_from_text, -1)
        self._parser = rst.Parser()
        self._settings = frontend.OptionParser(
                components=(rst.Parser, )).get_default_values()
        super(RstDocument, self).__init__(**kwargs)

    def on_source(self, instance, value):
        if self.document_root is None:
            # set the documentation root to the directory name of the first tile
            self.document_root = dirname(value)
        self._load_from_source()

    def on_text(self, instance, value):
        self._trigger_load()

    def render(self):
        '''Force document rendering.
        '''
        self._load_from_text()

    def resolve_path(self, filename):
        '''Get the path for this filename. If the filename doesn't exist,
        it return the document_root + filename.
        '''
        if exists(filename):
            return filename
        return join(self.document_root, filename)

    def preload(self, filename):
        '''Preload a rst file to get its toctree, and its title.

        The result will be stored in :data:`toctrees` with the ``filename`` as
        key.
        '''
        if filename in self.toctrees:
            return
        if not exists(filename):
            return

        with open(filename) as fd:
            text = fd.read()
        # parse the source
        document = utils.new_document('Document', self._settings)
        self._parser.parse(text, document)
        # fill the current document node
        visitor = _ToctreeVisitor(document)
        document.walkabout(visitor)
        self.toctrees[filename] = visitor.toctree

    def _load_from_source(self):
        filename = self.resolve_path(self.source)
        self.preload(filename)
        with open(filename) as fd:
            self.text = fd.read()

    def _load_from_text(self, *largs):
        try:
            # clear the current widgets
            self.content.clear_widgets()
            self.anchors_widgets = []
            self.refs_assoc = {}

            # parse the source
            document = utils.new_document('Document', self._settings)
            self._parser.parse(self.text, document)

            # fill the current document node
            visitor = _Visitor(self, document)
            document.walkabout(visitor)

            self.title = visitor.title or 'No title'
        except:
            Logger.exception('Rst: error while loading text')

    def on_ref_press(self, node, ref):
        self.goto(ref)

    def goto(self, ref, *largs):
        '''Scroll to the reference. If it's not found, nothing will be done.

        For this text::

            .. _myref:

            This is something I always wanted.

        You can do::

            from kivy.clock import Clock
            from functools import partial

            doc = RstDocument(...)
            Clock.schedule_once(partial(doc.goto, 'myref'), 0.1)

        .. note::

            It is preferable to delay the call of the goto if you just loaded
            the document, because the layout might not be finished, or if the
            size of the RstDocument is not fixed yet, then the calculation of
            the scrolling would be wrong.

            However, you can do a direct call if the document is already loaded.

        .. versionadded:: 1.3.0
        '''
        # check if it's a file ?
        if self.document_root is not None and ref.endswith('.rst'):
            filename = join(self.document_root, ref)
            if exists(filename):
                self.source = filename
                return

        # get the association
        ref = self.refs_assoc.get(ref, ref)

        # search into all the nodes containing anchors
        ax = ay = None
        for node in self.anchors_widgets:
            if ref in node.anchors:
                ax, ay = node.anchors[ref]
                break

        # not found, stop here
        if ax is None:
            return

        # found, calculate the real coordinate

        # get the anchor coordinate inside widget space
        ax += node.x
        ay = node.top - ay
        #ay += node.y

        # what's the current coordinate for us?
        sx, sy = self.scatter.x, self.scatter.top
        #ax, ay = self.scatter.to_parent(ax, ay)

        ay -= self.height

        dx, dy = self.convert_distance_to_scroll(0, ay)
        dy = max(0, min(1, dy))
        Animation(scroll_y=dy, d=.25, t='in_out_expo').start(self)

    def add_anchors(self, node):
        self.anchors_widgets.append(node)


class RstTitle(Label):

    section = NumericProperty(0)


class RstParagraph(Label):

    mx = NumericProperty(10)

    my = NumericProperty(10)


class RstTerm(AnchorLayout):
    text = StringProperty('')


class RstBlockQuote(GridLayout):
    content = ObjectProperty(None)


class RstLiteralBlock(GridLayout):
    content = ObjectProperty(None)


class RstList(GridLayout):
    pass


class RstListItem(GridLayout):
    content = ObjectProperty(None)


class RstListBullet(Label):
    pass


class RstSystemMessage(GridLayout):
    pass


class RstWarning(GridLayout):
    content = ObjectProperty(None)


class RstNote(GridLayout):
    content = ObjectProperty(None)


class RstImage(Image):
    pass


class RstAsyncImage(AsyncImage):
    pass


class RstDefinitionList(GridLayout):
    pass


class RstDefinition(GridLayout):
    pass


class RstFieldList(GridLayout):
    pass


class RstFieldName(Label):
    pass


class RstFieldBody(GridLayout):
    pass


class RstGridLayout(GridLayout):
    pass


class RstTable(GridLayout):
    pass


class RstEntry(GridLayout):
    pass


class RstTransition(Widget):
    pass


class RstEmptySpace(Widget):
    pass


class RstDefinitionSpace(Widget):
    pass


class _ToctreeVisitor(nodes.NodeVisitor):

    def __init__(self, *largs):
        self.toctree = self.current = []
        self.queue = []
        self.text = ''
        nodes.NodeVisitor.__init__(self, *largs)

    def push(self, tree):
        self.queue.append(tree)
        self.current = tree

    def pop(self):
        self.current = self.queue.pop()

    def dispatch_visit(self, node):
        cls = node.__class__
        #print '>>>', cls, node.attlist() if hasattr(node, 'attlist') else ''
        if cls is nodes.section:
            section = {
                'ids': node['ids'],
                'names': node['names'],
                'title': '',
                'children': []}
            if isinstance(self.current, dict):
                self.current['children'].append(section)
            else:
                self.current.append(section)
            self.push(section)
        elif cls is nodes.title:
            self.text = ''
        elif cls is nodes.Text:
            self.text += node

    def dispatch_departure(self, node):
        cls = node.__class__
        #print '<--', cls, node.attlist() if hasattr(node, 'attlist') else ''
        if cls is nodes.section:
            self.pop()
        elif cls is nodes.title:
            self.current['title'] = self.text


class _Visitor(nodes.NodeVisitor):

    def __init__(self, root, *largs):
        self.root = root
        self.title = None
        self.current_list = []
        self.current = None
        self.idx_list = None
        self.text = ''
        self.text_have_anchor = False
        self.section = 0
        self.do_strip_text = False
        nodes.NodeVisitor.__init__(self, *largs)

    def push(self, widget):
        self.current_list.append(self.current)
        self.current = widget

    def pop(self):
        self.current = self.current_list.pop()

    def dispatch_visit(self, node):
        cls = node.__class__
        #print '>>>', cls, node.attlist() if hasattr(node, 'attlist') else ''
        if cls is nodes.document:
            self.push(self.root.content)

        elif cls is nodes.section:
            self.section += 1

        elif cls is nodes.title:
            label = RstTitle(section=self.section)
            self.current.add_widget(label)
            self.push(label)
            #assert(self.text == '')

        elif cls is nodes.Text:
            if self.do_strip_text:
                node = node.replace('\n', ' ')
                node = node.replace('  ', ' ')
                node = node.replace('\t', ' ')
                node = node.replace('  ', ' ')
                if node.startswith(' '):
                    node = ' ' + node.lstrip(' ')
                if node.endswith(' '):
                    node = node.rstrip(' ') + ' '
                if self.text.endswith(' ') and node.startswith(' '):
                    node = node[1:]
            self.text += node

        elif cls is nodes.paragraph:
            self.do_strip_text = True
            label = RstParagraph()
            if isinstance(self.current, RstEntry):
                label.mx = 10
            self.current.add_widget(label)
            self.push(label)

        elif cls is nodes.literal_block:
            box = RstLiteralBlock()
            self.current.add_widget(box)
            self.push(box)

        elif cls is nodes.emphasis:
            self.text += '[i]'

        elif cls is nodes.strong:
            self.text += '[b]'

        elif cls is nodes.literal:
            self.text += '[font=fonts/DroidSansMono.ttf]'

        elif cls is nodes.block_quote:
            box = RstBlockQuote()
            self.current.add_widget(box)
            self.push(box.content)
            assert(self.text == '')

        elif cls is nodes.enumerated_list:
            box = RstList()
            self.current.add_widget(box)
            self.push(box)
            self.idx_list = 0

        elif cls is nodes.bullet_list:
            box = RstList()
            self.current.add_widget(box)
            self.push(box)
            self.idx_list = None

        elif cls is nodes.list_item:
            bullet = '-'
            if self.idx_list is not None:
                self.idx_list += 1
                bullet = '%d.' % self.idx_list
            bullet = self.colorize(bullet, 'bullet')
            item = RstListItem()
            self.current.add_widget(RstListBullet(text=bullet))
            self.current.add_widget(item)
            self.push(item)

        elif cls is nodes.system_message:
            label = RstSystemMessage()
            if self.root.show_errors:
                self.current.add_widget(label)
            self.push(label)

        elif cls is nodes.warning:
            label = RstWarning()
            self.current.add_widget(label)
            self.push(label.content)
            assert(self.text == '')

        elif cls is nodes.note:
            label = RstNote()
            self.current.add_widget(label)
            self.push(label.content)
            assert(self.text == '')

        elif cls is nodes.image:
            uri = node['uri']
            if uri.startswith('/') and self.root.document_root:
                uri = join(self.root.document_root, uri[1:])
            if uri.startswith('http://') or uri.startswith('https://'):
                image = RstAsyncImage(source=uri)
            else:
                image = RstImage(source=uri)

            align = node.get('align', 'center')
            root = AnchorLayout(size_hint_y=None, anchor_x=align, height=1)
            image.bind(height=root.setter('height'))
            root.add_widget(image)
            self.current.add_widget(root)

        elif cls is nodes.definition_list:
            lst = RstDefinitionList()
            self.current.add_widget(lst)
            self.push(lst)

        elif cls is nodes.term:
            assert(isinstance(self.current, RstDefinitionList))
            term = RstTerm()
            self.current.add_widget(term)
            self.push(term)

        elif cls is nodes.definition:
            assert(isinstance(self.current, RstDefinitionList))
            definition = RstDefinition()
            definition.add_widget(RstDefinitionSpace())
            self.current.add_widget(definition)
            self.push(definition)

        elif cls is nodes.field_list:
            fieldlist = RstFieldList()
            self.current.add_widget(fieldlist)
            self.push(fieldlist)

        elif cls is nodes.field_name:
            name = RstFieldName()
            self.current.add_widget(name)
            self.push(name)

        elif cls is nodes.field_body:
            body = RstFieldBody()
            self.current.add_widget(body)
            self.push(body)

        elif cls is nodes.table:
            table = RstTable(cols=0)
            self.current.add_widget(table)
            self.push(table)

        elif cls is nodes.colspec:
            self.current.cols += 1

        elif cls is nodes.entry:
            entry = RstEntry()
            self.current.add_widget(entry)
            self.push(entry)

        elif cls is nodes.transition:
            self.current.add_widget(RstTransition())

        elif cls is nodes.reference:
            name = node.get('name', node.get('refuri'))
            self.text += '[ref=%s][color=%s]' % (name,
                    self.root.colors.get('link',
                        self.root.colors.get('paragraph')))
            if 'refname' in node and 'name' in node:
                self.root.refs_assoc[node['name']] = node['refname']

        elif cls is nodes.target:
            name = None
            if 'ids' in node:
                name = node['ids'][0]
            elif 'names' in node:
                name = node['names'][0]
            self.text += '[anchor=%s]' % name
            self.text_have_anchor = True

        elif cls is role_doc:
            self.doc_index = len(self.text)

        elif cls is role_video:
            pass

    def dispatch_departure(self, node):
        cls = node.__class__
        #print '<--', cls
        if cls is nodes.document:
            self.pop()

        elif cls is nodes.section:
            self.section -= 1

        elif cls is nodes.title:
            assert(isinstance(self.current, RstTitle))
            if not self.title:
                self.title = self.text
            self.set_text(self.current, 'title')
            self.pop()

        elif cls is nodes.Text:
            pass

        elif cls is nodes.paragraph:
            self.do_strip_text = False
            assert(isinstance(self.current, RstParagraph))
            self.set_text(self.current, 'paragraph')
            self.pop()

        elif cls is nodes.literal_block:
            assert(isinstance(self.current, RstLiteralBlock))
            self.set_text(self.current.content, 'literal_block')
            self.pop()

        elif cls is nodes.emphasis:
            self.text += '[/i]'

        elif cls is nodes.strong:
            self.text += '[/b]'

        elif cls is nodes.literal:
            self.text += '[/font]'

        elif cls is nodes.block_quote:
            self.pop()

        elif cls is nodes.enumerated_list:
            self.idx_list = None
            self.pop()

        elif cls is nodes.bullet_list:
            self.pop()

        elif cls is nodes.list_item:
            self.pop()

        elif cls is nodes.system_message:
            self.pop()

        elif cls is nodes.warning:
            self.pop()

        elif cls is nodes.note:
            self.pop()

        elif cls is nodes.definition_list:
            self.pop()

        elif cls is nodes.term:
            assert(isinstance(self.current, RstTerm))
            self.set_text(self.current, 'term')
            self.pop()

        elif cls is nodes.definition:
            self.pop()

        elif cls is nodes.field_list:
            self.pop()

        elif cls is nodes.field_name:
            assert(isinstance(self.current, RstFieldName))
            self.set_text(self.current, 'field_name')
            self.pop()

        elif cls is nodes.field_body:
            self.pop()

        elif cls is nodes.table:
            self.pop()

        elif cls is nodes.colspec:
            pass

        elif cls is nodes.entry:
            self.pop()

        elif cls is nodes.reference:
            self.text += '[/color][/ref]'

        elif cls is role_doc:
            docname = self.text[self.doc_index:]
            rst_docname = docname
            if rst_docname.endswith('.rst'):
                docname = docname[:-4]
            else:
                rst_docname += '.rst'

            # try to preload it
            filename = self.root.resolve_path(rst_docname)
            self.root.preload(filename)

            # if exist, use the title of the first section found in the document
            title = docname
            if filename in self.root.toctrees:
                toctree = self.root.toctrees[filename]
                if len(toctree):
                    title = toctree[0]['title']

            # replace the text with a good reference
            text = '[ref=%s]%s[/ref]' % (
                    rst_docname,
                    self.colorize(title, 'link'))
            self.text = self.text[:self.doc_index] + text

        elif cls is role_video:
            width = node['width'] if 'width' in node.attlist() else 400
            height = node['height'] if 'height' in node.attlist() else 300
            uri = node['source']
            if uri.startswith('/') and self.root.document_root:
                uri = join(self.root.document_root, uri[1:])
            video = RstVideoPlayer(
                    source=uri,
                    size_hint=(None, None),
                    size=(width, height))
            anchor = AnchorLayout(size_hint_y=None, height=height + 20)
            anchor.add_widget(video)
            self.current.add_widget(anchor)

    def set_text(self, node, parent):
        text = self.text
        if parent == 'term' or parent == 'field_name':
            text = '[b]%s[/b]' % text
        # search anchors
        node.text = self.colorize(text, parent)
        node.bind(on_ref_press=self.root.on_ref_press)
        if self.text_have_anchor:
            self.root.add_anchors(node)
        self.text = ''
        self.text_have_anchor = False

    def colorize(self, text, name):
        return '[color=%s]%s[/color]' % (
            self.root.colors.get(name, self.root.colors['paragraph']),
            text)

if __name__ == '__main__':
    from kivy.base import runTouchApp
    import sys
    runTouchApp(RstDocument(source=sys.argv[1]))