
    ը	fb                     n   d Z ddlZddlZddlmZmZmZmZmZm	Z	m
Z
mZmZmZmZmZ ddlmc mZ ddlmZmZ ddlmZmZmZmZmZ ddlmZ ddlm Z  ddl!m"Z" dd	l#m$Z$m%Z%m&Z& dd
l'm(Z( ddl)m*Z* ddl+m,Z,  G d de(      Z- G d de(      Z.d Z/d Z0d Z1d Z2d Z3d Z4d Z5d Z6d Z7d Z8d Z9d Z:d Z;	 ddZ<y) a  
@package startup.guiutils

@brief General GUI-dependent utilities for GUI startup of GRASS GIS

(C) 2018 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>
@author Linda Kladivova <l.kladivova@seznam.cz>

This is for code which depend on something from GUI (wx or wxGUI).
    N)is_mapset_lockedget_mapset_lock_infois_mapset_name_validis_location_name_validget_mapset_name_invalid_reason get_location_name_invalid_reasonget_reason_mapset_not_removable!get_reasons_mapsets_not_removable"get_reasons_location_not_removable#get_reasons_locations_not_removable!get_reasons_grassdb_not_removableis_fallback_session)create_mapsetget_default_mapset_name)delete_mapsetdelete_locationdelete_grassdbrename_mapsetrename_location)create_environment)
try_remove)gisenv)GErrorGMessage
RunCommand)TextEntryDialog)	RegionDef)GenericValidatorc                   ,    e Zd Z	 	 	 	 	 	 ddZd Zd Zy)MapsetDialogNc                     || _         || _        t        | j                  | j                        }t        j                  | |||||       y N)parentmessagecaptiondefaultValue	validator)databaselocationr   _isMapsetNameValid_showMapsetNameInvalidReasonr   __init__)selfr#   defaultr$   r%   r(   r)   r'   s           1/usr/lib/grass83/gui/wxpython/startup/guiutils.pyr,   zMapsetDialog.__init__8   sO     ! $##T%F%F
	 	   	
    c                     t        | j                  | j                  |j                               }t	        | |t        d             y )NzInvalid mapset namer#   r$   r%   )r   r(   r)   GetValuer   _r-   ctrlr$   s      r/   r+   z)MapsetDialog._showMapsetNameInvalidReasonQ   s5    0MM4==$--/
 	dGQ7L5MNr0   c                 D    t        | j                  | j                  |      S z4Check whether user's input location is valid or not.)r   r(   r)   r-   texts     r/   r*   zMapsetDialog._isMapsetNameValidW   s    #DMM4==$GGr0   )NNNNNN)__name__
__module____qualname__r,   r+   r*    r0   r/   r    r    7   s'     
2OHr0   r    c                   "    e Zd Z	 ddZd Zd Zy)LocationDialogNc                     || _         t        | j                  | j                        }t	        j
                  | |||||       y r"   )r(   r   _isLocationNameValid_showLocationNameInvalidReasonr   r,   )r-   r#   r.   r$   r%   r(   r'   s          r/   r,   zLocationDialog.__init__]   sH     !$%%t'J'J
	 	   	
