U
    Pe=                     @   s   d Z dZddlmZ ddlmZ ddlmZm	Z	 ddl
mZ ddlmZmZmZmZmZmZmZmZmZ ddlmZ G d	d
 d
eZdS )aP$  Label
=====

.. image:: images/label.png
    :align: right

The :class:`Label` widget is for rendering text::

    # hello world text
    l = Label(text='Hello world')

    # unicode text; can only display glyphs that are available in the font
    l = Label(text='Hello world ' + chr(2764))

    # multiline text
    l = Label(text='Multi\nLine')

    # size
    l = Label(text='Hello world', font_size='20sp')

.. _kivy-uix-label-sizing-and-text-content:

Sizing and text content
---------------------------

By default, the size of :class:`Label` is not affected by :attr:`~Label.text`
content and the text is not affected by the size. In order to control
sizing, you must specify :attr:`~Label.text_size` to constrain the text
and/or bind :attr:`~Label.size` to :attr:`~Label.texture_size` to grow with
the text.

For example, this label's size will be set to the text content
(plus :attr:`~Label.padding`):

.. code-block:: kv

    Label:
        size: self.texture_size

This label's text will wrap at the specified width and be clipped to the
height:

.. code-block:: kv

    Label:
        text_size: cm(6), cm(4)

.. note:: The :attr:`~Label.shorten` and :attr:`~Label.max_lines` attributes
 control how overflowing text behaves.

Combine these concepts to create a Label that can grow vertically but wraps the
text at a certain width:

.. code-block:: kv

    Label:
        text_size: root.width, None
        size: self.texture_size

How to have a custom background color in the label:

.. code-block:: kv

    # Define your background color Template
    <BackgroundColor@Widget>
        background_color: 1, 1, 1, 1
        canvas.before:
            Color:
                rgba: root.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    # Now you can simply Mix the `BackgroundColor` class with almost
    # any other widget... to give it a background.
    <BackgroundLabel@Label+BackgroundColor>
        background_color: 0, 0, 0, 0
        # Default the background color for this label
        # to r 0, g 0, b 0, a 0
    # Use the BackgroundLabel any where in your kv code like below
    BackgroundLabel
        text: 'Hello'
        background_color: 1, 0, 0, 1

Text alignment and wrapping
---------------------------

The :class:`Label` has :attr:`~Label.halign` and :attr:`~Label.valign`
properties to control the alignment of its text. However, by default the text
image (:attr:`~Label.texture`) is only just large enough to contain the
characters and is positioned in the center of the Label. The valign property
will have no effect and halign will only have an effect if your text has
newlines; a single line of text will appear to be centered even though halign
is set to left (by default).

In order for the alignment properties to take effect, set the
:attr:`~Label.text_size`, which specifies the size of the bounding box within
which text is aligned. For instance, the following code binds this size to the
size of the Label, so text will be aligned within the widget bounds. This
will also automatically wrap the text of the Label to remain within this area.

.. code-block:: kv

    Label:
        text_size: self.size
        halign: 'right'
        valign: 'middle'

Markup text
-----------

.. versionadded:: 1.1.0

You can change the style of the text using :doc:`api-kivy.core.text.markup`.
The syntax is similar to the bbcode syntax but only the inline styling is
allowed::

    # hello world with world in bold
    l = Label(text='Hello [b]World[/b]', markup=True)

    # hello in red, world in blue
    l = Label(text='[color=ff3333]Hello[/color][color=3333ff]World[/color]',
        markup = True)

If you need to escape the markup from the current text, use
:func:`kivy.utils.escape_markup`::

    text = 'This is an important message [1]'
    l = Label(text='[b]' + escape_markup(text) + '[/b]', markup=True)

The following tags are available:

``[b][/b]``
    Activate bold text
``[i][/i]``
    Activate italic text
``[u][/u]``
    Underlined text
``[s][/s]``
    Strikethrough text
``[font=<str>][/font]``
    Change the font (note: this refers to a TTF file or registered alias)
