
    ը	fHb                         d 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	 ddlm
Z ddlmZmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ  e       \  ZZ G d dej8                        Zy)aX  
@package rdigit.controller

@brief rdigit controller for drawing and rasterizing

Classes:
 - controller::RDigitController

(C) 2014 by 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 Anna Petrasova <kratochanna gmail.com>
    N)NewEvent)coreraster)CalledModuleErrorScriptError)Signal)GErrorGMessage)UserSettings)gThread)NewRasterDialogc                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd ZddZd Zd Zd Z	 	 	 	 ddZd Zd Zd Zd Zd Zd Zd Zy)RDigitControllerzsController object for raster digitizer.
    Inherits from EvtHandler to be able to send wx events from thraed.
    c                 z   t         j                  j                  |        || _        || _        t               | _        d| _        d| _        d| _	        d| _
        d| _        d| _        d| _        d| _        g | _        d| _        d| _        t         j$                  | _        d| _        d| _        d| _        d| _        t0        j2                  j5                         | _        d| _        d| _        t=        d      | _        t=        d      | _         t=        d      | _!        t=        d      | _"        t=        d	      | _#        y)
zConstructs controller

        :param giface: grass interface object
        :param mapWindow: instance of BufferedMapWindow
        NFd   areaz!RDigitController:newRasterCreatedz"RDigitController:newFeatureCreatedz$RDigitController:uploadMapCategorieszRDigitController:quitDigitizerz!RDigitController:showNotification)$wx
EvtHandler__init___giface
_mapWindowr   _thread_editedRaster_backgroundRaster_backupRasterName_editOldRaster_mapType_areas_lines_points_all_drawing_runningGREEN
_drawColor_drawTransparency_graphicsType_currentCellValue_currentWidthValueosenvironcopy_env_oldMouseUse
_oldCursorr	   newRasterCreatednewFeatureCreateduploadMapCategoriesquitDigitizershowNotification)selfgiface	mapWindows      2/usr/lib/grass83/gui/wxpython/rdigit/controller.pyr   zRDigitController.__init__(   s    	t$# y!!%!% $	((!$#!%"&JJOO%	  !''J K!'(L!M $**P#Q #$DE &'J K    c                 p   | j                   j                  j                  | j                         | j                   j                  j                  | j
                         | j                   j                  j                  | j                         | j                   j                  t        j                         y N)r   mouseLeftDownconnect_startmouseLeftUp	_addPointmouseRightUp_finishUnbindr   EVT_CONTEXT_MENUr6   s    r9   _connectAllzRDigitController._connectAllc   sn    %%--dkk:##++DNN;$$,,T\\:r223r:   c                    | j                   j                  j                  | j                         | j                   j                  j                  | j
                         | j                   j                  j                  | j                         | j                   j                  t        j                  | j                   j                         y r<   )r   r=   
disconnectr?   r@   rA   rB   rC   Bindr   rE   OnContextMenurF   s    r9   _disconnectAllzRDigitController._disconnectAlli   sz    %%00=##..t~~>$$//=R00$//2O2OPr:   c                    | j                   ry| j                  s!t        | j                  t	        d             y| j
                  s| j                  dk(  rJ| j                  j                  g       }|j                  dd       | j                  j                  |       n| j                  dk(  rJ| j                  j                  g       }|j                  dd       | j                  j                  |       nX| j                  d	k(  rI| j                  j                  g       }|j                  dd       | j                  j                  |       d
| _        yy)zStart digitizing a new object.
        :param x: x coordinate in map units
        :param y: y coordinate in map units
        Nz"Please select first the raster mapparentmessager   )coordspenNamepen1linepointT)r$   r   r   r   _r#   r(   r   AddItemSetPropertyValr"   appendr    r!   )r6   xyitems       r9   r?   zRDigitController._starto   s   
 ==!!2V0W }}!!V+{{**"*5##Iv6		  &##v-{{**"*5##Iv6		  &##w.||++2+6##Iv6		  & DM r:   c                    | j                   ry| j                  sy| j                  dk(  rh| j                  j	                  d      }|j                         ||ggz   }|j                  |       | j                  j                  t        d             n| j                  dk(  rh| j                  j	                  d      }|j                         ||ggz   }|j                  |       | j                  j                  t        d             nM| j                  dk(  r>| j                  j	                  d      }|j                  ||g       | j                          | j                  j                          | j                  j                          | j                  j                          | j                  j                          | j                  j!                          y)	zxAdd point to an object.
        :param x: x coordinate in map units
        :param y: y coordinate in map units
        Nr   zRight click to finish area)textrT   zRight click to finish linerU   )r$   r#   r(   r   GetItem	GetCoords	SetCoordsr5   emitrV   r    r!   rC   r   
