
    ը	fC                        d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZmZ ddlmZmZmZ ddlmZ ddlmZ  e        dd	lmZ dd
lmZ ddlmZmZ dddddddddddddddddddddddddddd d!d"d#g	Z G d$ d%e      Zd& Z d' Z!d( Z" e
       \  Z#Z$ G d) d*ejJ                        Z& G d+ d,ejN                        Z(d- Z)e*d.k(  r e)        yy)/a  
@package startup.locdownload

@brief GRASS Location Download Management

Classes:
 - LocationDownloadPanel
 - LocationDownloadDialog
 - DownloadError

(C) 2017 by Vaclav Petras the GRASS Development Team

This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.

@author Vaclav Petras <wenzeslaus gmail com>
    )print_functionN)NewEvent)	try_rmdirlegalize_vector_name)download_and_extractname_from_urlDownloadError)is_location_valid)set_gui_path)Debug)gThread)Button
StaticTextzComplete NC locationzIhttps://grass.osgeo.org/sampledata/north_carolina/nc_spm_08_grass7.tar.gz)labelurlzBasic NC locationzLhttps://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.tar.gzzWorld location in LatLong/WGS84z7https://grass.osgeo.org/sampledata/worldlocation.tar.gzzSpearfish (SD) locationzChttps://grass.osgeo.org/sampledata/spearfish_grass70data-0.3.tar.gzzPiemonte, Italy data setzPhttps://grass.osgeo.org/sampledata/grassdata_piemonte_utm32n_wgs84_grass7.tar.gzz(Slovakia 3D precipitation voxel data setz;https://grass.osgeo.org/sampledata/slovakia3d_grass7.tar.gzzFire simulation sample dataz9https://grass.osgeo.org/sampledata/fire_grass6data.tar.gzz#GISMentors location, Czech Republicz:http://training.gismentors.eu/geodata/grass/gismentors.zipzNatural Earth Dataset in WGS84zDhttps://zenodo.org/record/3968936/files/natural-earth-dataset.tar.gzz207 MB4326z,ODC Public Domain Dedication and License 1.0z)Brendan Harmon (brendan.harmon@gmail.com))r   r   sizeepsglicense
maintainerc                   4    e Zd Zd Zd Zd ZddZd Zd	dZy)
RedirectTextc                     || _         y N)out)selfwindows     4/usr/lib/grass83/gui/wxpython/startup/locdownload.py__init__zRedirectText.__init__X   s	        c                     	 | j                   r^| j                  |      }| j                  |      }t        j                  | j                   j
                  |       | j                  |       y y #  Y y xY wr   )r   _wrap_string_get_heigthwx	CallAfterSetLabel_resize)r   stringheigths      r   writezRedirectText.write[   sa    	xx**62))&1TXX..7V$	 
	s   A)A- -A1c                      y r    r   s    r   flushzRedirectText.flushf   s    r    c                 R    t        j                  |      }|j                  |      S )zWrap string

        :param str string: input string
        :param int width: maximum length allowed of the wrapped lines

        :return str: newline-separated string
        )widthtext)textwrapTextWrapperfill)r   r(   r0   wrappers       r   r"   zRedirectText._wrap_stringi   s%     &&U3|||((r    c                     |j                  d      }| j                  j                         }|j                  j	                         }t        |dz   |z  dz        }|S )zkGet widget new heigth

        :param str string: input string

        :return int: widget heigth
        
   g      ?)countr   GetClassDefaultAttributesfontGetPointSizeint)r   r(   n_linesattr	font_sizer)   s         r   r#   zRedirectText._get_heigtht   sS     ,,t$xx113II**,	gkY.$67r    c                    t        j                  | j                  j                         j                  d       t        j                  | j                  j                  d|f       t        j                  | j                  j                         j
                  j                  j                  | j                  j                         j
                         y)zGResize widget heigth

        :param int heigth: widget heigth
        )rC   rC   N)r$   r%   r   	GetParent
SetMinSizeparentsizerFit)r   r)   s     r   r'   zRedirectText._resize   s    
 	TXX'')44h?
TXX((2v,7
HH ''--11HH ''	
r    N)(   )rC   )	__name__
__module____qualname__r   r*   r.   r"   r#   r'   r,   r    r   r   r   W   s     		)

