U
    Peq+                     @   s   d Z ddlZddlZddlmZ ddlmZ ddlmZmZ ddl	Z	ddl
mZ ddlZeeee	jZeedZeedZeed	Zd
ZeedZdd Zdd Zdd Zd"ddZdd Zdd Zdd Zdd Zdd Zdd  Zed!kre  dS )#a0   Create rst documentation of the examples directory.

This uses screenshots in the screenshots_dir
(currently doc/sources/images/examples) along with source code and files
in the examples/ directory to create rst files in the generation_dir
(doc/sources/examples) gallery.rst, index.rst, and gen__*.rst

    N)sep)join)dirnameabspath)LoggerZexampleszdoc/sources/images/exampleszdoc/sources/examplesz../images/examples/zgallery.rstc                 c   s   t d}t| D ]}|d D ]}|dr ||}|dkrRdd|iV  q |ddt	}|d||d	|d
t
||d	d |d
 dV  q qdS )a  
    Yield info (dict) of each matching screenshot found walking the
    directory dir_name. A matching screenshot uses double underscores to
    separate fields, i.e. path__to__filename__py.png as the screenshot for
    examples/path/to/filename.py.

    Files not ending with .png are ignored, others are either parsed or
    yield an error.

    Info fields 'dunder', 'dir', 'file', 'ext', 'source' if not 'error'
    z^((.+)__(.+)__([^-]+))\.png   .pngNerrorz1png filename not following screenshot pattern: {}__         .)dunderdirfileextsource)recompileoswalkendswithmatchformatgroupreplacer   slash)dir_namepatterntfilenamemd r$   6/tmp/pip-unpacked-wheel-xzebddm3/kivy/tools/gallery.pyiter_filename_info&   s     