ClearLinesDrawRefresh)r6   rZ   r[   r   rQ   rT   rU   s          r9   rA   zRDigitController._addPoint   sg   
 ==}}';;&&r*D^^%!Q0FNN6"!!&&A.J,K&L6);;&&r*D^^%!Q0FNN6"!!&&A.J,K&L7*LL((,EOOQF#LLN""$!r:   c                 @   | j                   ry| j                  dk(  r| j                  j                  d      }nW| j                  dk(  r| j                  j                  d      }n,| j                  dk(  r| j
                  j                  d      }nyd| _        |j                  dd       |j                  d	       |j                  d
       |j                  d	| j                         |j                  d
| j                         | j                  j                          | j                  j                          | j                  j                          | j                  j                          | j
                  j                          | j                  j!                          y)zFinish digitizing a new object and redraws.
        Saves current cell value and buffer width for that object.

        :param x: x coordinate in map units
        :param y: y coordinate in map units
        NrU   r^   r   rT   F	brushNamedone	cellValue
widthValue)r$   r(   r!   r`   r   r    r#   rX   AddPropertyr)   r*   r2   rc   r   rd   re   rf   )r6   r\   s     r9   rC   zRDigitController._finish   s8    ==(<<''+D6);;&&r*D6);;&&r*DK0%&K)?)?@L$*A*AB##%""$!r:   c                 `   | j                   r-|r+| j                   |k7  r| j                  r| j                          | j                   r|s| j                  j	                  | j                  j
                         | j                  j                  d   | j                  j                  d<   | j                          | j                  j                  | j                         | j                  | j                  j                  d<   || _         y| j                   |r| j                          d| j                  j                  d<   d| j                  j                  d<   t        j                  dd	t        j                  
      | j                  _        | j                  j                  d       || _         y)zSelects method (area/line/point) for drawing.
        Connects and disconnects signal to allow other tools
        in map toolbar to work.
        pdcbeginenduseNrT   boxred   colourwidthstylepencil)r(   r#   rC   r   rd   pdcTmpmouserL   SetNamedCursorr0   r/   rG   r   Pen
SHORT_DASHpen)r6   drawingTypes     r9   
SelectTypezRDigitController.SelectType   s@    ""k1 LLNkOO&&4??+A+A&B+/??+@+@+IDOO!!%(!OO**4??;+/+<+<DOO!!%( ) 'K ,0DOO!!%(+1DOO!!%("$&&Qbmm"TDOOOO**84(r:   c                     || _         y r<   )r)   r6   values     r9   SetCellValuezRDigitController.SetCellValue   s
    !&r:   c                     || _         y r<   )r*   r   s     r9   SetWidthValuezRDigitController.SetWidthValue   s
    "'r:   c                 d   |d d | j                   fz   | _        | j                  | j                  | j                  fD ]V  }|j                  d      j                  | j                         |j                  d      j                  | j                         X | j                  j                  d       y )N   rS   ri   Frender)