r    r   c           
         | dk(  r=t        j                          at        j                  j	                  t        d             y | dz  dk7  ry t        j                          t        z
  }t        | |z        }t        |d|z  z        }t        | |z  dz  |z        }t        j                  j	                  t        dj                  ||dz  ||                   y )Nr   z2Download in progress, wait until it is finished 0%d   i   z^Download in progress, wait until it is finished {0}%, {1} MB, {2} KB/s, {3:.0f} seconds passedi   )time
start_timesysstdoutr*   _r>   format)r:   
block_size
total_sizedurationprogress_sizespeedpercents          r   
reporthookr[      s    zYY[


BC	
 	s{ayy{Z'H
*+M12E%*$s*Z78GJJ	==CV-	>	

r    c                    	 t        | t              }t        j                  j	                  ||      }t        |      st        d      S t        j                  ||       t        |       y# t        $ r}|cY d}~S d}~ww xY w)zhWrapper to return DownloadError by value

    It also moves the location directory to the database.
    )sourcer[   z Downloaded location is not valid)srcdstN)r   r[   ospathjoinr
   rS   shutilcopytreer   r	   )r   namedatabase	directorydestinationerrors         r   download_locationrj      so    

 )
K	ggll8T2 +788I;7)   s$   AA, 	"A, ,	B5A<6B<Bc                 *    t        t        |             S )zCreate location name from URL)r   r   )r   s    r   location_name_from_urlrl      s    c 233r    c                   t    e Zd ZdZefdZd Z ed       ed      fdZd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zy)LocationDownloadPanela  Panel to select and initiate downloads of locations.

    Has a place to report errors to user and also any potential problems
    before the user hits the button.

    In the future, it can potentially show also some details about what
    will be downloaded. The choice widget can be also replaced.

    For the future, there can be multiple panels with different methods
    or sources, e.g. direct input of URL. These can be in separate tabs
    of one panel (perhaps sharing the common background download and
    message logic).
    c                     t         j                  j                  | |       || _        d| _        d| _        || _        || _        t        d      | _	        t        d      | _
        t        | t        d            | _        g }| j                  D ]  }|j                  |d           t        j                  | |	      | _        | j                  j!                  t         j"                  | j$                         | j                  j&                  j!                  t         j(                  | j*                         t        | d
      | _        t/        | j,                        t0        _        	 | j,                  j5                  t        j6                  ddd             | j;                          d}| j                  j=                  |       | j?                  | j                  |          tA               | _!        y# t8        $ r Y fw xY w)z

        :param database: directory with G database to download to
        :param locations: list of dictionaries with label and url
        rF   NFAbortzAbort download locationz#Select sample location to download:)rF   r   r   )rF   choices)rC   2   )rF   r      r   )"r$   Panelr   rF   _last_downloaded_location_name_download_in_progressrf   	locationsrS   _abort_btn_label_abort_btn_tooltipr   r   appendChoicechoiceBind
EVT_CHOICEOnChangeChoicedownload_button
EVT_BUTTON
OnDownloadmessager   rQ   rR   SetForegroundColourColourAttributeError_layoutSetSelection	CheckItemr   thread)r   rF   rf   rx   rr   itemdefaults          r   r   zLocationDownloadPanel.__init__   s    	$v..2+%*" " !'
"#$=">q!FG

 NN 	*DNN4=)	*iitW=(;(;<##((H
 "H=!$,,/
	LL,,RYYsAq-AB 	  )t~~g./i  		s   &0G1 1	G=<G=c                 8   t        j                  t         j                        }|| _        |j	                  | j
                  dt         j                  t         j                  z  t         j                  z  t         j                  z  d       |j	                  | j                  dt         j                  t         j                  z  t         j                  z  t         j                  z  d       |j                          |j	                  | j                  dt         j                  t         j                  z  t         j                  z  d       | j                  |       |j!                  |        | j#                          | j%                  | j'                                y)zCreate and layout sizersr   
   