``[font_context=<str>][/font_context]``
    Change context for the font, use string value "none" for isolated context
    (this is equivalent to `None`; if you created a font context named
    `'none'`, it cannot be referred to using markup)
``[font_family=<str>][/font_family]``
    Font family to request for drawing. This is only valid when using a
    font context, see :class:`kivy.uix.label.Label` for details.
``[font_features=<str>][/font_features]``
    OpenType font features, in CSS format, this is passed straight
    through to Pango. The effects of requesting a feature depends on loaded
    fonts, library versions, etc. Pango only, requires v1.38 or later.
``[size=<integer>][/size]``
    Change the font size
``[color=#<color>][/color]``
    Change the text color
``[ref=<str>][/ref]``
    Add an interactive zone. The reference + bounding box inside the
    reference will be available in :attr:`Label.refs`
``[anchor=<str>]``
    Put an anchor in the text. You can get the position of your anchor within
    the text with :attr:`Label.anchors`
``[sub][/sub]``
    Display the text at a subscript position relative to the text before it.
``[sup][/sup]``
    Display the text at a superscript position relative to the text before it.
``[text_language=<str>][/text_language]``
    Language of the text, this is an RFC-3066 format language tag (as string),
    for example "en_US", "zh_CN", "fr" or "ja". This can impact font selection
    and metrics. Use the string "None" to revert to locale detection.
    Pango only.

If you want to render the markup text with a [ or ] or & character, you need to
escape them. We created a simple syntax::

    [   -> &bl;
    ]   -> &br;
    &   -> &amp;

Then you can write::

    "[size=24]Hello &bl;World&br;[/size]"

Interactive zone in text
------------------------

.. versionadded:: 1.1.0

You can now have definable "links" using text markup. The idea is to be able
to detect when the user clicks on part of the text and to react.
The tag ``[ref=xxx]`` is used for that.

In this example, we are creating a reference on the word "World". When
this word is clicked, the function ``print_it`` will be called with the
name of the reference::

    def print_it(instance, value):
        print('User clicked on', value)
    widget = Label(text='Hello [ref=world]World[/ref]', markup=True)
    widget.bind(on_ref_press=print_it)

For prettier rendering, you could add a color for the reference. Replace the
``text=`` in the previous example with::

    'Hello [ref=world][color=0000ff]World[/color][/ref]'

Catering for Unicode languages
------------------------------

The font kivy uses does not contain all the characters required for displaying
all languages. When you use the built-in widgets, this results in a block being
drawn where you expect a character.

If you want to display such characters, you can chose a font that supports them
and deploy it universally via kv:

.. code-block:: kv

    <Label>:
        font_name: '/<path>/<to>/<font>'

Note that this needs to be done before your widgets are loaded as kv rules are
only applied at load time.

Usage example
-------------

The following example marks the anchors and references contained in a label::

    from kivy.app import App
    from kivy.uix.label import Label
    from kivy.clock import Clock
    from kivy.graphics import Color, Rectangle


    class TestApp(App):

        @staticmethod
        def get_x(label, ref_x):
            """ Return the x value of the ref/anchor relative to the canvas """
            return label.center_x - label.texture_size[0] * 0.5 + ref_x

        @staticmethod
        def get_y(label, ref_y):
            """ Return the y value of the ref/anchor relative to the canvas """
            # Note the inversion of direction, as y values start at the top of
            # the texture and increase downwards
            return label.center_y + label.texture_size[1] * 0.5 - ref_y

        def show_marks(self, label):

            # Indicate the position of the anchors with a red top marker
            for name, anc in label.anchors.items():
                with label.canvas:
                    Color(1, 0, 0)
                    Rectangle(pos=(self.get_x(label, anc[0]),
                                   self.get_y(label, anc[1])),
                              size=(3, 3))

            # Draw a green surround around the refs. Note the sizes y inversion
            for name, boxes in label.refs.items():
                for box in boxes:
                    with label.canvas:
                        Color(0, 1, 0, 0.25)
                        Rectangle(pos=(self.get_x(label, box[0]),
                                       self.get_y(label, box[1])),
                                  size=(box[2] - box[0],
                                        box[1] - box[3]))

        def build(self):
            label = Label(
                text='[anchor=a]a\nChars [anchor=b]b\n[ref=myref]ref[/ref]',
                markup=True)
            Clock.schedule_once(lambda dt: self.show_marks(label), 1)
            return label

    TestApp().run()

)Label    )Clock)Widget)r   DEFAULT_FONT)MarkupLabel)	StringPropertyOptionPropertyNumericPropertyBooleanPropertyListPropertyObjectPropertyDictPropertyColorPropertyVariableListProperty)get_hex_from_colorc                       s  e Zd ZdZdgZdZ fddZdd Zdd	d
Zdd Z	 fddZ
dd ZeddddgZedZeddgZeddddddgddZedddZedddZedddZeeZeddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddgdZedddddgdZedZe ZedZedZ edZ!edZ"edZ#edddZ$edddZ%e&ddddgddčZ'eddddddgdZ(edddddgdZ)eddddgZ*edddZ+eddddgZ,eddddgZ-e.dddZ/eddgZ0edZ1edZ2eddddgdZ3edZ4edZ5e6i Z7edddZ8edZ9e6i Z:e6i Z;edZ<edZ=edddddgddZ>edZ?edZ@  ZAS )r   zLabel class, see module documentation for more information.

    :Events:
        `on_ref_press`
            Fired when the user clicks on a word referenced with a
            ``[ref]`` tag in a text markup.
    on_ref_press)$text	font_size	font_namefont_script_namefont_directionbolditalic	underlinestrikethroughfont_familycolordisabled_colorhalignvalignpaddingoutline_widthdisabled_outline_coloroutline_color	text_sizeshortenmipmapline_height	max_linesstripshorten_from	split_strellipsis_optionsunicode_errorsmarkupfont_hintingfont_kerningfont_blendedfont_contextfont_featuresbase_directiontext_languagec                    s   t | jd| _tt| jf | tj}| j}| j	}|d|d |d|d |d|d |D ]}|||| q\d | _