r'   r&   r   r    r!   GetPen	SetColourGetBrushr   	UpdateMap)r6   coloreachs      r9   ChangeDrawColorz RDigitController.ChangeDrawColor   s    )t'='=&??[[$++t||< 	=DKK))$//:MM&!++DOO<	= 	!!!/r:   c                     | j                   j                  d   | _        | j                   j                         | _        | j                          d| j                   j                  d<   d| j                   j                  d<   t        j                  ddt        j                        | j                   _	        | j                  dd | j                  fz   }| j                   j                  d	| j                   j                  d
      | _        | j                  j                  dt        j                  |dt        j                                | j                  j#                  dt        j$                  |t        j                                | j                   j                  d| j                   j                  d
      | _        | j&                  j                  dt        j                  |dt        j                                | j&                  j#                  dt        j$                  |t        j                                | j                   j                  d| j                   j                  d
      | _        | j(                  j                  dt        j                  |dt        j                                | j(                  j#                  dt        j$                  |t        j                                | j                   j+                  d       y)zRRegisters graphics to map window,
        connect required mouse signals.
        rr   NrT   rs   rt   ru   rv   r   polygonT)graphicsTypero   	mapCoordsrS   ri   )rw   ry   rU   rz   )r   r|   r/   GetNamedCursorr0   rG   r   r~   r   r   r&   r'   RegisterGraphicsToDrawpdcTransparentr   AddPenSOLIDAddBrushBrushr    r!   r}   )r6   r   s     r9   StartzRDigitController.Start   s    !OO11%8//88: (,e$'-e$ ffE"--P#t'='=&??oo<<"(F(FRV = 
 	6266arxx#PQVRXXU"((%KLoo<<T__%C%Ct = 
 	6266arxx#PQVRXXU"((%KL== doo&D&DPT > 
 	FBFF%q$QRfbhhe288&LM 	&&x0r:   c                      j                   rt        j                   j                  t	        d      t	        d      t        j
                        }|j                         t        j                  k(  rG j                  r j                           j                  j                   j                   fd       y j                  j                          y j                  j                          y)z-Before stopping digitizer, asks to save editszDo you want to save changes?zSave raster map changesc                 $    j                         S r<   )_updateAndQuiteventr6   s    r9   <lambda>z'RDigitController.Stop.<locals>.<lambda>.  s    )<)<)> r:   callableondoneN)r   r   MessageDialogr   rV   YES_NO	ShowModalID_YESr#   rC   r   Run_exportRasterr4   rc   )r6   dlgs   ` r9   StopzRDigitController.Stop   s    ""01+,			C }}"))+==LLN  !//> ! 
 ""'')##%r:   c                       j                   r j                           j                  j                   j                   fd       y)z#Saves current edits to a raster mapc                 $    j                         S r<   )_updater   s    r9   r   z'RDigitController.Save.<locals>.<lambda>;  s    dlln r:   r   N)r#   rC   r   r   r   rF   s   `r9   SavezRDigitController.Save5  s6    ==LLN''0L 	 	
r:   c                 N   t        | j                        r| j                  j                  d      }| j                  j	                  |       | j
                  j	                  |       | j                  j	                  |       d| _        | j                  j                  d       yy)z:Undo a change, goes object back (finished or not finished)r^   Fr   N)
lenr"   popr   
DeleteItemr    r!   r#   r   r   )r6   removeds     r9   UndozRDigitController.Undo>  sx    tyy>iimmB'G KK""7+KK""7+LL##G,!DMOO%%U%3 r:   c                 *   	 | j                   r$t        j                  ddd| j                   d       | j                  j                  | j                  j                         | j                  j                  d   | j                  j                  d<   | j                  r| j                          | j                  j                  | j                         | j                  j                  | j                         | j                  j                  | j                         | j                  j                  d	
       |rI| j                  j                  | j                          | j"                  | j                  j                  d<   yy# t        $ r Y _w xY w)zlCleans up drawing, temporary maps.
        :param restore: if restore previous cursor, mouse['use']
        g.remover   fTtypeflagsnamequietrn   rp   rq   Fr   rr   N)r   gcorerun_commandr   r   rd   r{   r|   r(   rL   UnregisterGraphicsToDrawr   r    r!   r   r}   r0   r/   )r6   restores     r9   CleanUpzRDigitController.CleanUpJ  s1   
	%%!!!// 	""t'='=">'+'<'<W'Ee$!00=00=00>!!!/ OO**4??;+/+<+<DOO!!%(	  ! 		s   0F 	FFc                 ~    d| _         | j                  j                  d       | j                  j	                          y)zECalled when thread is done. Updates map and calls to quits digitizer.FTr   N)r$   r   r   r4   rc   rF   s    r9   r   zRDigitController._updateAndQuitl  s0    !!!.!r:   c                 J    d| _         | j                  j                  d       y)z(Called when thread is done. Updates map.FTr   N)r$   r   r   rF   s    r9   r   zRDigitController._updater  s    !!!.r:   c                     	 | j                  |       || _        t        j                  |      d   | _        d| _	        y# t        $ r# t        | j                  t	        d             Y yw xY w)z>After selecting old raster, creates a backup copy for editing.z2Failed to create backup copy of edited raster map.rN   F)mapdatatypeT)