proportionflagborderN)r$   BoxSizerVERTICALrG   Addr   EXPANDTOPLEFTRIGHTr}   AddStretchSpacerr   
ALIGN_LEFTALLSetSizerrH   LayoutrE   GetBestSize)r   verticals     r   r   zLocationDownloadPanel._layout  s   ;;r{{+
JJRVV#bgg-8	 	 	
 	KKRVV#bgg-8	 	 	
 	!!#LL'"))3	 	 	
 	hT((*+r    	Do&wnloadDownload selected locationc                     | j                   j                  rK| j                   j                  j                  |       | j                   j                  j                  |       yy)z$Change download button label/tooltipN)rF   r   r&   
SetToolTip)r   r   tooltips      r   _change_download_btn_labelz0LocationDownloadPanel._change_download_btn_label%  sF     ;;&&KK''007KK''227; 'r    c                    | j                   j                  j                         }|t        d      t        d      fv r| j	                  | j
                  | j                         t        j                  dd       | j                  r| j                  t        d             | j                  j                         }| j                  | j                  |          y| j                   j                          y)z(Handle user-initiated action of downloadDownloadr   )r   r      r   /Download in progress, wait until it is finishedN)rF   r   GetLabelrS   r   ry   rz   r   msgrw   _warningr}   GetSelectionDownloadItemrx   OnCancel)r   eventbutton_labelindexs       r   r   z LocationDownloadPanel.OnDownload-  s    {{22;;=AjM1[>::++++// ,  IIa&))a QRSKK,,.EdnnU34KK  "r    c                     t        j                  dd|z         |d   }t        |      t        j                  j                   j                        }t        j                  j                  |      r. j                  t        d      z          j                          y fd} fd}d _         j                  t        d	              j                  j                  t        | j                  ||
       y)zDownload the selected itemr   zDownloadItem: %sr   z5Location named <%s> already exists, download canceledNc                     d_         | j                  }|rj                  t        d      |z         n!_        j                  t        d             j                          y )NFzDownload failed: %szpDownload completed. The downloaded sample data is listed in the location/mapset tabs upon closing of this window)rw   ret_errorrS   rv   r   r   )r   errorsdirnamer   s     r   download_complete_callbackzFLocationDownloadPanel.DownloadItem.<locals>.download_complete_callbackK  s^    ).D&YYFA34v=>6=3R ++-r    c                     ddl m} d_        |j                          t        j
                  j                  d       t               _        j                          y )Nr   )requestFzDownload aborted)