|   |   d S )N	padding_x	padding_ydisabled)r   Zcreate_triggertexture_update_trigger_texturesuperr   __init___font_propertiesfbind_trigger_texture_update_label_create_label)selfkwargsdr?   updatex	__class__ 2/tmp/pip-unpacked-wheel-xzebddm3/kivy/uix/label.pyr=   <  s    zLabel.__init__c                    s    j d k	r j j}nd } j}|r*|tk	s6|s|tk	r fdd jD } j|d<  jrn j|d<  j	|d< |rtf | _ ntf | _ d S )Nc                    s   i | ]}|t  |qS rJ   )getattr).0rG   rC   rJ   rK   
<dictcomp>]  s      z'Label._create_label.<locals>.<dictcomp>usersizer   r#   )
rA   rI   r.   CoreMarkupLabel	CoreLabelr>   r$   r9   r   r"   )rC   clsr.   dkwrJ   rN   rK   rB   S  s"    




zLabel._create_labelNc                 C   s(  |dkr|    |r|dkr(|| j_n|dkr:|| j_n|dkrP|| jj|< n|dkrl| jrl|| jjd< n|dkr| jr|| jjd< n|d	kr|r| jn| j| jjd< |r| jn| j	| jjd< nZ|d
kr|gd | jjd d d d< n4|dkr|gd | jjd dd d< n|| jj|< | 
  d S )Nr.   r   r$   r   r   r   r"   r#   r9   r7      r    r8      )rB   rA   r   rP   optionsr9   r   r   r"   r#   r;   )rC   namesourcevaluerJ   rJ   rK   r@   h  s4    





zLabel._trigger_texture_updatec                 G   s*  | j jtk}d| _| j jr6| jdks*| jrh| j j shd| _d| _|rfi i  | _	| j _
i i  | _| j _n|r| j}| jdks| jr| }ddt| jr| jn| jd|df| j _| j   | j jr| j j  | j j	| _	| j j| _n
| j   | j j}|dk	r| j j| _t| jj| _| j j| _dS )	zForce texture recreation with the current Label properties.

        After this function call, the :attr:`texture` and :attr:`texture_size`
        will be updated in this order.
        Njustify)r   r   F z[color=]z[/color])rA   rI   rQ   texturer   r   r)   texture_sizeis_shortenedrefsZ_refsanchorsZ_anchorsjoinr   r9   r   r   Zrefreshbindlistsize)rC   largsZmrkupr   r^   rJ   rJ   rK   r:     sN    
  