_backupRasterr   r
   r   rV   r   grastraster_infor   r   )r6   r   s     r9   SelectOldMapzRDigitController.SelectOldMapw  so    	t$ "))d3J?"  	NO 	s   A   )A,+A,Nc                    |r	 | j                  |||       yt        | j                        }|j                          |j                         t        j                  k(  rQ	 | j                  |j                         |j                         |j                                	 |j                          y|j                          y# t        $ r# t        | j                  t	        d             Y yw xY w# t        $ r3 t        | j                  t	        d             Y |j                          yw xY w# |j                          w xY w)a  After selecting new raster, shows dialog to choose name,
        background map and type of the new map.

        :params standalone, mapName, bgMap, mapType: if digitizer is
        launched as standalone module

        :param bool standalone: if digitizer is launched as standalone
        module
        :param str mapName: edited raster map name
        :param str bgMap: background raster map name
        :param str mapType: raster map type CELL, FCELL, DCELL
        )mapNamebackgroundMapmapTypez Failed to create new raster map.rN   FT)rO   )_createNewMapr   r
   r   rV   r   CenterOnParentr   r   ID_OK
GetMapNameGetBackgroundMapName
GetMapTypeDestroy)r6   
standaloner   bgMapr   r   s         r9   SelectNewMapzRDigitController.SelectNewMap  s   & ""#"'# #  !9C }}"((*"&& # 0&)&>&>&@ # 0 '  KKM9  ??@A " # !# !"D E !KKM! KKMs5   C !>C1 )C.-C.1)D-D0 ,D--D0 0Ec           	      ^   |j                  d      d   }|j                  d      d   }dddd}|r|}nd}	 t        j                  dj                  |||   |	      d
d
       |r|| _        t        j                  d|| j                  d
       |dk(  rTt        j                  dd|d
      j                         }|r+| j                  j                  |j                  d             | j                  |       |dz   t        j                         d   z   }|| _        || _        | j"                  j                  |       t        j                         }	| j$                  j&                  j                  |	d   |	d   |	d   d|j                  d      d   d       y# t        $ r t        w xY w)z@Creates a new raster map based on specified background and type.@r   intfloatdouble)CELLFCELLDCELLznull()z{name} = {mtype}({back}))r   mtypebackT)exp	overwriter   r.colorsr   r   r   r   z
r.describe1n)r   r   r   
)valuesMAPSET)r   GISDBASELOCATION_NAMEnewr   )grassdblocationmapsetactionr   elementN)splitr   mapcalcformatr   r   r   read_commandstripr3   rc   r   r   r   gisenvr   r   r1   r   grassdbChanged)
r6   r   r   r   r   
backgroundtypesr   r   r   s
             r9   r   zRDigitController._createNewMap  s   }}S!!$"((-a0
8DDD	MM.55U7^$ 6   )6&!!D1G1Gt f$"//$Dd$eg  0055V\\$=O5P 	4 czELLN844!"""-##((:&O,(#

3" 	) 	
 ! 		s   B2F F,c                     |j                  d      d   }|dz   t        t        j                               z   }	 t	        j
                  d||gd       || _        y# t        $ r t        w xY w)zCreates a temporary backup raster necessary for undo behavior.

        :param str name: name of raster map for which we create backup
        r   r   _backupcopy_g.copyT)r   r   N)	r   strr+   getpidr   r   r   r   r   )r6   r   backups      r9   r   zRDigitController._backupRaster  sl    
 zz#q!&RYY[)99	hf~TJ "( ! 		s   A A+c                    | j                          | j                  r| j                  ryd| _        t        | j                        dk  r_| j                  }d| j                  v r| j                  j                  d      d   }t        j                  d| j                  |gdd       ndt        t        j                               z   }g }g }d}dx}}t        t        | j                        dt        d	      
      }t        j                  | |       | j                  d   j!                  d      }| j                  d   j!                  d      }| j                  D ];  }	|	j!                  d      r||	j!                  d      k7  s||	j!                  d      k7  r|r1| j#                  ||| j$                  |      }
|j'                  |
       g }| j)                  |	|       | j#                  ||	j!                  d      | j$                  |      }
|j'                  |
       g }n| j)                  |	|       |	j!                  d      }|	j!                  d      }|dz  }t        t        | j                        |t        d	      
      }t        j                  | |       > |r>| j#                  |	j!                  d      | j$                  |      }
|j'                  |
       t        j                  d|ddd   | j                  gz   | j                  dd| j*                         t        j                  ddd||gz   d       	 | j,                  ry| j.                  s@t1        j2                  ddd      }|sd}t        j                  d|| j                  d       yt        j                  d| j                  | j.                  d       y# t4        $ r* d| _        t7        | j8                  t        d             Y yw xY w)aU  Rasterizes digitized features.

        Uses r.in.poly and r.grow for buffering features. Creates separate raster
        maps depending on common cell values and buffering width necessary to
        keep the order of editing. These rasters are then patched together.
        Sets default color table for the newly digitized raster.
        NT   r   r   r  )r   r   r   tmp_rdigit_rast_zRasterizing...)ranger   r_   rj   rk   zr.patchr^   )inputoutputr   r   envr   r   r   r   rasterLayer