r0   c                 z    t        | j                  |j                               }t        | |t	        d             y )NzInvalid location namer2   )r   r(   r3   r   r4   r5   s      r/   rC   z-LocationDialog._showLocationNameInvalidReasono   s*    24==$--/RdGQ7N5OPr0   c                 .    t        | j                  |      S r8   )r   r(   r9   s     r/   rB   z#LocationDialog._isLocationNameValids   s    %dmmT::r0   )NNNNN)r;   r<   r=   r,   rC   rB   r>   r0   r/   r@   r@   \   s    NR
$Q;r0   r@   c                 V    t        | ||      \  }}t        dd|       t        |       y)z'Initialize mapset (database connection)
db.connectcflagsenvN)r   r   r   )grassdbr)   mapset
gisrc_filerK   s        r/   initialize_mapsetrO   x   s(    ((FCOJ|3C0zr0   c                    t        | t               t        d      t        d      ||      }d}|j                         t        j
                  k(  r+|j                         }	 t        |||       t        |||       |j                          |S # t        $ r2}d}t        | t        d      j                  |      d       Y d}~Hd}~ww xY w)z
    Create new mapset
    zName for the new mapset:zCreate new mapsetr#   r.   r$   r%   r(   r)   NzUnable to create new mapset: {}F)r#   r$   showTraceback)r    r   r4   	ShowModalwxID_OKr3   r   rO   OSErrorr   formatDestroy)	guiparentrL   r)   dlgrM   errs         r/   create_mapset_interactivelyr\      s     '),-%&C F
}}"(("		'8V4gx8 KKMM  	F ;<CCCH# 	s    B 	C(CCc                    ddl m}  || |      }|j                  d}|S |j                  rt	        d      j                  |j                        }t        j                  | |t	        d      t        j                  t        j                  z  t        j                  z        }|j                          |j                         t        j                  k(  rFt        |j                  |j                  d      \  }}t!        | |j                  |       t#        |       |j%                          |j&                  rGt)        | |j                  	      }	|	j                          |	j                          |	j%                          |j*                  r<t-        | |j                  |j                        }
|j                  |j                  |
f}|S |j                  |j                  df}|S )
z
    Create new location using Location Wizard.

    Returns tuple (database, location, mapset) where mapset is "PERMANENT"
    by default or another mapset a user created and may want to switch to.
    r   )LocationWizard)r#   grassdatabaseNNNz7Do you want to import {} to the newly created location?zImport data?r#   r$   r%   style	PERMANENT)r)   )location_wizard.wizardr^   r)   
georeffiler4   rW   rT   MessageDialogYES_NOYES_DEFAULTICON_QUESTIONCenterOnParentrS   ID_YESr   r_   import_filer   rX   default_regionr   user_mapsetr\   )rY   rL   r^   gWizardgWizard_outputr$   rZ   rN   rK   defineRegionrM   s              r/   create_location_interactivelyrr      s    6IWEG+H

&##
$ 	 n%))bnn,r/?/??	
 	==?bii'0%%w'7'7OJ 	7#5#5s;z" W5E5EF##% ,w,,g.>.>

 "//1A1A6J  "//1A1A;Or0   c                 .   d}t        |||d      }|r}t        j                  | t        d      j	                  ||      t        d      t        j
                  t        j                  z        }|j                          |j                          |S t        | |t        d      j	                  |      t        d	      ||
      }|j                         t        j                  k(  r|j                         }	 t        ||||       |j                          |S # t        $ rv}d}t        j                  | t        d      t        d      j	                  |      t        j
                  t        j                  z  t        j                   z         Y d}~d}~ww xY w)aH  Rename mapset with user interaction.

    Exceptions during renaming are handled in get_reason_mapset_not_removable
    function.

    Returns newmapset if there was a change or None if the mapset cannot be
    renamed (see reasons given by get_reason_mapset_not_removable
    function) or if another error was encountered.
    NTcheck_permanentz_Cannot rename mapset <{mapset}> for the following reason:

{reason}

No mapset will be renamed.)rM   reasonz Unable to rename selected mapsetra   !Current name: {}

Enter new name:zRename selected mapsetrQ   ErrorzUnable to rename mapset.

{}r#   r%   r$   rb   )r	   rT   rf   r4   rW   OKICON_WARNINGrS   rX   r    rU   r3   r   rV   
MessageBox
ICON_ERRORCENTRE)rY   rL   r)   rM   	newmapsetr$   rZ   r[   s           r/   rename_mapset_interactivelyr      s]    I .64G - fF7f389%%"//)	
 	 78??G*+C }}"(("LLN			'8VY? KKM  	IMM '
:;BB3Geebmm+bii7	 	s   5D 	FA,FFc           	      B   d}t        ||      }|rt        j                  | t        d      j	                  |dj                  |            t        d      t        j                  t        j                  z        }|j                          |j                          |S t        | |t        d      j	                  |      t        d      |	      }|j                         t        j                  k(  r|j                         }	 t        |||       |j                          |S # t        $ rv}d}t        j                  | t        d
      t        d      j	                  |      t        j                  t        j                   z  t        j"                  z         Y d}~d}~ww xY w)aT  Rename location with user interaction.

    Exceptions during renaming are handled in get_reasons_location_not_removable
    function.

    Returns newlocation if there was a change or None if the location cannot be
    renamed (see reasons given by get_reasons_location_not_removable
    function) or if another error was encountered.
    NzgCannot rename location <{location}> for the following reasons:

{reasons}