urllibr   rw   
urlcleanuprQ   rR   r*   r   r   r   )r   r   r   s     r   terminate_download_callbackzGLocationDownloadPanel.DownloadItem.<locals>.terminate_download_callbackZ  sD     ').D& JJ/0!)DK++-r    Tr   )callabler   re   rf   ondoneonterminate)r   r   rl   r`   ra   rb   rf   existsr   rS   r   rw   r   r   Runrj   )r   r   r   rh   r   r   r   s   `     @r   r   z"LocationDownloadPanel.DownloadItem=  s    		!'$./5k(-ggll4==':77>>+&KKLMPWW ++-	.		. &*"aIJK&]]-3 	 	
r    c                 t    | j                   j                         }| j                  | j                  |          y)z$React to user changing the selectionN)r}   r   r   rx   )r   r   r   s      r   r   z$LocationDownloadPanel.OnChangeChoicep  s)    ((*t~~e,-r    c                 p   |d   }t        |      }t        j                  j                  | j                  |      }t        j                  j                  |      rM| j                  t        d      |z         | j                  j                  j                  t        d             y| j                          y)z4Check what user selected and report potential issuesr   z3Location named <%s> already exists, rename it firstr   )r   N)rl   r`   ra   rb   rf   r   r   rS   rF   r   r&   _clearMessage)r   r   r   r   rh   s        r   r   zLocationDownloadPanel.CheckItemu  s     5k(-ggll4==':77>>+&MMJKgU KK''00q}0E r    c                     | j                   S z8Get the name of the last location downloaded by the user)rv   r-   s    r   GetLocationz!LocationDownloadPanel.GetLocation  s    222r    c                 v    t         j                  j                  |       | j                  j	                          y)aE  Displays a warning, hint or info message to the user.

        This function can be used for all kinds of messages except for
        error messages.

        .. note::
            There is no cleaning procedure. You should call
            _clearMessage() when you know that there is everything
            correct.
        N)rQ   rR   r*   rG   r   r   r2   s     r   r   zLocationDownloadPanel._warning  s&     	



r    c                     t         j                  j                  t        d      j	                  |             | j
                  j                          y)a^  Displays a error message to the user.

        This function should be used only when something serious and unexpected
        happens, otherwise _showWarning should be used.

        .. note::
            There is no cleaning procedure. You should call
            _clearMessage() when you know that there is everything
            correct.
        zError: {text}r1   N)rQ   rR   r*   rS   rT   rG   r   r   s     r   r   zLocationDownloadPanel._error  s9     	

?+222=>

r    c                 n    | j                   j                  d       | j                  j                          y)zClears/hides the error message. N)r   r&   rG   r   r-   s    r   r   z#LocationDownloadPanel._clearMessage  s&     	b!

r    N)rJ   rK   rL   __doc__	LOCATIONSr   r   rS   r   r   r   r   r   r   r   r   r   r,   r    r   rn   rn      sV     4= 1 f,> kNA.J,K<# 1
f.
!3r    rn   c                   4    e Zd ZdZ ed      fdZd ZddZy)LocationDownloadDialogzPDialog for download of locations

    Contains the panel and Cancel button.
    zLocation Downloadc                 <   t         j                  j                  | ||       t        | t         j                        }t        | t         j
                  t        d            | _        | j                  j                  t        d             t        | |      | _
        |j                  t         j                  | j                         | j                  t         j                  | j                         t        j                  t         j                         | _        | j"                  j%                  | j                  dt         j&                         t        j(                         }|j%                  |d	t         j&                  t         j*                  z  t         j,                  z  d
       |j%                  | j                  d	t         j&                  t         j*                  z  t         j,                  z  d
       |j/                          | j"                  j%                  |d	t         j0                  t         j2                  z  t         j4                  z  d       | j7                  | j"                         | j"                  j9                  |        | j;                          y)z
        :param database: database to download the location to
        :param title: window title if the default is not appropriate
        )rF   title)idr   )rF   r   r   r   rF   rf   r   )r   r   r      r   r   N)r$   Dialogr   r   	ID_CANCELID_ANYrS   r   r   rn   panelr~   r   r   	EVT_CLOSEr   r   rG   r   r   StdDialogButtonSizerr   r   RealizeALIGN_RIGHTr   BOTTOMr   rH   r   )r   rF   rf   r   cancel_buttonbutton_sizers         r   r   zLocationDownloadDialog.__init__  s   
 			4e<t5%Tbiiq~V''*F(GH*$J
2==$--8		",,.[[-


tzzabii@..0RWW$rxx/	 	 	
 	  RWW$rxx/	 	 	
 	

"&&(2994	 	 	
 	djj!

tr    c                 6    | j                   j                         S r   )r   r   r-   s    r   r   z"LocationDownloadDialog.GetLocation  s    zz%%''r    Nc                 0   | j                   j                  rt        j                  | t	        d      t	        d      t        j
                  t        j                  z  t        j                  z  t        j                  z        }|j                         }|j                          |t        j                  k(  ry | j                   j                  j                          | j                   j                          |r | j                  t        j                          y y )Nz(Do you want to cancel location download?zAbort download)rF   r   captionstyle)r   rw   r$   MessageDialogrS   YES_NO
NO_DEFAULTICON_QUESTIONCENTRE	ShowModalDestroyID_NOr   	Terminater   EndModalr   )r   r   dlgr   s       r   r   zLocationDownloadDialog.OnCancel  s    ::++""DE*+ii"--/"2B2BBRYYN	C --/CKKMbhh

!!++-

557MM",,' r    r   )rJ   rK   rL   r   rS   r   r   r   r,   r    r   r   r     s"    
 011D/E (T((r    r   c                     t        t        j                        dk  rt        j                  d       t        j                  d   } t	        j
                         }t        t        j                        dk(  st        j                  d   dk(  rKt        d|       }|j                          |j                         }|rt        |       |j                          nt        j                  d   dk(  rat	        j                  d      }t        ||       }|j                          |j                         }|rt        |       |j                          nt        d	       |j                          y)
zTests the download dialogr9   zProvide a test directoryr   dialogNr   r   rp   z%Unknown settings: try dialog or panel)lenrQ   argvexitr$   Appr   r   r   printr   r   rn   MainLoop)rf   appr   locationr   s        r   mainr     s    
388}q+,xx{H
&&(C
388}SXXa[H4'thG%%'(O	!	$'%VhG$$&(O56LLNr    __main__)+r   
__future__r   r`   rQ   rc   r3   rO   r$   wx.lib.neweventr   grass.script.utilsr   r   grass.utils.downloadr   r   r	   grass.grassdb.checksr
   grass.script.setupr   
core.debugr   core.gthreadr   gui_core.wrapr   r   r   objectr   r[   rj   rl   DownloadDoneEventEVT_DOWNLOAD_DONEru   rn   r   r   r   rJ   r,   r    r   <module>r     s6  $ & 	 
    	 $ > S S 2 +     , (Z
 %]
 3H
 +T
 ,a
 <L
 /J
 7K
 2UAAC)	X4
6 4
p6&4
 (0z $ $dBHH dNH(RYY H(V: zF r    