r&   c                 C   sv   d}d |}t|| tj}|rj|ddd}|d|dd  }|d	|d
|d|dS ddiS dS )av   parse docstring from text (normal string with '
's) and return an info
    dict. A docstring should the first triple quoted string, have a title
    followed by a line of equal signs, and then a description at
    least one sentence long.

    fields are 'docstring', 'title', and 'first_sentence' if not 'error'
    'first_sentence' is a single line without newlines.
    z"""|'''z!({})\s+([^\n]+)\s+\=+\s+(.*?)(\1)r   
 Nr   r   r   r   )Z	docstringtitledescriptionfirst_sentencer	   z1Did not find docstring with title at top of file.)r   r   searchSr   r   find)textqpr"   commentr+   r$   r$   r%   parse_docstring_infoD   s    	
 r3   c              
   c   s   t | D ]}d|kr$t|d  qtt|d |d d |d  }tj|s^td| qt|L}|	 }t
|}d|krt|d d |  W 5 Q R  qn
|| W 5 Q R X |V  qdS )	z Iterate over screenshots in directory, yield info from the file
     name and initial parse of the docstring. Errors are logged, but
     files with errors are skipped.
    r	   r   r   r   r   z;Screen shot references source code that does not exist:  %sz  File: N)r&   r   r	   r   examples_dirr   pathexistsopenreadr3   update)r   	file_infor   fr/   Zdocstring_infor$   r$   r%   iter_docstring_infoY   s(    

r<   O   c                    s   | d  d}dd |D }d|}| d d | d  g| d	< d
}t||D ]}|| d	 krP| d	 | qPd| d  tdd d }tdd|}|d|}dd | dD } fdd|D }|| d< dS )aF   Using the info['description'], add fields to info.

    info['files'] is the source filename and any filenames referenced by the
    magic words in the description, e.g. 'the file xxx.py' or
    'The image this.png'. These are as written in the description, do
    not allow ../dir notation, and are relative to the source directory.

    info['enhanced_description'] is the description, as an array of
    paragraphs where each paragraph is an array of lines wrapped to width
    line_length. This enhanced description include the rst links to
    the files of info['files'].
    r*   z

c                 S   s   g | ]}| d dqS )r'   	$newline$r   ).0	paragraphr$   r$   r%   
<listcomp>   s   z,enhance_info_description.<locals>.<listcomp>r'   r   r   r   filesz$[tT]he (?:file|image) ([\w\/]+\.\w+)_r   Nz&([tT]he (?:file|image) )([\w\/]+\.\w+)z\1:ref:`\2 <$folder$\2>`z$folder$c                 S   s   g | ]}| d dqS )r>   r'   r?   r@   liner$   r$   r%   rB      s     c                    s(   g | ] }| d st| n|gqS )r(   )
startswithtextwrapwraprF   line_lengthr$   r%   rB      s   enhanced_description)splitr   r   findallappendr   subr   )inforL   Z
paragraphslinesr/   regexnamefolderr$   rK   r%   enhance_info_descriptions   s*    
  
rW   c                 C   sH   dd t | D }|jdd d t|D ]\}}||d< t| q*|S )z return infos, an array info dicts for each matching screenshot in the
    dir, sorted by source file name, and adding the field 'num' as he unique
    order in this array of dicts'.

    c                 S   s   g | ]}|qS r$   r$   )r@   ir$   r$   r%   rB      s     zget_infos.<locals>.<listcomp>c                 S   s   | d S )Nr   r$   )xr$   r$   r%   <lambda>       zget_infos.<locals>.<lambda>)keynum)r<   sort	enumeraterW   )r   infosr]   rR   r$   r$   r%   	get_infos   s    
ra   c                 C   s4   d}|g}| D ]}| djf | qd|d S )zy return string of the rst (Restructured Text) of the gallery page,
    showing information on all screenshots found.
    a  
Gallery
-------

.. _Tutorials:  ../tutorials-index.html

.. container:: title

    This gallery lets you explore the many examples included with Kivy.
    Click on any screenshot to see the code.

This gallery contains:

    * Examples from the examples/ directory that show specific capabilities of
      different libraries and features of Kivy.
    * Demonstrations from the examples/demos/ directory that explore many of
      Kivy's abilities.

There are more Kivy programs elsewhere:

    * Tutorials_ walks through the development of complete Kivy applications.
    * Unit tests found in the source code under the subdirectory kivy/tests/
      can also be useful.

We hope your journey into learning Kivy is exciting and fun!

z
**{title}** (:doc:`{source}<gen__{dunder}>`)

{description}
.. image:: ../images/examples/{dunder}.png
  :width:  216pt
  :align:  left
  :target: gen__{dunder}.htmlr'   rP   r   r   )r`   Zgallery_topoutputrR   r$   r$   r%   make_gallery_page   s    rd   c           	         s  d$ fdd	}g |d |dt  d   |d |d |   d	 D ]}|D ]}|| qV|  qNd
} d D ],}t d |}td|d}|d|td d  d|kr|ttd }|dkrd| d }|d|  |dt |  |d|  |d qxd| d }|d|  |dt |  ||krt|dkrt|d|dd   |d  |}n|dkr|d! |d  |}|d"|  |d# qxdd S )%zE return str of the rst text for the detail page of the file in info.  c                    s    | jf   dS )z? append formatted s to output, which will be joined into lines N)rP   r   )srR   rc   r$   r%   a   s    zmake_detail_page.<locals>.az{title}=r)   zU
.. |pic{num}| image:: /images/examples/{dunder}.png
   :width: 50%
   :align: middlez
|pic{num}|rM   z.pyrC   r   z\.\w+$r   z
.. _`rD   z`:\r   )r   z.jpgz.jpegzImage **z**r'   ~z
.. image:: ../../../examples/z    :align:  centerzFile **z.txtz
.. highlight:: r   Nz    :linenothreshold: 3z
.. highlight:: nonez 
.. include:: ../../../examples/z
    :code:)re   )lenr   r   r,   r   r   r   r   )	rR   rh   rA   rG   Z	last_langfnameZ	full_namer   r)   r$   rg   r%   make_detail_page   sL    




rn   c              	   C   sF   t j| }t j|s"t | t| d}|| W 5 Q R X dS )z" write the string to the filename wN)r   r5   r   r6   makedirsr7   write)rU   rf   	directoryr;   r$   r$   r%   
write_file  s
    
rs   c                 C   s6   d}|g}| D ]}| d|d  qd|d S )z< return string of the rst for the gallery's index.rst file. zT
Gallery of Examples
===================

.. toctree::
    :maxdepth: 1

    galleryz    gen__{}r   r'   rb   )r`   Zstart_stringrc   rR   r$   r$   r%   
make_index  s
    rt   c                  C   st   t t} t| }tt| | D ]*}t|}ttd|d }t|| qt	| }ttd}t|| t
d dS )zO Do the main task of writing the gallery,
    detail, and index rst pages.
    zgen__{}.rstr   z	index.rstz4gallery.py: Created gallery rst documentation pages.N)ra   screenshots_dirrd   rs   gallery_filenamern   r   generation_dirr   rt   r   rR   )r`   rf   rR   Zdetail_nameZ
index_namer$   r$   r%   write_all_rst_pages.  s    


rx   __main__)r=   )__doc__r   r   os.pathr   r   r   r   r   ZkivyZkivy.loggerr   rI   __file__base_dirr4   ru   rw   Z	image_dirrv   r&   r3   r<   rW   ra   rd   rn   rs   rt   rx   __name__r$   r$   r$   r%   <module>   s4   





--6