No location will be renamed.
)r)   reasonsz"Unable to rename selected locationra   rw   zRename selected location)r#   r.   r$   r%   r(   rx   zUnable to rename location.

{}ry   )r   rT   rf   r4   rW   joinrz   r{   rS   rX   r@   rU   r3   r   rV   r|   r}   r~   )rY   rL   r)   newlocationmessagesrZ   r[   s          r/   rename_location_interactivelyr     sX    K 2'8DH/ fh		(0CfD:;%%"//)	
 	 78??I,-C }}"(("lln		GX{; KKM  	KMM '
<=DDSIeebmm+bii7	 	s    D 	F(A,FFc                     ddl m} d} || |      }|j                          |j                          |j	                         ||j	                         df}|j                          |S )z
    Download new location using Location Wizard.

    Returns tuple (database, location, mapset) where mapset is "PERMANENT"
    by default or in future it could be the mapset the user may want to
    switch to.
    r   )LocationDownloadDialogr`   )r#   r(   rc   )startup.locdownloadr   CentrerS   GetLocationrX   )rY   rL   r   resultloc_downloads        r/   download_location_interactivelyr   @  sg     ;F)WML!- <335{CMr0   c                 &    |||fg}t        | |      S )zDelete one mapset with user interaction.

    This is currently just a convenience wrapper for delete_mapsets_interactively().
    )delete_mapsets_interactively)rY   rL   r)   rM   mapsetss        r/   delete_mapset_interactivelyr   W  s     
 6*+G'	7;;r0   c                    g }d}t        |d      }|rt        j                  | t        d      j	                  dj                  |            t        d      t        j                  t        j                  z        }|j                          |j                          |S |D ]8  \  }}}t        j                  j                  |||      }	|j                  |	       : t        j                  | t        d	      j	                  dj                  |      
      t        d      t        j                  t        j                  z  t        j                  z        }|j                         t        j                   k(  r-	 |D ]  \  }}}t#        |||       d} |j                          |S |j                          |S # t$        $ r}
t        j&                  | t        d      t        d      j	                  t        j                  j                        |
      t        j                  t        j(                  z  t        j*                  z         Y d}
~
d}
~
ww xY w)a,  Delete multiple mapsets with user interaction.

    Parameter *mapsets* is a list of tuples (database, location, mapset).

    Exceptions during deletation are handled in get_reasons_mapsets_not_removable
    function.

    Returns True if there was a change, i.e., all mapsets were successfully
    deleted or at least one mapset was deleted.
    Returns False if one or more mapsets cannot be deleted (see reasons given
    by get_reasons_mapsets_not_removable function) or if an error was
    encountered when deleting the first mapset in the list.
    FTrt   zdCannot delete one or more mapsets for the following reasons:

{reasons}

No mapsets will be deleted.r   r   z!Unable to delete selected mapsetsra   zDo you want to continue with deleting one or more of the following mapsets?

{deletes}

All maps included in these mapsets will be permanently deleted!deleteszDelete selected mapsetszError when deleting mapsetszjThe following error occurred when deleting mapset <{path}>:

{error}

Deleting of mapsets was interrupted.patherrorry   N)r
   rT   rf   r4   rW   r   rz   r{   rS   rX   osr   appendrg   
NO_DEFAULTri   rk   r   rV   r|   r}   r~   )rY   r   r   modifiedr   rZ   rL   r)   rM   mapset_pathr   s              r/   r   r   `  s    GH 1$OH. fTYYx0f19:%%"//)	
 	 &- $!6ggll7Hf={#$
 

N

 &7+&
,+,ii"--'"*:*::
C }}"))#	-4  )6gx8  KKMO KKMO  	MM 78; &gx@   eebmm+bii7 	s   8+F6 6	I?BIIc                 $    ||fg}t        | |      S )zDelete one location with user interaction.

    This is currently just a convenience wrapper for delete_locations_interactively().
    )delete_locations_interactively)rY   rL   r)   	locationss       r/   delete_location_interactivelyr     s    
 8$%I))Y??r0   c                    g }d}t        |      }|rt        j                  | t        d      j	                  dj                  |            t        d      t        j                  t        j                  z        }|j                          |j                          |S |D ]6  \  }}t        j                  j                  ||      }|j                  |       8 t        j                  | t        d      j	                  dj                  |            t        d	      t        j                  t        j                  z  t        j                  z        }|j                         t        j                   k(  r+	 |D ]  \  }}t#        ||       d
} |j                          |S |j                          |S # t$        $ r}	t        j&                  | t        d      t        d      j	                  t        j                  j                        |	      t        j                  t        j(                  z  t        j*                  z         Y d}	~	d}	~	ww xY w)a4  Delete multiple locations with user interaction.

    Parameter *locations* is a list of tuples (database, location).

    Exceptions during deletation are handled in get_reasons_locations_not_removable
    function.

    Returns True if there was a change, i.e., all locations were successfully
    deleted or at least one location was deleted.
    Returns False if one or more locations cannot be deleted (see reasons given
    by get_reasons_locations_not_removable function) or if an error was
    encountered when deleting the first location in the list.
    FzhCannot delete one or more locations for the following reasons:

{reasons}

No locations will be deleted.r   r   z#Unable to delete selected locationsra   zDo you want to continue with deleting one or more of the following locations?

{deletes}

All mapsets included in these locations will be permanently deleted!r   zDelete selected locationsTzError when deleting locationsznThe following error occurred when deleting location <{path}>:

{error}

Deleting of locations was interrupted.r   ry   N)r   rT   rf   r4   rW   r   rz   r{   rS   rX   r   r   r   rg   r   ri   rk   r   rV   r|   r}   r~   )
rY   r   r   r   r   rZ   rL   r)   location_pathr   s
             r/   r   r     s    GH 39=H0 fTYYx0f1;<%%"//)	
 	 ' &Wh7}%&
 

S

 &7+&
,-.ii"--'"*:*::
C }}"))#	%.  !2  KKMO KKMO  	MM 9:= &gx8   eebmm+bii7 	s   4)F0 0	I9B
IIc           	         d}t        |      }|rzt        j                  | t        d      j	                  dj                  |            t        d      t        j                  t        j                  z        }|j                          nt        j                  | t        d      j	                  |      t        d	      t        j                  t        j                  z  t        j                  z        }|j                         t        j                  k(  r 	 t        |       d
}|j                          |S |j                          |S # t        $ rv}t        j                   | t        d      t        d      j	                  ||      t        j                  t        j"                  z  t        j$                  z         Y d}~d}~ww xY w)aE  
    Delete grass database if could be deleted.

    If current grass database found, desired operation cannot be performed.

    Exceptions during deleting are handled in this function.

    Returns True if grass database is deleted from the disk. Returns None if
    cannot be deleted (see above the possible reasons).
    FzpCannot delete GRASS database from disk for the following reason:

{reasons}

GRASS database will not be deleted.r   r   z(Unable to delete selected GRASS databasera   ztDo you want to delete the following GRASS database from disk?

{grassdb}

The directory will be permanently deleted!)rL   zDelete selected GRASS databaseTz"Error when deleting GRASS databasezsThe following error occurred when deleting database <{path}>:

{error}

Deleting of GRASS database was interrupted.r   ry   N)r   rT   rf   r4   rW   r   rz   r{   rS   rg   r   ri   rk   r   rX   rV   r|   r}   r~   )rY   rL   deletedr   rZ   r   s         r/   delete_grassdb_interactivelyr     sx    G 19H6 fTYYx0f1@A%%"//)	
 	=
 fWf%67))bmm+b.>.>>

 ==?bii'w' KKMN  $BCF f$#   %%"--/")); s   E 	GA,GGc           	      R   d}t         j                  j                  |||      }t        |      rt	        |      }|d   r|d   n
t        d      }|d   }|d   }	t        j                  | t        d      j                  ||||	      t        d      t        j                  t        j                  z  t        j                  z  	      }
|
j                  d
d       |
j                         t        j                  k(  r	 t        j                  |       nd}|
j+                          |S # t         $ rx}t        j"                  | t        d      t        d      j                  ||      t        j$                  t        j&                  z  t        j(                  z         d}Y d}~d}~ww xY w)a  
    Checks if mapset is locked and offers to remove the lock file.

    Returns True if user wants to switch to the selected mapset in spite of
    removing lock. Returns False if a user wants to stay in the current
    mapset or if an error was encountered.
    Townerunknownlockpath	timestampzUser {user} is already running GRASS in selected mapset <{mapset}>
 (file {lockpath} created {timestamp} found).

Concurrent use not allowed.