zLabel.texture_updatec                    s   t t| |rdS t| js"dS |j\}}|| j| jd d  8 }|| j| jd d  8 }| jd | }| j	 D ]b\}}|D ]T}|\}}}	}
||  kr|	krn q||  kr|
krn q| 
d|   dS qqtdS )NTFr   g       @rV   r   )r<   r   on_touch_downlenra   posZcenter_xr_   Zcenter_yitemsdispatch)rC   touchZtxtyuidZzoneszonerG   ywhrH   rJ   rK   rh     s    

0zLabel.on_touch_downc                 C   s   d S )NrJ   )rC   refrJ   rJ   rK   r     s    zLabel.on_ref_pressrV   g333333?r\   ZltrrtlZweak_rtlZweak_ltrT)rW   	allownone)rv   ZLatnZZyyyZHaniZCyrlZHiraZKanaThaiZArabZHangZDevaZGrekZHebrZTamlZKndaZGeorZMlymZTeluZMymrZGujrZBengZGuruZLaooZZinhZKhmrZTibtZSinhZEthiZThaaZOryaZZzzzZCansZSyrcZBopoZNkooZCherZYiiiZSamrZCoptZMongZGlagZVaiiZBaliZTfngZBamuZBatkZChamJavaZKaliZLepcZLimbZLisuZMandZMteiZTaluZOlckZSaurZSundZSyloZTaleZLanaZAvstZBrahZBugiZBuhdZCariZXsuxZCprtZDsrtZEgypZGothZHanoZArmiZPhliZPrtiZKthiZKharZLinbZLyciZLydiZOgamZItalZXpeoZSarbZOrkhZOsmaZPhagZPhnxZRjngZRunrZShawZTglgZTagbZUgarZCakmZMercZMeroZPlrdZShrdZSoraZTakrZBraiZAghbZBassZDuplZElbaZGranZKhojZLinaZMahjZManiZModiZMrooZNarbZNbatZPalmZPaucZPermZPhlpZSiddZSindZTirhZWaraZAhomZHluwZHatrZMultZHungZSgnwZAdlmZBhksZMarcZOsgeZTangZNewaZGonmZNshuZSoyoZZanbZDogrZGongZRohgZMakaZMedfZSogoZSogdZElymZHmnpZNandZWchoZChrsZDiakZKitsZYeziZCpmnZOugrZTnsaZTotoZVithZKawiZNagm)rW   ZttbZbttZ15spg      ?Fr   )
deprecated   )Zlenghtautoleftcenterrightr[   ZbottomZmiddletopreplace)strictr   ignorenormallightZmono)NNN)B__name__
__module____qualname____doc__Z
__events__r>   r=   rB   r@   r:   rh   r   r   r   r   r   r   r$   r   r4   r5   r2   r   r   r   r   r   r	   r   r3   r'   r
   r   r   r   r   r7   r8   r   r    r   r   r   r!   r#   r"   r   r^   r_   r&   r%   r*   r`   r+   r   r,   r-   r.   ra   rb   r(   r)   r/   r0   r1   __classcell__rJ   rJ   rH   rK   r   %  s  
",
                                                                                                                                         "


 


 &  
 r   N)r   __all__Z
kivy.clockr   Zkivy.uix.widgetr   Zkivy.core.textr   rR   r   Zkivy.core.text.markupr   rQ   Zkivy.propertiesr   r   r	   r
   r   r   r   r   r   Z
kivy.utilsr   rJ   rJ   rJ   rK   <module>   s     ,