colorTable	selection)groupkeysubkeyrainbowr   )r   r   r   r   Fz7Failed to set default color table for edited raster maprN   )
_setRegionr   r$   r   r"   r   r   r   r   r  r+   r  updateProgressrV   r   	PostEventGetPropertyVal
_rasterizer   rY   
_writeItemr.   r   r   r   Getr   r
   r   )r6   r   
tempRasterr_   rastersToPatchilastCellValuelastWidthValueevtr\   outtables               r9   r   zRDigitController._exportRaster  s    	!!T]]tyy>A$$Cd(((((..s3A6..4	 ,c"))+.>>JDNA-11MN $))nAA6F4GC LLs# IIaL77DM!YYq\88FN		 (&&|4!T%8%8%EE%)<)<\)JJ"oo .$-- '--c2!OOD$///++L9"	C #))#.DOOD$/ $ 3 3K @!%!4!4\!BQ$dii.:J8K T3'=(> oo$--l;T]]J %%c*$TrT*d.D.D-EE))II #zl2	""))$(('\+ %E!!e1C1C4 !!**11	 ! 	!DMST	s   ;O AO -O 0O54O5c           
      >   |j                         }|dk(  r|g}|j                  d      }dj                  |      }|D ]2  }|dj                  |D cg c]  }t	        |       c}      z  }|dz  }4 |dj                  |      z  }|j                  |       y	c c}w )
z.Writes digitized features in r.in.poly format.Prj   z{vtype}
)vtype r   z= {cellValue}
)rj   N)ra   r  r   joinr  rY   )	r6   r\   r'  r_   rQ   rj   recordcoordcs	            r9   _writeFeaturezRDigitController._writeFeaturem  s    !C<XF''4	##%#0 	Echh61A677FdNF	 	#**Y*??F	  7s   Bc                 *   || j                   j                         v r| j                  |d|       y || j                  j                         v r| j                  |d|       y || j                  j                         v r| j                  |d|       y y )NA)r'  r_   Lr&  )r   GetAllItemsr-  r    r!   )r6   r\   r_   s      r9   r  zRDigitController._writeItem{  s    4;;**,,t3T:T[[,,..t3T:T\\--//t3T: 0r:   c           	         dt        t        j                               dd z   }t        j                  dd      }|j                  dj                  |             |j                          |rQ|dz  }t        j                  d	|j                  ||d
d
       t        j                  d||d|d
| j                         n/t        j                  d	|j                  ||d
| j                         t        j                  |j                         |S )a  Performs the actual rasterization using r.in.poly
        and buffering with r.grow if required.

        :param str text: string in r.in.poly format
        :param float bufferDist: buffer distance in map units
        :param str mapType: CELL, FCELL, DCELL
        :param str tempRaster: name of temporary raster used in computation

        :return: output raster map name as a result of digitization
        rZ   N   wF)modedeleter   g       @z	r.in.polyT)r  r  type_r   r   zr.growm)r  r  r   radiusr   r  )r  r  r7  r   r  )r  uuiduuid4tempfileNamedTemporaryFilewriter)  closer   r   r   r.   r+   unlink)r6   r_   
bufferDistr   r  r  	asciiFiles          r9   r  zRDigitController._rasterize  s     s4::<(!,,//SG			$(#Jnn!  !II nnII 			)..!r:   c                 ^    t        j                  | j                        | j                  d<   y)z%Set region according input raster mapr   GRASS_REGIONN)r   
region_envr   r.   rF   s    r9   r  zRDigitController._setRegion  s!    $)$4$4D<R<R$S		.!r:   )T)FNNN)__name__
__module____qualname____doc__r   rG   rL   r?   rA   rC   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r-  r  r  r   r:   r9   r   r   #   s    9Lv4Q!8"@ "D)B'(0#1J&*

4 =D"/
" 6p,
\(qf;-^Tr:   r   )rI  r+   r<  r   r:  wx.lib.neweventr   grass.scriptr   r   r   r   grass.exceptionsr   r   grass.pydispatch.signalr	   	core.gcmdr
   r   core.settingsr   core.gthreadr   rdigit.dialogsr   r  EVT_UPDATE_PROGRESSr   r   rJ  r:   r9   <module>rT     sT    
  	  $ & ( ; * & &   *&.j ##Q
Tr}} Q
Tr:   