Do you want to stay in the current mapset or remove .gislock and switch to selected mapset?)userrM   r   r   zMapset is in usera   zS&witch to selected mapsetzS&tay in current mapsetzError when removing lock filez0Unable to remove {lockpath}.

 Details: {error}.)r   r   ry   FN)r   r   r   r   r   r4   rT   rf   rW   rg   r   ri   SetYesNoLabelsrS   rk   removeIOErrorr|   rz   r}   r~   rX   )rY   rL   r)   rM   
can_switchr   infor   r   r   rZ   es               r/   can_switch_mapset_interactiver   A  sb    J'',,w&9K$#K0 $WtG}1Y<
#%	: f$vIfV()))bmm+b.>.>>
 	79RS==?bii'#		(# J  	#$=>Lfhaf8%%"--/")); #
	#s   ;D% %	F&.A.F!!F&c                 n   t        dd|       t        j                  j                  t        j                  j	                  |            d   }t        d|dd|      }t        j                          t        j                         j                          |r(t        d||d|	      \  }}|dk(  r7t        d
d||       n't        d||d|	      \  }}|dk(  rt        d
d||       t        j                          |dk7  rt        | t        d      ||dz         yt        t        d      d|iz  |        y)zhTries to import file as vector or raster.

    If successful sets default region from imported map.
    rG   rH   rI   r   zv.in.ogrlT)inputrJ   readrK   )r   outputgetErrorMsgrK   zg.regions)rJ   vectorrK   z	r.in.gdal)rJ   rasterrK   z,Import of <%(name)s> failed.
Reason: %(msg)s)namemsgr#   r$   ziData file <%(name)s> imported successfully. The location's default region was set from this imported map.r   )r$   r#   N)r   r   r   splitextbasenamerT   BeginBusyCursorGetAppYieldEndBusyCursorr   r4   r   )rY   filePathrK   mapNamevectors
returncoder   s          r/   rl   rl   t  s,   
 |3C0ggrww//9:1=G83TsSGIIK&hwDc

E ?zW#F&xTs

E ?zW#FQHI /1	
 	%
 x ! 	
r0   c                    t               }|rQt        d| |||      dk(  r|rt        | t        d      |||dz         |j                  j                  |||       n|rOt        d| ||      dk(  r|rt        | t        d	      ||d
z         |j                  j                  d||       nJt        d| |      dk(  r9|rt        | t        d      |z         |j                  j                  dd|       |r`t        j                  d   }t        j                  }|t               d   k7  r,t        ||       |j                  j                  ||dd       yyy)z@Switch current mapset. Emits giface.currentMapsetChanged signal.zg.mapset)r#   r)   rM   dbaser   zeCurrent GRASS database is <%(dbase)s>.
Current location is <%(loc)s>.
Current mapset is <%(mapset)s>.)r   locrM   r   )r   r)   rM   )r#   r)   rM   z>Current location is <%(loc)s>.
Current mapset is <%(mapset)s>.)r   rM   N)r#   rM   zCurrent mapset is <%s>.TMPDIRGISDBASEdeleterL   )r)   rL   actionelement)r   r   r   r4   currentMapsetChangedemitr   environcfgtemporary_locationr   r   grassdbChanged)	rY   gifacer   r)   rM   show_confirmationfallback_session	tmp_dbasetmp_locs	            r/   switch_mapset_interactivelyr     s   
 +, !  !$:
 !&h&IJ '',,hv -  
z)hvV !$: '&9	: '',,Xf -  j6BaG $a0I.JV.S '',,4$v,VJJx(	((,,Iw/!!&&!9Xy ' 	 - r0   )F)=__doc__r   rT   grass.grassdb.checksr   r   r   r   r   r   r	   r
   r   r   r   r   grass.grassdb.configrL   configr   grass.grassdb.creater   r   grass.grassdb.manager   r   r   r   r   grass.script.corer   grass.script.utilsr   grass.scriptr   	core.gcmdr   r   r   gui_core.dialogsr   location_wizard.dialogsr   gui_core.widgetsr   r    r@   rO   r\   rr   r   r   r   r   r   r   r   r   r   rl   r   r>   r0   r/   <module>r      s   " 
 	    # " G  1 )  2 2 , - -"H? "HJ;_ ;8<3l5p2j.<IX@IX=@0f)
Z CHAr0   