mapdisp.py 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956
  1. """
  2. MODULE: mapdisp.py
  3. CLASSES:
  4. - Command
  5. - MapWindow
  6. - BufferedWindow
  7. - MapFrame
  8. - MapApp
  9. PURPOSE: GIS map display canvas, with toolbar for various display
  10. management functions, and second toolbar for vector
  11. digitizing. Can be used either from GIS Manager or as p.mon backend
  12. Usage:
  13. python mapdisp.py monitor-identifier /path/to/command/file
  14. AUTHORS: Michael Barton
  15. Jachym Cepicky
  16. Martin Landa <landa.martin gmail.com>
  17. COPYRIGHT: (C) 2006-2008 by the GRASS Development Team
  18. This program is free software under the GNU General Public
  19. License (>=v2). Read the file COPYING that comes with GRASS
  20. for details.
  21. """
  22. import os
  23. import sys
  24. import time
  25. import glob
  26. import math
  27. import tempfile
  28. import copy
  29. import wx
  30. import wx.aui
  31. from threading import Thread
  32. import globalvar
  33. try:
  34. import subprocess
  35. except:
  36. CompatPath = os.path.join(globalvar.ETCWXDIR)
  37. sys.path.append(CompatPath)
  38. from compat import subprocess
  39. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  40. sys.path.append(gmpath)
  41. import render
  42. import toolbars
  43. import grassenv
  44. import track
  45. import menuform
  46. import gselect
  47. import disp_print
  48. import gcmd
  49. import dbm
  50. import histogram
  51. import profile
  52. import globalvar
  53. import utils
  54. import gdialogs
  55. from vdigit import VDigitCategoryDialog as VDigitCategoryDialog
  56. from vdigit import VDigitZBulkDialog as VDigitZBulkDialog
  57. from vdigit import VDigitDuplicatesDialog as VDigitDuplicatesDialog
  58. from vdigit import GV_LINES as VDigit_Lines_Type
  59. from debug import Debug as Debug
  60. from icon import Icons as Icons
  61. from preferences import globalSettings as UserSettings
  62. import images
  63. imagepath = images.__path__[0]
  64. sys.path.append(imagepath)
  65. ###
  66. ### global variables
  67. ###
  68. # for standalone app
  69. cmdfilename = None
  70. class Command(Thread):
  71. """
  72. Creates thread which will observe the command file and see, if
  73. there is new command to be executed
  74. """
  75. def __init__ (self, parent, Map):
  76. Thread.__init__(self)
  77. global cmdfilename
  78. self.parent = parent
  79. self.map = Map
  80. self.cmdfile = open(cmdfilename, "r")
  81. def run(self):
  82. """
  83. Run this in thread
  84. """
  85. dispcmd = []
  86. while 1:
  87. self.parent.redraw = False
  88. line = self.cmdfile.readline().strip()
  89. if line == "quit":
  90. break
  91. if line:
  92. try:
  93. Debug.msg (3, "Command.run(): cmd=%s" % (line))
  94. self.map.AddLayer(item=None, type="raster",
  95. name='',
  96. command=line,
  97. l_opacity=1)
  98. self.parent.redraw =True
  99. except Exception, e:
  100. print "Command Thread: ",e
  101. time.sleep(0.1)
  102. sys.exit()
  103. class MapWindow(object):
  104. """Abstract map window class
  105. Parent for BufferedWindow class (2D display mode) and
  106. GLWindow (3D display mode)
  107. """
  108. def __init__(self, parent, id=wx.ID_ANY,
  109. pos=wx.DefaultPosition,
  110. size=wx.DefaultSize,
  111. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  112. Map=None, tree=None, gismgr=None):
  113. self.parent = parent # MapFrame
  114. def EraseMap(self):
  115. """
  116. Erase the canvas (virtual method)
  117. """
  118. pass
  119. def UpdateMap(self):
  120. """
  121. Updates the canvas anytime there is a change to the
  122. underlaying images or to the geometry of the canvas.
  123. """
  124. pass
  125. def OnLeftDown(self, event):
  126. pass
  127. def OnLeftUp(self, event):
  128. pass
  129. def OnMouseMotion(self, event):
  130. pass
  131. def OnZoomToMap(self, event):
  132. pass
  133. def OnZoomToRaster(self, event):
  134. pass
  135. def GetSelectedLayer(self, type='layer'):
  136. """Get selected layer from layer tree
  137. @param type 'item' / 'layer' / 'nviz'
  138. @return layer / map layer properties / nviz properties
  139. @return None on failure
  140. """
  141. # get currently selected map layer
  142. if not self.tree or not self.tree.GetSelection():
  143. return None
  144. item = self.tree.GetSelection()
  145. if not item.IsChecked():
  146. return None
  147. if type == 'item':
  148. return item
  149. try:
  150. if type == 'nviz':
  151. layer = self.tree.GetPyData(item)[0]['nviz']
  152. else:
  153. layer = self.tree.GetPyData(item)[0]['maplayer']
  154. except:
  155. layer = None
  156. return layer
  157. class BufferedWindow(MapWindow, wx.Window):
  158. """
  159. A Buffered window class.
  160. When the drawing needs to change, you app needs to call the
  161. UpdateMap() method. Since the drawing is stored in a bitmap, you
  162. can also save the drawing to file by calling the
  163. SaveToFile(self,file_name,file_type) method.
  164. """
  165. def __init__(self, parent, id,
  166. pos = wx.DefaultPosition,
  167. size = wx.DefaultSize,
  168. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  169. Map=None, tree=None, gismgr=None):
  170. MapWindow.__init__(self, parent, id, pos, size, style,
  171. Map, tree, gismgr)
  172. wx.Window.__init__(self, parent, id, pos, size, style)
  173. self.Map = Map
  174. self.tree = tree
  175. self.gismanager = gismgr
  176. #
  177. # Flags
  178. #
  179. self.resize = False # indicates whether or not a resize event has taken place
  180. self.dragimg = None # initialize variable for map panning
  181. #
  182. # Variable for drawing on DC
  183. #
  184. self.pen = None # pen for drawing zoom boxes, etc.
  185. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  186. # List of wx.Point tuples defining a polyline (geographical coordinates)
  187. self.polycoords = []
  188. # ID of rubber band line
  189. self.lineid = None
  190. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  191. self.plineid = None
  192. #
  193. # Event bindings
  194. #
  195. self.Bind(wx.EVT_PAINT, self.OnPaint)
  196. self.Bind(wx.EVT_SIZE, self.OnSize)
  197. self.Bind(wx.EVT_IDLE, self.OnIdle)
  198. self.Bind(wx.EVT_MOTION, self.MouseActions)
  199. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  200. self.processMouse = True
  201. #
  202. # Render output objects
  203. #
  204. self.mapfile = None # image file to be rendered
  205. self.img = "" # wx.Image object (self.mapfile)
  206. # used in digitization tool (do not redraw vector map)
  207. self.imgVectorMap = None
  208. # decoration overlays
  209. self.overlays = {}
  210. # images and their PseudoDC ID's for painting and dragging
  211. self.imagedict = {}
  212. self.select = {} # selecting/unselecting decorations for dragging
  213. self.textdict = {} # text, font, and color indexed by id
  214. self.currtxtid = None # PseudoDC id for currently selected text
  215. #
  216. # Zoom objects
  217. #
  218. self.zoomhistory = [] # list of past zoom extents
  219. self.currzoom = 0 # current set of extents in zoom history being used
  220. #
  221. # mouse attributes like currently pressed buttons, position on
  222. # the screen, begin and end of dragging, and type of drawing
  223. #
  224. self.mouse = {
  225. 'l' : False,
  226. 'r' : False,
  227. 'm' : False,
  228. 'begin': [0, 0], # screen coordinates
  229. 'end' : [0, 0],
  230. 'use' : "pointer",
  231. 'box' : "point"
  232. }
  233. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  234. self.hitradius = 10 # distance for selecting map decorations
  235. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  236. # OnSize called to make sure the buffer is initialized.
  237. # This might result in OnSize getting called twice on some
  238. # platforms at initialization, but little harm done.
  239. ### self.OnSize(None)
  240. # create PseudoDC used for background map, map decorations like scales and legends
  241. self.pdc = wx.PseudoDC()
  242. # used for digitization tool
  243. self.pdcVector = None
  244. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  245. self.pdcTmp = wx.PseudoDC()
  246. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  247. self.redrawAll = True
  248. # will store an off screen empty bitmap for saving to file
  249. self._buffer = ''
  250. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  251. # vars for handling mouse clicks
  252. self.dragid = -1
  253. self.lastpos = (0, 0)
  254. def Draw(self, pdc, img=None, drawid=None, pdctype='image', coords=[0, 0, 0, 0]):
  255. """
  256. Draws map and overlay decorations
  257. """
  258. if drawid == None:
  259. if pdctype == 'image' and img:
  260. drawid = self.imagedict[img]
  261. elif pdctype == 'clear':
  262. drawid == None
  263. else:
  264. drawid = wx.NewId()
  265. if img and pdctype == 'image':
  266. # self.imagedict[img]['coords'] = coords
  267. self.select[self.imagedict[img]['id']] = False # ?
  268. pdc.BeginDrawing()
  269. if drawid != 99:
  270. bg = wx.TRANSPARENT_BRUSH
  271. else:
  272. bg = wx.Brush(self.GetBackgroundColour())
  273. pdc.SetBackground(bg)
  274. #pdc.Clear()
  275. self.Refresh()
  276. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % \
  277. (drawid, pdctype, coords))
  278. # set PseudoDC id
  279. if drawid is not None:
  280. pdc.SetId(drawid)
  281. if pdctype == 'clear': # erase the display
  282. bg = wx.WHITE_BRUSH
  283. # bg = wx.Brush(self.GetBackgroundColour())
  284. pdc.SetBackground(bg)
  285. pdc.RemoveAll()
  286. pdc.Clear()
  287. self.Refresh()
  288. pdc.EndDrawing()
  289. return
  290. if pdctype == 'image': # draw selected image
  291. bitmap = wx.BitmapFromImage(img)
  292. w,h = bitmap.GetSize()
  293. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  294. pdc.SetIdBounds(drawid, (coords[0],coords[1], w, h))
  295. elif pdctype == 'box': # draw a box on top of the map
  296. if self.pen:
  297. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  298. pdc.SetPen(self.pen)
  299. x2 = max(coords[0],coords[2])
  300. x1 = min(coords[0],coords[2])
  301. y2 = max(coords[1],coords[3])
  302. y1 = min(coords[1],coords[3])
  303. rwidth = x2-x1
  304. rheight = y2-y1
  305. rect = wx.Rect(x1,y1,rwidth,rheight)
  306. pdc.DrawRectangleRect(rect)
  307. pdc.SetIdBounds(drawid,rect)
  308. # self.ovlcoords[drawid] = coords
  309. elif pdctype == 'line': # draw a line on top of the map
  310. if self.pen:
  311. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  312. pdc.SetPen(self.pen)
  313. pdc.DrawLine(coords[0], coords[1], coords[2], coords[3])
  314. pdc.SetIdBounds(drawid,(coords[0], coords[1], coords[2], coords[3]))
  315. # self.ovlcoords[drawid] = coords
  316. elif pdctype == 'polyline': # draw a polyline on top of the map
  317. if self.polypen:
  318. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  319. pdc.SetPen(self.polypen)
  320. pdc.DrawLines(coords)
  321. # get bounding rectangle for polyline
  322. xlist = []
  323. ylist = []
  324. if len(coords) > 0:
  325. for point in coords:
  326. x,y = point
  327. xlist.append(x)
  328. ylist.append(y)
  329. x1=min(xlist)
  330. x2=max(xlist)
  331. y1=min(ylist)
  332. y2=max(ylist)
  333. pdc.SetIdBounds(drawid,(x1,y1,x2,y2))
  334. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  335. elif pdctype == 'point': # draw point
  336. if self.pen:
  337. pdc.SetPen(self.pen)
  338. pdc.DrawPoint(coords[0], coords[1])
  339. coordsBound = (coords[0] - 5,
  340. coords[1] - 5,
  341. coords[0] + 5,
  342. coords[1] + 5)
  343. pdc.SetIdBounds(drawid, coordsBound)
  344. # self.ovlcoords[drawid] = coords
  345. elif pdctype == 'text': # draw text on top of map
  346. text = img[0]
  347. rotation = float(img[3])
  348. w, h = self.GetFullTextExtent(img[0])[0:2]
  349. pdc.SetFont(img[1])
  350. pdc.SetTextForeground(img[2])
  351. coords, w, h = self.TextBounds(img, coords)
  352. if rotation == 0:
  353. pdc.DrawText(img[0], coords[0], coords[1])
  354. else:
  355. pdc.DrawRotatedText(img[0], coords[0], coords[1], rotation)
  356. pdc.SetIdBounds(drawid, (coords[0], coords[1], w, h))
  357. # self.ovlcoords[drawid] = coords
  358. pdc.EndDrawing()
  359. self.Refresh()
  360. return drawid
  361. def TextBounds(self, textinfo, coords):
  362. """
  363. Return text boundary data
  364. @param textinfo text metadata (text, font, color, rotation)
  365. @param coords reference point
  366. """
  367. rotation = float(textinfo[3])
  368. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  369. (textinfo[0], rotation))
  370. self.Update()
  371. self.Refresh()
  372. self.SetFont(textinfo[1])
  373. w, h = self.GetTextExtent(textinfo[0])
  374. if rotation == 0:
  375. coords[2], coords[3] = coords[0] + w, coords[1] + h
  376. return coords, w, h
  377. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  378. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  379. coords[2] = coords[0] + boxw
  380. coords[3] = coords[1] + boxh
  381. return coords, boxw, boxh
  382. def OnPaint(self, event):
  383. """
  384. Draw PseudoDC's to buffered paint DC
  385. self.pdc for background and decorations
  386. self.pdcVector for vector map which is edited
  387. self.pdcTmp for temporaly drawn objects (self.polycoords)
  388. If self.redrawAll is False on self.pdcTmp content is re-drawn
  389. """
  390. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  391. dc = wx.BufferedPaintDC(self, self.buffer)
  392. # we need to clear the dc BEFORE calling PrepareDC
  393. #bg = wx.Brush(self.GetBackgroundColour())
  394. dc.SetBackground(wx.Brush("White"))
  395. dc.Clear()
  396. # use PrepareDC to set position correctly
  397. self.PrepareDC(dc)
  398. # create a clipping rect from our position and size
  399. # and update region
  400. rgn = self.GetUpdateRegion().GetBox()
  401. dc.SetClippingRect(rgn)
  402. if self.redrawAll: # redraw pdc and pdcVector
  403. # draw to the dc using the calculated clipping rect
  404. self.pdc.DrawToDCClipped(dc, rgn)
  405. # draw vector map layer
  406. if self.pdcVector:
  407. self.pdcVector.DrawToDCClipped(dc, rgn)
  408. self.bufferLast = None
  409. else: # do not redraw pdc and pdcVector
  410. if self.bufferLast is None:
  411. # draw to the dc
  412. self.pdc.DrawToDC(dc)
  413. if self.pdcVector:
  414. self.pdcVector.DrawToDC(dc)
  415. # store buffered image
  416. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  417. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  418. pdcLast = wx.PseudoDC()
  419. pdcLast.DrawBitmap(bmp=self.bufferLast, x=0, y=0)
  420. pdcLast.DrawToDC(dc)
  421. # draw temporary object on the foreground
  422. # self.pdcTmp.DrawToDCClipped(dc, rgn)
  423. self.pdcTmp.DrawToDC(dc)
  424. def OnSize(self, event):
  425. """
  426. Scale map image so that it is
  427. the same size as the Window
  428. """
  429. Debug.msg(3, "BufferedWindow.OnSize():")
  430. # set size of the input image
  431. self.Map.ChangeMapSize(self.GetClientSize())
  432. # align extent based on center point and display resolution
  433. # this causes that image is not resized when display windows is resized
  434. # self.Map.AlignExtentFromDisplay()
  435. # Make new off screen bitmap: this bitmap will always have the
  436. # current drawing in it, so it can be used to save the image to
  437. # a file, or whatever.
  438. self.buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  439. # get the image to be rendered
  440. self.img = self.GetImage()
  441. # update map display
  442. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  443. self.img = self.img.Scale(self.Map.width, self.Map.height)
  444. if len(self.Map.GetListOfLayers()) > 0:
  445. self.UpdateMap()
  446. # re-render image on idle
  447. self.resize = True
  448. # reposition checkbox in statusbar
  449. self.parent.StatusbarReposition()
  450. # update statusbar
  451. self.parent.StatusbarUpdate()
  452. def OnIdle(self, event):
  453. """
  454. Only re-render a composite map image from GRASS during
  455. idle time instead of multiple times during resizing.
  456. """
  457. if self.resize:
  458. self.UpdateMap(render=True)
  459. event.Skip()
  460. def SaveToFile(self, FileName, FileType):
  461. """
  462. This draws the psuedo DC to a buffer that
  463. can be saved to a file.
  464. """
  465. dc = wx.BufferedPaintDC(self, self.buffer)
  466. self.pdc.DrawToDC(dc)
  467. if self.pdcVector:
  468. self.pdcVector.DrawToDC(dc)
  469. self.buffer.SaveFile(FileName, FileType)
  470. def GetOverlay(self):
  471. """
  472. Converts rendered overlay files to wx.Image
  473. Updates self.imagedict
  474. @return list of images
  475. """
  476. imgs = []
  477. for overlay in self.Map.GetListOfLayers(l_type="overlay", l_active=True):
  478. if os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  479. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  480. self.imagedict[img] = { 'id' : overlay.id,
  481. 'layer' : overlay }
  482. imgs.append(img)
  483. return imgs
  484. def GetImage(self):
  485. """
  486. Converts redered map files to wx.Image
  487. Updates self.imagedict (id=99)
  488. @return wx.Image instance (map composition)
  489. """
  490. imgId = 99
  491. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  492. os.path.getsize(self.Map.mapfile):
  493. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  494. else:
  495. img = None
  496. self.imagedict[img] = { 'id': imgId }
  497. return img
  498. def UpdateMap(self, render=True, renderVector=True):
  499. """
  500. Updates the canvas anytime there is a change to the
  501. underlaying images or to the geometry of the canvas.
  502. @param render re-render map composition
  503. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  504. """
  505. start = time.clock()
  506. self.resize = False
  507. # if len(self.Map.GetListOfLayers()) == 0:
  508. # return False
  509. if self.img is None:
  510. render = True
  511. #
  512. # initialize process bar (only on 'render')
  513. #
  514. if render is True or renderVector is True:
  515. self.parent.onRenderGauge.Show()
  516. if self.parent.onRenderGauge.GetRange() > 0:
  517. self.parent.onRenderGauge.SetValue(1)
  518. #
  519. # render background image if needed
  520. #
  521. # update layer dictionary if there has been a change in layers
  522. if self.tree.reorder == True:
  523. self.tree.ReorderLayers()
  524. # reset flag for auto-rendering
  525. self.tree.rerender = False
  526. if render:
  527. # update display size
  528. self.Map.ChangeMapSize(self.GetClientSize())
  529. windres = False
  530. if self.parent.compResolution.GetValue():
  531. # use computation region resolution for rendering
  532. windres = True
  533. self.mapfile = self.Map.Render(force=True, mapWindow=self.parent,
  534. windres=windres)
  535. else:
  536. self.mapfile = self.Map.Render(force=False, mapWindow=self.parent)
  537. self.img = self.GetImage() # id=99
  538. #
  539. # clear pseudoDcs
  540. #
  541. self.pdc.Clear()
  542. self.pdc.RemoveAll()
  543. self.pdcTmp.Clear()
  544. self.pdcTmp.RemoveAll()
  545. #
  546. # draw background map image to PseudoDC
  547. #
  548. if not self.img:
  549. self.Draw(self.pdc, pdctype='clear')
  550. else:
  551. try:
  552. id = self.imagedict[self.img]['id']
  553. except:
  554. return False
  555. self.Draw(self.pdc, self.img, drawid=id)
  556. #
  557. # render vector map layer
  558. #
  559. digitToolbar = self.parent.toolbars['vdigit']
  560. if renderVector and digitToolbar and \
  561. digitToolbar.GetLayer():
  562. # set region
  563. self.parent.digit.driver.UpdateRegion()
  564. # re-calculate threshold for digitization tool
  565. self.parent.digit.driver.GetThreshold()
  566. # draw map
  567. self.pdcVector.Clear()
  568. self.pdcVector.RemoveAll()
  569. try:
  570. item = self.tree.FindItemByData('maplayer', digitToolbar.GetLayer())
  571. except TypeError:
  572. item = None
  573. if item and self.tree.IsItemChecked(item):
  574. self.parent.digit.driver.DrawMap()
  575. #
  576. # render overlays
  577. #
  578. for img in self.GetOverlay():
  579. # draw any active and defined overlays
  580. if self.imagedict[img]['layer'].IsActive():
  581. id = self.imagedict[img]['id']
  582. self.Draw(self.pdc, img=img, drawid=id,
  583. pdctype=self.overlays[id]['pdcType'], coords=self.overlays[id]['coords'])
  584. for id in self.textdict.keys():
  585. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  586. pdctype='text', coords=[10, 10, 10, 10])
  587. # optionally draw computational extent box
  588. self.DrawCompRegionExtent()
  589. #
  590. # redraw pdcTmp if needed
  591. #
  592. if len(self.polycoords) > 0:
  593. self.DrawLines(self.pdcTmp)
  594. if self.parent.gismanager.georectifying:
  595. # -> georectifier (redraw GCPs)
  596. if self.parent.toolbars['georect']:
  597. coordtype = 'gcpcoord'
  598. else:
  599. coordtype = 'mapcoord'
  600. self.parent.gismanager.georectifying.DrawGCP(coordtype)
  601. stop = time.clock()
  602. #
  603. # hide process bar
  604. #
  605. self.parent.onRenderGauge.Hide()
  606. #
  607. # update statusbar
  608. #
  609. ### self.Map.SetRegion()
  610. self.parent.StatusbarUpdate()
  611. Debug.msg (2, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  612. (render, renderVector, (stop-start)))
  613. return True
  614. def DrawCompRegionExtent(self):
  615. """Draw computational region extent in the display
  616. Display region is drawn as a blue box inside the computational region,
  617. computational region inside a display region as a red box).
  618. """
  619. if hasattr(self, "regionCoords"):
  620. compReg = self.Map.GetRegion()
  621. dispReg = self.Map.GetCurrentRegion()
  622. reg = None
  623. if self.IsInRegion(dispReg, compReg):
  624. self.polypen = wx.Pen(colour='blue', width=3, style=wx.SOLID)
  625. reg = dispReg
  626. else:
  627. self.polypen = wx.Pen(colour='red', width=3, style=wx.SOLID)
  628. reg = compReg
  629. self.regionCoords = []
  630. self.regionCoords.append((reg['w'], reg['n']))
  631. self.regionCoords.append((reg['e'], reg['n']))
  632. self.regionCoords.append((reg['e'], reg['s']))
  633. self.regionCoords.append((reg['w'], reg['s']))
  634. self.regionCoords.append((reg['w'], reg['n']))
  635. # draw region extent
  636. self.DrawLines(pdc=self.pdcTmp, polycoords=self.regionCoords)
  637. def IsInRegion(self, region, refRegion):
  638. """Test if 'region' is inside of 'refRegion'
  639. @param region input region
  640. @param refRegion reference region (e.g. computational region)
  641. @return True if region is inside of refRegion
  642. @return False
  643. """
  644. if region['s'] >= refRegion['s'] and \
  645. region['n'] <= refRegion['n'] and \
  646. region['w'] >= refRegion['w'] and \
  647. region['e'] <= refRegion['e']:
  648. return True
  649. return False
  650. def EraseMap(self):
  651. """
  652. Erase the canvas
  653. """
  654. self.Draw(self.pdc, pdctype='clear')
  655. if self.pdcVector:
  656. self.Draw(self.pdcVector, pdctype='clear')
  657. self.Draw(self.pdcVector, pdctype='clear')
  658. def DragMap(self, moveto):
  659. """
  660. Drag the entire map image for panning.
  661. """
  662. dc = wx.BufferedDC(wx.ClientDC(self))
  663. dc.SetBackground(wx.Brush("White"))
  664. dc.Clear()
  665. self.dragimg = wx.DragImage(self.buffer)
  666. self.dragimg.BeginDrag((0, 0), self)
  667. self.dragimg.GetImageRect(moveto)
  668. self.dragimg.Move(moveto)
  669. self.dragimg.DoDrawImage(dc, moveto)
  670. self.dragimg.EndDrag()
  671. return True
  672. def DragItem(self, id, event):
  673. """
  674. Drag an overlay decoration item
  675. """
  676. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % \
  677. id)
  678. x, y = self.lastpos
  679. dx = event.GetX() - x
  680. dy = event.GetY() - y
  681. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  682. r = self.pdc.GetIdBounds(id)
  683. if self.dragid > 100: # text dragging
  684. rtop = (r[0],r[1]-r[3],r[2],r[3])
  685. r = r.Union(rtop)
  686. rleft = (r[0]-r[2],r[1],r[2],r[3])
  687. r = r.Union(rleft)
  688. self.pdc.TranslateId(id, dx, dy)
  689. r2 = self.pdc.GetIdBounds(id)
  690. r = r.Union(r2)
  691. r.Inflate(4,4)
  692. self.Update()
  693. self.RefreshRect(r, False)
  694. self.lastpos = (event.GetX(), event.GetY())
  695. def MouseDraw(self, pdc=None, begin=None, end=None):
  696. """
  697. Mouse box or line from 'begin' to 'end'
  698. If not given from self.mouse['begin'] to self.mouse['end'].
  699. """
  700. self.redrawAll = False
  701. if not pdc:
  702. return
  703. if begin is None:
  704. begin = self.mouse['begin']
  705. if end is None:
  706. end = self.mouse['end']
  707. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  708. (self.mouse['use'], self.mouse['box'],
  709. begin[0], begin[1], end[0], end[1]))
  710. if self.mouse['box'] == "box":
  711. boxid = wx.ID_NEW
  712. mousecoords = [begin[0], begin[1],
  713. end[0], end[1]]
  714. r = pdc.GetIdBounds(boxid)
  715. r.Inflate(4,4)
  716. pdc.ClearId(boxid)
  717. self.RefreshRect(r, False)
  718. pdc.SetId(boxid)
  719. self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
  720. elif self.mouse['box'] == "line":
  721. self.lineid = wx.ID_NEW
  722. mousecoords = [begin[0], begin[1], \
  723. end[0], end[1]]
  724. x1=min(begin[0],end[0])
  725. x2=max(begin[0],end[0])
  726. y1=min(begin[1],end[1])
  727. y2=max(begin[1],end[1])
  728. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  729. r.Inflate(4,4)
  730. try:
  731. pdc.ClearId(self.lineid)
  732. except:
  733. pass
  734. self.RefreshRect(r, False)
  735. pdc.SetId(self.lineid)
  736. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=mousecoords)
  737. def DrawLines(self, pdc=None, polycoords=None):
  738. """Draw polyline in PseudoDC
  739. Set self.pline to wx.NEW_ID + 1
  740. polycoords - list of polyline vertices, geographical coordinates
  741. (if not given, self.polycoords is used)
  742. """
  743. if not pdc:
  744. pdc = self.pdcTmp
  745. if not polycoords:
  746. polycoords = self.polycoords
  747. if len(polycoords) > 0:
  748. self.plineid = wx.ID_NEW + 1
  749. # convert from EN to XY
  750. coords = []
  751. for p in polycoords:
  752. coords.append(self.Cell2Pixel(p))
  753. self.Draw(pdc, drawid=self.plineid, pdctype='polyline', coords=coords)
  754. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  755. (coords, self.plineid))
  756. return self.plineid
  757. return -1
  758. def DrawCross(self, pdc, coords, size, rotation=0,
  759. text=None, textAlign='lr', textOffset=(5, 5)):
  760. """Draw cross in PseudoDC
  761. @todo implement rotation
  762. @param pdc PseudoDC
  763. @param coord center coordinates
  764. @param rotation rotate symbol
  765. @param text draw also text (text, font, color, rotation)
  766. @param textAlign alignment (default 'lower-right')
  767. @textOffset offset for text (from center point)
  768. """
  769. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  770. (pdc, coords, size))
  771. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  772. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  773. self.lineid = wx.NewId()
  774. for lineCoords in coordsCross:
  775. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=lineCoords)
  776. if not text:
  777. return self.lineid
  778. if textAlign == 'ul':
  779. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  780. elif textAlign == 'ur':
  781. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  782. elif textAlign == 'lr':
  783. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  784. else:
  785. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  786. self.Draw(pdc, img=text,
  787. pdctype='text', coords=coord)
  788. return self.lineid
  789. def MouseActions(self, event):
  790. """
  791. Mouse motion and button click notifier
  792. """
  793. if not self.processMouse:
  794. return
  795. if self.redrawAll is False:
  796. self.redrawAll = True
  797. wheel = event.GetWheelRotation()
  798. # zoom with mouse wheel
  799. if wheel != 0:
  800. self.processMouse = False
  801. current = event.GetPositionTuple()[:]
  802. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  803. # zoom 1/2 of the screen, centered to current mouse position (TODO: settings)
  804. begin = (current[0] - self.Map.width / 4,
  805. current[1] - self.Map.height / 4)
  806. end = (current[0] + self.Map.width / 4,
  807. current[1] + self.Map.height / 4)
  808. if wheel > 0:
  809. zoomtype = 1
  810. else:
  811. zoomtype = -1
  812. # zoom
  813. self.Zoom(begin, end, zoomtype)
  814. # redraw map
  815. self.UpdateMap()
  816. self.OnPaint(None)
  817. # update statusbar
  818. self.parent.StatusbarUpdate()
  819. self.processMouse = True
  820. # left mouse button pressed
  821. elif event.LeftDown():
  822. self.OnLeftDown(event)
  823. # left mouse button released
  824. elif event.LeftUp():
  825. self.OnLeftUp(event)
  826. # dragging
  827. elif event.Dragging():
  828. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  829. current = event.GetPositionTuple()[:]
  830. previous = self.mouse['begin']
  831. move = (current[0] - previous[0],
  832. current[1] - previous[1])
  833. # dragging or drawing box with left button
  834. if self.mouse['use'] == 'pan':
  835. self.DragMap(move)
  836. # dragging decoration overlay item
  837. elif (self.mouse['use'] == 'pointer' and not self.parent.toolbars['vdigit']) and \
  838. self.dragid != None and \
  839. self.dragid != 99:
  840. self.DragItem(self.dragid, event)
  841. # dragging anything else - rubber band box or line
  842. else:
  843. self.mouse['end'] = event.GetPositionTuple()[:]
  844. if event.LeftIsDown():
  845. # draw box only when left mouse button is pressed
  846. self.MouseDraw(pdc=self.pdcTmp)
  847. # double click
  848. elif event.ButtonDClick():
  849. self.OnButtonDClick(event)
  850. # middle mouse button pressed
  851. elif event.MiddleDown():
  852. self.OnMiddleDown(event)
  853. # right mouse button pressed
  854. elif event.RightDown():
  855. self.OnRightDown(event)
  856. # right mouse button released
  857. elif event.RightUp():
  858. self.OnRightUp(event)
  859. elif event.Moving():
  860. self.OnMouseMoving(event)
  861. event.Skip()
  862. def OnLeftDown(self, event):
  863. """
  864. Left mouse button pressed
  865. """
  866. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  867. self.mouse["use"])
  868. self.mouse['begin'] = event.GetPositionTuple()[:]
  869. if self.mouse["use"] in ["measure", "profile"]:
  870. # measure or profile
  871. if len(self.polycoords) == 0:
  872. self.mouse['end'] = self.mouse['begin']
  873. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  874. self.ClearLines(pdc=self.pdcTmp)
  875. else:
  876. self.mouse['begin'] = self.mouse['end']
  877. elif self.mouse['use'] == 'zoom':
  878. pass
  879. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  880. # digitization
  881. digitToolbar = self.parent.toolbars['vdigit']
  882. digitClass = self.parent.digit
  883. east, north = self.Pixel2Cell(self.mouse['begin'])
  884. try:
  885. map = digitToolbar.GetLayer().GetName()
  886. except:
  887. map = None
  888. wx.MessageBox(parent=self,
  889. message=_("No vector map selected for editing."),
  890. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  891. event.Skip()
  892. return
  893. # calculate position of 'update record' dialog
  894. position = self.mouse['begin']
  895. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  896. position[1] + self.dialogOffset))
  897. if digitToolbar.GetAction() not in ("moveVertex", "addVertex",
  898. "removeVertex", "editLine"):
  899. # set pen
  900. self.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  901. self.polypen = wx.Pen(colour='dark green', width=2, style=wx.SOLID)
  902. if digitToolbar.GetAction() in ("addVertex", "removeVertex"):
  903. # unselect
  904. digitClass.driver.SetSelected([])
  905. if digitToolbar.GetAction() == "addLine":
  906. if digitToolbar.GetAction('type') in ["point", "centroid"]:
  907. # add new point
  908. if digitToolbar.GetAction('type') == 'point':
  909. point = True
  910. else:
  911. point = False
  912. if digitClass.AddPoint(map, point, east, north) < 0:
  913. return
  914. self.UpdateMap(render=False) # redraw map
  915. # add new record into atribute table
  916. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') is True:
  917. # select attributes based on layer and category
  918. cats = {}
  919. cats[UserSettings.Get(group='vdigit', key="layer", subkey='value')] = \
  920. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  921. addRecordDlg = dbm.DisplayAttributesDialog(parent=self, map=map,
  922. cats=cats,
  923. pos=posWindow,
  924. action="add")
  925. if addRecordDlg.mapDBInfo and \
  926. addRecordDlg.ShowModal() == wx.ID_OK:
  927. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  928. for sql in addRecordDlg.GetSQLString():
  929. sqlfile.file.write(sql + ";\n")
  930. sqlfile.file.flush()
  931. executeCommand = gcmd.Command(cmd=["db.execute",
  932. "--q",
  933. "input=%s" % sqlfile.name])
  934. elif digitToolbar.GetAction('type') in ["line", "boundary"]:
  935. # add new point to the line
  936. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  937. self.DrawLines(pdc=self.pdcTmp)
  938. elif digitToolbar.GetAction() == "editLine" and hasattr(self, "moveIds"):
  939. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  940. self.moveIds.append(wx.NewId())
  941. self.DrawLines(pdc=self.pdcTmp)
  942. elif digitToolbar.GetAction() == "deleteLine":
  943. pass
  944. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  945. not hasattr(self, "moveBegin"):
  946. # incremental value
  947. self.moveBegin = [0, 0]
  948. # geographic coordinates of initial position (self.mouse['end'])
  949. self.moveCoords = []
  950. # list of ids to modify
  951. self.moveIds = []
  952. if digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  953. # set pen
  954. pcolor = UserSettings.Get(group='vdigit', key="symbol",
  955. subkey=["highlight", "color"])
  956. self.pen = self.polypen = wx.Pen(colour=pcolor,
  957. width=2, style=wx.SHORT_DASH)
  958. self.pdcTmp.SetPen(self.polypen)
  959. elif digitToolbar.GetAction() == "splitLine":
  960. # unselect
  961. digitClass.driver.SetSelected([])
  962. elif digitToolbar.GetAction() in ["displayAttrs", "displayCats"]:
  963. qdist = digitClass.driver.GetThreshold(type='selectThresh')
  964. coords = (east, north)
  965. if digitToolbar.GetAction() == "displayAttrs":
  966. # select attributes based on coordinates (all layers)
  967. if self.parent.dialogs['attributes'] is None:
  968. if digitClass.type == 'vedit':
  969. self.parent.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self, map=map,
  970. query=(coords, qdist),
  971. pos=posWindow,
  972. action="update")
  973. else:
  974. if digitClass.driver.SelectLineByPoint(coords,
  975. digitClass.GetSelectType()) is not None:
  976. self.parent.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self, map=map,
  977. cats=digitClass.GetLineCats(),
  978. line=digitClass.driver.GetSelected()[0],
  979. action="update")
  980. else:
  981. # update currently open dialog
  982. if digitClass.type == 'vedit':
  983. self.parent.dialogs['attributes'].UpdateDialog(query=(coords, qdist))
  984. else:
  985. # unselect
  986. digitClass.driver.SetSelected([])
  987. # select new feature
  988. if digitClass.driver.SelectLineByPoint(coords,
  989. digitClass.GetSelectType()) is None:
  990. line = None
  991. else:
  992. line = digitClass.driver.GetSelected()[0]
  993. # upgrade dialog
  994. self.parent.dialogs['attributes'].UpdateDialog(cats=digitClass.GetLineCats(),
  995. line=line)
  996. if self.parent.dialogs['attributes']:
  997. line = self.parent.dialogs['attributes'].GetLine()
  998. if self.parent.dialogs['attributes'].mapDBInfo and line:
  999. # highlight feature & re-draw map
  1000. digitClass.driver.SetSelected([line])
  1001. if not self.parent.dialogs['attributes'].IsShown():
  1002. self.parent.dialogs['attributes'].Show()
  1003. else:
  1004. digitClass.driver.SetSelected([])
  1005. if self.parent.dialogs['attributes'] and \
  1006. self.parent.dialogs['attributes'].IsShown():
  1007. self.parent.dialogs['attributes'].Hide()
  1008. else: # displayCats
  1009. if self.parent.dialogs['category'] is None:
  1010. # open new dialog
  1011. if digitClass.type == 'vedit':
  1012. self.parent.dialogs['category'] = VDigitCategoryDialog(parent=self,
  1013. map=map,
  1014. query=(coords, qdist),
  1015. pos=posWindow,
  1016. title=_("Update categories"))
  1017. else:
  1018. if digitClass.driver.SelectLineByPoint(coords,
  1019. digitClass.GetSelectType()) is not None:
  1020. self.parent.dialogs['category'] = VDigitCategoryDialog(parent=self,
  1021. map=map,
  1022. cats=digitClass.GetLineCats(),
  1023. line=digitClass.driver.GetSelected()[0],
  1024. pos=posWindow,
  1025. title=_("Update categories"))
  1026. else:
  1027. # update currently open dialog
  1028. if digitClass.type == 'vedit':
  1029. self.parent.dialogs['category'].UpdateDialog(query=(coords, qdist))
  1030. else:
  1031. # unselect
  1032. digitClass.driver.SetSelected([])
  1033. # select new feature
  1034. if digitClass.driver.SelectLineByPoint(coords,
  1035. digitClass.GetSelectType()) is None:
  1036. line = None
  1037. else:
  1038. line = digitClass.driver.GetSelected()[0]
  1039. # upgrade dialog
  1040. self.parent.dialogs['category'].UpdateDialog(cats=digitClass.GetLineCats(),
  1041. line=line)
  1042. if self.parent.dialogs['category']:
  1043. line = self.parent.dialogs['category'].GetLine()
  1044. if line:
  1045. # highlight feature & re-draw map
  1046. digitClass.driver.SetSelected([line])
  1047. if not self.parent.dialogs['category'].IsShown():
  1048. self.parent.dialogs['category'].Show()
  1049. else:
  1050. digitClass.driver.SetSelected([])
  1051. if self.parent.dialogs['category'].IsShown():
  1052. self.parent.dialogs['category'].Hide()
  1053. self.UpdateMap(render=False)
  1054. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1055. if not hasattr(self, "copyCatsList"):
  1056. self.copyCatsList = []
  1057. else:
  1058. self.copyCatsIds = []
  1059. self.mouse['box'] = 'box'
  1060. elif digitToolbar.GetAction() == "copyLine":
  1061. self.copyIds = []
  1062. self.layerTmp = None
  1063. elif digitToolbar.GetAction() == "zbulkLine":
  1064. if len(self.polycoords) > 1: # start new line
  1065. self.polycoords = []
  1066. self.ClearLines(pdc=self.pdcTmp)
  1067. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1068. if len(self.polycoords) == 1:
  1069. begin = self.Pixel2Cell(self.polycoords[-1])
  1070. end = self.Pixel2Cell(self.mouse['end'])
  1071. else:
  1072. end = self.Pixel2Cell(self.polycoords[-1])
  1073. begin = self.Pixel2Cell(self.mouse['begin'])
  1074. self.DrawLines(self.pdcTmp, begin, end)
  1075. else:
  1076. # get decoration id
  1077. self.lastpos = self.mouse['begin']
  1078. idlist = self.pdc.FindObjects(x=self.lastpos[0], y=self.lastpos[1],
  1079. radius=self.hitradius)
  1080. if idlist != []:
  1081. self.dragid = idlist[0]
  1082. event.Skip()
  1083. def OnLeftUp(self, event):
  1084. """
  1085. Left mouse button released
  1086. """
  1087. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  1088. self.mouse["use"])
  1089. self.mouse['end'] = event.GetPositionTuple()[:]
  1090. if self.mouse['use'] in ["zoom", "pan"]:
  1091. # set region in zoom or pan
  1092. begin = self.mouse['begin']
  1093. end = self.mouse['end']
  1094. if self.mouse['use'] == 'zoom':
  1095. # set region for click (zero-width box)
  1096. if begin[0] - end[0] == 0 or \
  1097. begin[1] - end[1] == 0:
  1098. # zoom 1/2 of the screen (TODO: settings)
  1099. begin = (end[0] - self.Map.width / 4,
  1100. end[1] - self.Map.height / 4)
  1101. end = (end[0] + self.Map.width / 4,
  1102. end[1] + self.Map.height / 4)
  1103. self.Zoom(begin, end, self.zoomtype)
  1104. # redraw map
  1105. self.UpdateMap(render=True)
  1106. # update statusbar
  1107. self.parent.StatusbarUpdate()
  1108. elif self.mouse["use"] == "query":
  1109. # querying
  1110. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  1111. elif self.mouse["use"] == "queryVector":
  1112. # editable mode for vector map layers
  1113. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  1114. # clear temp canvas
  1115. self.UpdateMap(render=False, renderVector=False)
  1116. elif self.mouse["use"] in ["measure", "profile"]:
  1117. # measure or profile
  1118. if self.mouse["use"] == "measure":
  1119. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  1120. try:
  1121. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1122. self.pdcTmp.ClearId(self.lineid)
  1123. self.DrawLines(pdc=self.pdcTmp)
  1124. except:
  1125. pass
  1126. elif self.mouse["use"] == "pointer" and self.parent.gismanager.georectifying:
  1127. # -> georectifying
  1128. coord = self.Pixel2Cell(self.mouse['end'])
  1129. if self.parent.toolbars['georect']:
  1130. coordtype = 'gcpcoord'
  1131. else:
  1132. coordtype = 'mapcoord'
  1133. self.parent.gismanager.georectifying.SetGCPData(coordtype, coord, self)
  1134. self.UpdateMap(render=False, renderVector=False)
  1135. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  1136. # digitization tool active
  1137. digitToolbar = self.parent.toolbars['vdigit']
  1138. digitClass = self.parent.digit
  1139. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1140. pos2 = self.Pixel2Cell(self.mouse['end'])
  1141. if hasattr(self, "moveBegin"):
  1142. if len(digitClass.driver.GetSelected()) == 0:
  1143. self.moveCoords = pos2
  1144. else:
  1145. dx = pos2[0] - pos1[0]
  1146. dy = pos2[1] - pos1[1]
  1147. self.moveCoords = (self.moveCoords[0] + dx,
  1148. self.moveCoords[1] + dy)
  1149. # eliminate initial mouse moving efect
  1150. self.mouse['begin'] = self.mouse['end']
  1151. if digitToolbar.GetAction() in ["deleteLine", "moveLine", "moveVertex",
  1152. "copyCats", "copyAttrs", "editLine", "flipLine",
  1153. "mergeLine", "snapLine",
  1154. "queryLine", "breakLine", "typeConv", "connectLine"]:
  1155. nselected = 0
  1156. # -> delete line || move line || move vertex
  1157. if digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1158. if len(digitClass.driver.GetSelected()) == 0:
  1159. nselected = digitClass.driver.SelectLineByPoint(pos1, type=VDigit_Lines_Type)
  1160. if digitToolbar.GetAction() == "editLine":
  1161. try:
  1162. selVertex = digitClass.driver.GetSelectedVertex(pos1)[0]
  1163. except IndexError:
  1164. selVertex = None
  1165. if selVertex:
  1166. # self.UpdateMap(render=False)
  1167. ids = digitClass.driver.GetSelected(grassId=False)
  1168. # move this line to tmp layer
  1169. self.polycoords = []
  1170. for id in ids:
  1171. if id % 2: # register only vertices
  1172. self.moveIds.append(id)
  1173. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  1174. self.polycoords.append((e, n))
  1175. # self.pdcVector.RemoveId(id)
  1176. digitClass.driver.DrawSelected(False)
  1177. if selVertex < ids[-1] / 2:
  1178. # choose first or last node of line
  1179. self.moveIds.reverse()
  1180. self.polycoords.reverse()
  1181. else:
  1182. # unselect
  1183. digitClass.driver.SetSelected([])
  1184. del self.moveBegin
  1185. del self.moveCoords
  1186. del self.moveIds
  1187. self.UpdateMap(render=False)
  1188. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1189. if not hasattr(self, "copyCatsIds"):
  1190. # 'from' -> select by point
  1191. nselected = digitClass.driver.SelectLineByPoint(pos1, digitClass.GetSelectType())
  1192. if nselected:
  1193. if UserSettings.Get(group='advanced', key='digitInterface', subkey='type') == 'vedit':
  1194. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / \
  1195. self.Map.width)
  1196. vWhat = gcmd.Command(['v.what',
  1197. '--q',
  1198. 'map=%s' % digitClass.map,
  1199. 'east_north=%f,%f' % \
  1200. (float(pos1[0]), float(pos1[1])),
  1201. 'distance=%f' % qdist])
  1202. for line in vWhat.ReadStdOutput():
  1203. if "Category:" in line:
  1204. cat = int(line.split(':')[1].strip())
  1205. self.copyCatsList.append(cat)
  1206. else:
  1207. self.copyCatsList = digitClass.driver.GetSelected()
  1208. else:
  1209. # -> 'to' -> select by bbox
  1210. digitClass.driver.SetSelected([])
  1211. # return number of selected features (by box/point)
  1212. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1213. digitClass.GetSelectType())
  1214. if nselected == 0:
  1215. if digitClass.driver.SelectLineByPoint(pos1,
  1216. digitClass.GetSelectType()) is not None:
  1217. nselected = 1
  1218. if nselected > 0:
  1219. self.copyCatsIds = digitClass.driver.GetSelected()
  1220. elif digitToolbar.GetAction() == "queryLine":
  1221. selected = digitClass.SelectLinesByQuery(pos1, pos2)
  1222. nselected = len(selected)
  1223. if nselected > 0:
  1224. digitClass.driver.SetSelected(selected)
  1225. else:
  1226. # -> moveLine || deleteLine, etc. (select by point/box)
  1227. if digitToolbar.GetAction() == 'moveLine' and \
  1228. len(digitClass.driver.GetSelected()) > 0:
  1229. nselected = 0
  1230. else:
  1231. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1232. digitClass.GetSelectType())
  1233. if nselected == 0:
  1234. if digitClass.driver.SelectLineByPoint(pos1,
  1235. digitClass.GetSelectType()) is not None:
  1236. nselected = 1
  1237. if nselected > 0:
  1238. if digitToolbar.GetAction() in ["moveLine", "moveVertex"]:
  1239. # get pseudoDC id of objects which should be redrawn
  1240. if digitToolbar.GetAction() == "moveLine":
  1241. # -> move line
  1242. self.moveIds = digitClass.driver.GetSelected(grassId=False)
  1243. elif digitToolbar.GetAction() == "moveVertex":
  1244. # -> move vertex
  1245. self.moveIds = digitClass.driver.GetSelectedVertex(pos1)
  1246. if len(self.moveIds) == 0: # no vertex found
  1247. digitClass.driver.SetSelected([])
  1248. #
  1249. # check for duplicates
  1250. #
  1251. if UserSettings.Get(group='vdigit', key='checkForDupl', subkey='enabled') is True:
  1252. dupl = digitClass.driver.GetDuplicates()
  1253. self.UpdateMap(render=False)
  1254. if dupl:
  1255. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1256. self.mouse['end'][1] + self.dialogOffset))
  1257. dlg = VDigitDuplicatesDialog(parent=self, data=dupl, pos=posWindow)
  1258. if dlg.ShowModal() == wx.ID_OK:
  1259. digitClass.driver.UnSelect(dlg.GetUnSelected())
  1260. # update selected
  1261. self.UpdateMap(render=False)
  1262. if digitToolbar.GetAction() != "editLine":
  1263. # -> move line || move vertex
  1264. self.UpdateMap(render=False)
  1265. else: # no vector object found
  1266. self.UpdateMap(render=False, renderVector=False)
  1267. elif digitToolbar.GetAction() in ["splitLine", "addVertex", "removeVertex"]:
  1268. pointOnLine = digitClass.driver.SelectLineByPoint(pos1,
  1269. type=VDigit_Lines_Type)
  1270. if pointOnLine:
  1271. if digitToolbar.GetAction() in ["splitLine", "addVertex"]:
  1272. self.UpdateMap(render=False) # highlight object
  1273. self.DrawCross(pdc=self.pdcTmp, coords=self.Cell2Pixel(pointOnLine),
  1274. size=5)
  1275. elif digitToolbar.GetAction() == "removeVertex":
  1276. # get only id of vertex
  1277. try:
  1278. id = digitClass.driver.GetSelectedVertex(pos1)[0]
  1279. except IndexError:
  1280. id = None
  1281. if id:
  1282. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  1283. self.pdcVector.RemoveId(id)
  1284. self.UpdateMap(render=False) # highlight object
  1285. self.DrawCross(pdc=self.pdcTmp, coords=(x, y),
  1286. size=5)
  1287. else:
  1288. # unselect
  1289. digitClass.driver.SetSelected([])
  1290. self.UpdateMap(render=False)
  1291. elif digitToolbar.GetAction() == "copyLine":
  1292. if UserSettings.Get(group='vdigit', key='backgroundMap', subkey='value') == '':
  1293. # no background map -> copy from current vector map layer
  1294. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1295. digitClass.GetSelectType())
  1296. if nselected > 0:
  1297. # highlight selected features
  1298. self.UpdateMap(render=False)
  1299. else:
  1300. self.UpdateMap(render=False, renderVector=False)
  1301. else:
  1302. # copy features from background map
  1303. self.copyIds = digitClass.SelectLinesFromBackgroundMap(pos1, pos2)
  1304. if len(self.copyIds) > 0:
  1305. color = UserSettings.Get(group='vdigit', key='symbol',
  1306. subkey=['highlight', 'color'])
  1307. colorStr = str(color[0]) + ":" + \
  1308. str(color[1]) + ":" + \
  1309. str(color[2]) + ":"
  1310. dVectTmp = ['d.vect',
  1311. 'map=%s' % UserSettings.Get(group='vdigit', key='backgroundMap', subkey='value'),
  1312. 'cats=%s' % utils.ListOfCatsToRange(self.copyIds),
  1313. '-i',
  1314. 'color=%s' % colorStr,
  1315. 'fcolor=%s' % colorStr,
  1316. 'type=point,line,boundary,centroid',
  1317. 'width=2']
  1318. self.layerTmp = self.Map.AddLayer(type='vector',
  1319. name=globalvar.QUERYLAYER,
  1320. command=dVectTmp)
  1321. self.UpdateMap(render=True, renderVector=False)
  1322. else:
  1323. self.UpdateMap(render=False, renderVector=False)
  1324. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1325. # select lines to be labeled
  1326. pos1 = self.polycoords[0]
  1327. pos2 = self.polycoords[1]
  1328. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1329. digitClass.GetSelectType())
  1330. if nselected > 0:
  1331. # highlight selected features
  1332. self.UpdateMap(render=False)
  1333. self.DrawLines(pdc=self.pdcTmp) # redraw temp line
  1334. else:
  1335. self.UpdateMap(render=False, renderVector=False)
  1336. elif digitToolbar.GetAction() == "connectLine":
  1337. if len(digitClass.driver.GetSelected()) > 0:
  1338. self.UpdateMap(render=False)
  1339. elif self.dragid != None:
  1340. # end drag of overlay decoration
  1341. if self.overlays.has_key(self.dragid):
  1342. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1343. self.dragid = None
  1344. self.currtxtid = None
  1345. self.Update()
  1346. event.Skip()
  1347. def OnButtonDClick(self, event):
  1348. """
  1349. Mouse button double click
  1350. """
  1351. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1352. self.mouse["use"])
  1353. if self.mouse["use"] == "measure":
  1354. # measure
  1355. self.ClearLines(pdc=self.pdcTmp)
  1356. self.polycoords = []
  1357. self.mouse['use'] = 'pointer'
  1358. self.mouse['box'] = 'point'
  1359. self.mouse['end'] = [0, 0]
  1360. self.Refresh()
  1361. self.SetCursor(self.parent.cursors["default"])
  1362. elif self.mouse["use"] == "profile":
  1363. # profile
  1364. pass
  1365. # self.pdc.ClearId(self.lineid)
  1366. # self.pdc.ClearId(self.plineid)
  1367. # print 'coordinates: ',self.polycoords
  1368. # self.polycoords = []
  1369. # self.mouse['begin'] = self.mouse['end'] = [0, 0]
  1370. # self.Refresh()
  1371. elif self.mouse['use'] == 'pointer' and self.parent.toolbars['vdigit']:
  1372. # digitization tool
  1373. pass
  1374. else:
  1375. # select overlay decoration options dialog
  1376. clickposition = event.GetPositionTuple()[:]
  1377. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1378. if idlist == []:
  1379. return
  1380. self.dragid = idlist[0]
  1381. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1382. if self.dragid > 100:
  1383. self.currtxtid = self.dragid
  1384. self.parent.OnAddText(None)
  1385. elif self.dragid == 0:
  1386. self.parent.OnAddBarscale(None)
  1387. elif self.dragid == 1:
  1388. self.parent.OnAddLegend(None)
  1389. event.Skip()
  1390. def OnRightDown(self, event):
  1391. """
  1392. Right mouse button pressed
  1393. """
  1394. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1395. self.mouse["use"])
  1396. x,y = event.GetPositionTuple()[:]
  1397. l = self.pdc.FindObjects(x=x, y=y, radius=self.hitradius)
  1398. if not l:
  1399. return
  1400. id = l[0]
  1401. if id != 99:
  1402. if self.pdc.GetIdGreyedOut(id) == True:
  1403. self.pdc.SetIdGreyedOut(id, False)
  1404. else:
  1405. self.pdc.SetIdGreyedOut(id, True)
  1406. r = self.pdc.GetIdBounds(id)
  1407. r.Inflate(4,4)
  1408. self.RefreshRect(r, False)
  1409. digitToolbar = self.parent.toolbars['vdigit']
  1410. if digitToolbar:
  1411. digitClass = self.parent.digit
  1412. # digitization tool (confirm action)
  1413. if digitToolbar.GetAction() in ["moveLine", "moveVertex"] and \
  1414. hasattr(self, "moveBegin"):
  1415. pTo = self.Pixel2Cell(event.GetPositionTuple())
  1416. pFrom = self.moveCoords
  1417. move = (pTo[0]-pFrom[0], pTo[1]-pFrom[1])
  1418. if digitToolbar.GetAction() == "moveLine":
  1419. # move line
  1420. if digitClass.MoveSelectedLines(move) < 0:
  1421. return
  1422. elif digitToolbar.GetAction() == "moveVertex":
  1423. # move vertex
  1424. if digitClass.MoveSelectedVertex(pFrom, move) < 0:
  1425. return
  1426. del self.moveBegin
  1427. del self.moveCoords
  1428. del self.moveIds
  1429. event.Skip()
  1430. def OnRightUp(self, event):
  1431. """
  1432. Right mouse button released
  1433. """
  1434. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1435. self.mouse["use"])
  1436. digitToolbar = self.parent.toolbars['vdigit']
  1437. if digitToolbar:
  1438. digitClass = self.parent.digit
  1439. # digitization tool (confirm action)
  1440. if digitToolbar.GetAction() == "addLine" and \
  1441. digitToolbar.GetAction('type') in ["line", "boundary"]:
  1442. # -> add new line / boundary
  1443. try:
  1444. map = digitToolbar.GetLayer().GetName()
  1445. except:
  1446. map = None
  1447. wx.MessageBox(parent=self,
  1448. message=_("No vector map selected for editing."),
  1449. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1450. if map:
  1451. # mapcoords = []
  1452. # xy -> EN
  1453. # for coord in self.polycoords:
  1454. # mapcoords.append(self.Pixel2Cell(coord))
  1455. if digitToolbar.GetAction('type') == 'line':
  1456. line = True
  1457. else:
  1458. line = False
  1459. if len(self.polycoords) < 2: # ignore 'one-point' lines
  1460. return
  1461. if digitClass.AddLine(map, line, self.polycoords) < 0:
  1462. return
  1463. position = self.Cell2Pixel(self.polycoords[-1])
  1464. self.polycoords = []
  1465. self.UpdateMap(render=False)
  1466. # add new record into atribute table
  1467. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') is True:
  1468. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  1469. position[1] + self.dialogOffset))
  1470. # select attributes based on layer and category
  1471. cats = {}
  1472. cats[UserSettings.Get(group='vdigit', key="layer", subkey='value')] = \
  1473. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  1474. addRecordDlg = dbm.DisplayAttributesDialog(parent=self, map=map,
  1475. cats=cats,
  1476. pos=posWindow,
  1477. action="add")
  1478. if addRecordDlg.mapDBInfo and \
  1479. addRecordDlg.ShowModal() == wx.ID_OK:
  1480. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1481. for sql in addRecordDlg.GetSQLString():
  1482. sqlfile.file.write(sql + ";\n")
  1483. sqlfile.file.flush()
  1484. executeCommand = gcmd.Command(cmd=["db.execute",
  1485. "--q",
  1486. "input=%s" % sqlfile.name])
  1487. elif digitToolbar.GetAction() == "deleteLine":
  1488. # -> delete selected vector features
  1489. if digitClass.DeleteSelectedLines() < 0:
  1490. return
  1491. elif digitToolbar.GetAction() == "splitLine":
  1492. # split line
  1493. if digitClass.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1494. return
  1495. elif digitToolbar.GetAction() == "addVertex":
  1496. # add vertex
  1497. if digitClass.AddVertex(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1498. return
  1499. elif digitToolbar.GetAction() == "removeVertex":
  1500. # remove vertex
  1501. if digitClass.RemoveVertex(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1502. return
  1503. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1504. try:
  1505. if digitToolbar.GetAction() == 'copyCats':
  1506. if digitClass.CopyCats(self.copyCatsList,
  1507. self.copyCatsIds, copyAttrb=False) < 0:
  1508. return
  1509. else:
  1510. if digitClass.CopyCats(self.copyCatsList,
  1511. self.copyCatsIds, copyAttrb=True) < 0:
  1512. return
  1513. del self.copyCatsList
  1514. del self.copyCatsIds
  1515. except AttributeError:
  1516. pass
  1517. elif digitToolbar.GetAction() == "editLine" and hasattr(self, "moveBegin"):
  1518. line = digitClass.driver.GetSelected()
  1519. if digitClass.EditLine(line, self.polycoords) < 0:
  1520. return
  1521. del self.moveBegin
  1522. del self.moveCoords
  1523. del self.moveIds
  1524. elif digitToolbar.GetAction() == "flipLine":
  1525. if digitClass.FlipLine() < 0:
  1526. return
  1527. elif digitToolbar.GetAction() == "mergeLine":
  1528. if digitClass.MergeLine() < 0:
  1529. return
  1530. elif digitToolbar.GetAction() == "breakLine":
  1531. if digitClass.BreakLine() < 0:
  1532. return
  1533. elif digitToolbar.GetAction() == "snapLine":
  1534. if digitClass.SnapLine() < 0:
  1535. return
  1536. elif digitToolbar.GetAction() == "connectLine":
  1537. if len(digitClass.driver.GetSelected()) > 1:
  1538. if digitClass.ConnectLine() < 0:
  1539. return
  1540. elif digitToolbar.GetAction() == "copyLine":
  1541. if digitClass.CopyLine(self.copyIds) < 0:
  1542. return
  1543. del self.copyIds
  1544. if self.layerTmp:
  1545. self.Map.DeleteLayer(self.layerTmp)
  1546. self.UpdateMap(render=True, renderVector=False)
  1547. del self.layerTmp
  1548. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1549. pos1 = self.polycoords[0]
  1550. pos2 = self.polycoords[1]
  1551. selected = digitClass.driver.GetSelected()
  1552. dlg = VDigitZBulkDialog(parent=self, title=_("Z bulk-labeling dialog"),
  1553. nselected=len(selected))
  1554. if dlg.ShowModal() == wx.ID_OK:
  1555. if digitClass.ZBulkLine(pos1, pos2, dlg.value.GetValue(),
  1556. dlg.step.GetValue()) < 0:
  1557. return
  1558. self.UpdateMap(render=False, renderVector=True)
  1559. elif digitToolbar.GetAction() == "typeConv":
  1560. # -> feature type conversion
  1561. # - point <-> centroid
  1562. # - line <-> boundary
  1563. if digitClass.TypeConvForSelectedLines() < 0:
  1564. return
  1565. if digitToolbar.GetAction() != "addLine":
  1566. # unselect and re-render
  1567. digitClass.driver.SetSelected([])
  1568. self.polycoords = []
  1569. self.UpdateMap(render=False)
  1570. event.Skip()
  1571. def OnMiddleDown(self, event):
  1572. """Middle mouse button pressed"""
  1573. digitToolbar = self.parent.toolbars['vdigit']
  1574. # digitization tool
  1575. if self.mouse["use"] == "pointer" and digitToolbar:
  1576. digitClass = self.parent.digit
  1577. if (digitToolbar.GetAction() == "addLine" and digitToolbar.GetAction('type') in ["line", "boundary"]) or \
  1578. digitToolbar.GetAction() == "editLine":
  1579. # add line or boundary -> remove last point from the line
  1580. try:
  1581. removed = self.polycoords.pop()
  1582. Debug.msg(4, "BufferedWindow.OnMiddleDown(): polycoords_poped=%s" % \
  1583. [removed,])
  1584. self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
  1585. except:
  1586. pass
  1587. if digitToolbar.GetAction() == "editLine":
  1588. # remove last vertex & line
  1589. if len(self.moveIds) > 1:
  1590. self.moveIds.pop()
  1591. self.UpdateMap(render=False, renderVector=False)
  1592. elif digitToolbar.GetAction() in ["deleteLine", "moveLine", "splitLine",
  1593. "addVertex", "removeVertex", "moveVertex",
  1594. "copyCats", "flipLine", "mergeLine",
  1595. "snapLine", "connectLine", "copyLine",
  1596. "queryLine", "breakLine", "typeConv"]:
  1597. # varios tools -> unselected selected features
  1598. digitClass.driver.SetSelected([])
  1599. if digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  1600. hasattr(self, "moveBegin"):
  1601. del self.moveBegin
  1602. del self.moveCoords
  1603. del self.moveIds
  1604. elif digitToolbar.GetAction() == "copyCats":
  1605. try:
  1606. del self.copyCatsList
  1607. del self.copyCatsIds
  1608. except AttributeError:
  1609. pass
  1610. elif digitToolbar.GetAction() == "copyLine":
  1611. del self.copyIds
  1612. if self.layerTmp:
  1613. self.Map.DeleteLayer(self.layerTmp)
  1614. self.UpdateMap(render=True, renderVector=False)
  1615. del self.layerTmp
  1616. self.polycoords = []
  1617. self.UpdateMap(render=False) # render vector
  1618. elif digitToolbar.GetAction() == "zbulkLine":
  1619. # reset polyline
  1620. self.polycoords = []
  1621. digitClass.driver.SetSelected([])
  1622. self.UpdateMap(render=False)
  1623. def OnMouseMoving(self, event):
  1624. """Motion event and no mouse buttons were pressed"""
  1625. digitToolbar = self.parent.toolbars['vdigit']
  1626. if self.mouse["use"] == "pointer" and digitToolbar:
  1627. digitClass = self.parent.digit
  1628. self.mouse['end'] = event.GetPositionTuple()[:]
  1629. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  1630. (self.mouse['end'][0], self.mouse['end'][1]))
  1631. if digitToolbar.GetAction() == "addLine" and digitToolbar.GetAction('type') in ["line", "boundary"]:
  1632. if len(self.polycoords) > 0:
  1633. self.MouseDraw(pdc=self.pdcTmp, begin=self.Cell2Pixel(self.polycoords[-1]))
  1634. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] \
  1635. and hasattr(self, "moveBegin"):
  1636. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  1637. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  1638. self.moveBegin[0] += dx
  1639. self.moveBegin[1] += dy
  1640. if len(self.moveIds) > 0:
  1641. # draw lines on new position
  1642. if digitToolbar.GetAction() == "moveLine":
  1643. # move line
  1644. for id in self.moveIds:
  1645. self.pdcVector.TranslateId(id, dx, dy)
  1646. elif digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1647. # move vertex ->
  1648. # (vertex, left vertex, left line,
  1649. # right vertex, right line)
  1650. # do not draw static lines
  1651. if digitToolbar.GetAction() == "moveVertex":
  1652. self.polycoords = []
  1653. self.pdcVector.TranslateId(self.moveIds[0], dx, dy)
  1654. if self.moveIds[1] > 0: # previous vertex
  1655. x, y = self.Pixel2Cell(self.pdcVector.GetIdBounds(self.moveIds[1])[0:2])
  1656. self.pdcVector.RemoveId(self.moveIds[1]+1)
  1657. self.polycoords.append((x, y))
  1658. x, y = self.Pixel2Cell(self.pdcVector.GetIdBounds(self.moveIds[0])[0:2])
  1659. self.polycoords.append((x, y))
  1660. if self.moveIds[2] > 0: # next vertex
  1661. x, y = self.Pixel2Cell(self.pdcVector.GetIdBounds(self.moveIds[2])[0:2])
  1662. self.pdcVector.RemoveId(self.moveIds[2]-1)
  1663. self.polycoords.append((x, y))
  1664. self.ClearLines(pdc=self.pdcTmp)
  1665. self.DrawLines(pdc=self.pdcTmp)
  1666. else: # edit line
  1667. try:
  1668. if self.moveIds[-1] > 0: # previous vertex
  1669. self.MouseDraw(pdc=self.pdcTmp,
  1670. begin=self.Cell2Pixel(self.polycoords[-1]))
  1671. except: # no line
  1672. self.moveIds = []
  1673. self.polycoords = []
  1674. self.Refresh() # TODO: use RefreshRect()
  1675. self.mouse['begin'] = self.mouse['end']
  1676. elif digitToolbar.GetAction() == "zbulkLine":
  1677. if len(self.polycoords) == 1:
  1678. # draw mouse moving
  1679. self.MouseDraw(self.pdcTmp)
  1680. event.Skip()
  1681. def ClearLines(self, pdc=None):
  1682. """
  1683. Clears temporary drawn lines from PseudoDC
  1684. """
  1685. if not pdc:
  1686. return
  1687. exit = True
  1688. try:
  1689. pdc.ClearId(self.lineid)
  1690. pdc.RemoveId(self.lineid)
  1691. except:
  1692. exit = False
  1693. try:
  1694. pdc.ClearId(self.plineid)
  1695. pdc.RemoveId(self.plineid)
  1696. except:
  1697. exit = False
  1698. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1699. (self.lineid, self.plineid))
  1700. self.Refresh()
  1701. return exit
  1702. def Pixel2Cell(self, (x, y)):
  1703. """
  1704. Convert image coordinates to real word coordinates
  1705. Input : int x, int y
  1706. Output: float x, float y
  1707. """
  1708. try:
  1709. x = int(x)
  1710. y = int(y)
  1711. except:
  1712. return None
  1713. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1714. res = self.Map.region["ewres"]
  1715. else:
  1716. res = self.Map.region["nsres"]
  1717. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1718. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1719. east = w + x * res
  1720. north = n - y * res
  1721. # extent does not correspond with whole map canvas area...
  1722. # east = self.Map.region['w'] + x * self.Map.region["ewres"]
  1723. # north = self.Map.region['n'] - y * self.Map.region["nsres"]
  1724. return (east, north)
  1725. def Cell2Pixel(self, (east, north)):
  1726. """
  1727. Convert real word coordinates to image coordinates
  1728. """
  1729. try:
  1730. east = float(east)
  1731. north = float(north)
  1732. except:
  1733. return None
  1734. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1735. res = self.Map.region["ewres"]
  1736. else:
  1737. res = self.Map.region["nsres"]
  1738. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1739. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1740. # x = int((east - w) / res)
  1741. # y = int((n - north) / res)
  1742. x = (east - w) / res
  1743. y = (n - north) / res
  1744. return (x, y)
  1745. def Zoom(self, begin, end, zoomtype):
  1746. """
  1747. Calculates new region while (un)zoom/pan-ing
  1748. """
  1749. x1, y1 = begin
  1750. x2, y2 = end
  1751. newreg = {}
  1752. # threshold - too small squares do not make sense
  1753. # can only zoom to windows of > 5x5 screen pixels
  1754. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1755. if x1 > x2:
  1756. x1, x2 = x2, x1
  1757. if y1 > y2:
  1758. y1, y2 = y2, y1
  1759. # zoom in
  1760. if zoomtype > 0:
  1761. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1762. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1763. # zoom out
  1764. elif zoomtype < 0:
  1765. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1766. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1767. (self.Map.width - x2),
  1768. self.Map.height + 2 * \
  1769. (self.Map.height - y2)))
  1770. # pan
  1771. elif zoomtype == 0:
  1772. dx = x1 - x2
  1773. dy = y1 - y2
  1774. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1775. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1776. self.Map.height + dy))
  1777. # if new region has been calculated, set the values
  1778. if newreg != {}:
  1779. # calculate new center point and display resolution
  1780. self.Map.region['center_easting'] = newreg['w'] + \
  1781. (newreg['e'] - newreg['w']) / 2
  1782. self.Map.region['center_northing'] = newreg['s'] + \
  1783. (newreg['n'] - newreg['s']) / 2
  1784. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  1785. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  1786. self.Map.AlignExtentFromDisplay()
  1787. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1788. self.Map.region['e'], self.Map.region['w'])
  1789. if self.redrawAll is False:
  1790. self.redrawAll = True
  1791. def ZoomBack(self):
  1792. """
  1793. Zoom to previous extents in zoomhistory list
  1794. """
  1795. zoom = []
  1796. if len(self.zoomhistory) > 1:
  1797. self.zoomhistory.pop()
  1798. zoom = self.zoomhistory[len(self.zoomhistory)-1]
  1799. # (n, s, e, w)
  1800. if zoom:
  1801. # zoom to selected region
  1802. self.Map.region['center_easting'] = zoom[3] + \
  1803. (zoom[2] - zoom[3]) / 2
  1804. self.Map.region['center_northing'] = zoom[1] + \
  1805. (zoom[0] - zoom[1]) / 2
  1806. self.Map.region["ewres"] = (zoom[2] - zoom[3]) / self.Map.width
  1807. self.Map.region["nsres"] = (zoom[0] - zoom[1]) / self.Map.height
  1808. self.Map.AlignExtentFromDisplay()
  1809. # update map
  1810. self.UpdateMap()
  1811. # update statusbar
  1812. self.parent.StatusbarUpdate()
  1813. def ZoomHistory(self, n, s, e, w):
  1814. """
  1815. Manages a list of last 10 zoom extents
  1816. Return removed history item if exists
  1817. """
  1818. removed = None
  1819. self.zoomhistory.append((n,s,e,w))
  1820. if len(self.zoomhistory) > 10:
  1821. removed = self.zoomhistory.pop(0)
  1822. if removed:
  1823. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1824. (self.zoomhistory, removed))
  1825. else:
  1826. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1827. (self.zoomhistory))
  1828. return removed
  1829. def OnZoomToMap(self, event):
  1830. """
  1831. Set display extents to match selected raster (including NULLs)
  1832. or vector map.
  1833. """
  1834. self.ZoomToMap()
  1835. def OnZoomToRaster(self, event):
  1836. """
  1837. Set display extents to match selected raster map (ignore NULLs)
  1838. """
  1839. self.ZoomToMap(zoom=True)
  1840. def ZoomToMap(self, zoom=False):
  1841. """
  1842. Set display extents to match selected raster
  1843. or vector map.
  1844. """
  1845. zoomreg = {}
  1846. layer = self.GetSelectedLayer()
  1847. if layer is None:
  1848. return
  1849. Debug.msg (3, "BufferedWindow.ZoomToMap(): layer=%s, type=%s" % \
  1850. (layer.name, layer.type))
  1851. # selected layer must be a valid map
  1852. if layer.type in ('raster', 'rgb', 'his', 'shaded', 'arrow'):
  1853. if layer.type == 'raster':
  1854. self.Map.region = self.Map.GetRegion(rast="%s" % layer.name)
  1855. else:
  1856. self.Map.region = self.Map.GetRegion(rast="%s" % layer.name)
  1857. elif layer.type in ('vector', 'thememap', 'themechart'):
  1858. if self.parent.digit and layer.name == self.parent.digit.map and \
  1859. self.parent.digit.type == 'vdigit':
  1860. w, s, b, e, n, t = self.parent.digit.driver.GetMapBoundingBox()
  1861. self.Map.region = self.Map.GetRegion(n=n, s=s, w=w, e=e)
  1862. else:
  1863. self.Map.region = self.Map.GetRegion(vect="%s" % layer.name)
  1864. else:
  1865. return
  1866. ### self.Map.SetRegion()
  1867. ### self.Map.AlignExtentFromDisplay()
  1868. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1869. self.Map.region['e'], self.Map.region['w'])
  1870. self.UpdateMap()
  1871. self.parent.StatusbarUpdate()
  1872. def ZoomToWind(self, event):
  1873. """
  1874. Set display geometry to match computational
  1875. region settings (set with g.region)
  1876. """
  1877. self.Map.region = self.Map.GetRegion()
  1878. ### self.Map.SetRegion(windres=True)
  1879. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1880. self.Map.region['e'], self.Map.region['w'])
  1881. self.UpdateMap()
  1882. self.parent.StatusbarUpdate()
  1883. def ZoomToDefault(self, event):
  1884. """Set display geometry to match default
  1885. region settings"""
  1886. self.Map.region = self.Map.GetRegion(default=True)
  1887. self.Map.AdjustRegion() # aling region extent to the display
  1888. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1889. self.Map.region['e'], self.Map.region['w'])
  1890. self.UpdateMap()
  1891. self.parent.StatusbarUpdate()
  1892. def DisplayToWind(self, event):
  1893. """
  1894. Set computational region (WIND file) to
  1895. match display extents
  1896. """
  1897. tmpreg = os.getenv("GRASS_REGION")
  1898. os.unsetenv("GRASS_REGION")
  1899. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1900. # for user to set explicitly with g.region
  1901. new = self.Map.AlignResolution()
  1902. cmdRegion = ["g.region", "--o",
  1903. "n=%f" % new['n'],
  1904. "s=%f" % new['s'],
  1905. "e=%f" % new['e'],
  1906. "w=%f" % new['w'],
  1907. "rows=%f" % new['rows'],
  1908. "cols=%f" % new['cols']]
  1909. p = gcmd.Command(cmdRegion)
  1910. if tmpreg:
  1911. os.environ["GRASS_REGION"] = tmpreg
  1912. def ZoomToSaved(self, event):
  1913. """
  1914. Set display geometry to match extents in
  1915. saved region file
  1916. """
  1917. zoomreg = {}
  1918. dlg = gdialogs.SavedRegion(self, wx.ID_ANY, _("Zoom to saved region extents"),
  1919. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1920. style=wx.DEFAULT_DIALOG_STYLE,
  1921. loadsave='load')
  1922. if dlg.ShowModal() == wx.ID_CANCEL:
  1923. dlg.Destroy()
  1924. return
  1925. wind = dlg.wind
  1926. p = gcmd.Command (["g.region",
  1927. "-ugp", "region=%s" % wind])
  1928. if p.returncode == 0:
  1929. output = p.ReadStdOutput()
  1930. for line in output:
  1931. line = line.strip()
  1932. if '=' in line: key,val = line.split('=')
  1933. zoomreg[key] = float(val)
  1934. self.Map.region['n'] = zoomreg['n']
  1935. self.Map.region['s'] = zoomreg['s']
  1936. self.Map.region['e'] = zoomreg['e']
  1937. self.Map.region['w'] = zoomreg['w']
  1938. self.ZoomHistory(self.Map.region['n'],self.Map.region['s'],self.Map.region['e'],self.Map.region['w'])
  1939. self.UpdateMap()
  1940. dlg.Destroy()
  1941. def SaveDisplayRegion(self, event):
  1942. """
  1943. Save display extents to named region file.
  1944. """
  1945. dlg = gdialogs.SavedRegion(self, wx.ID_ANY, "Save display extents to region file",
  1946. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1947. style=wx.DEFAULT_DIALOG_STYLE,
  1948. loadsave='save')
  1949. if dlg.ShowModal() == wx.ID_CANCEL:
  1950. dlg.Destroy()
  1951. return
  1952. wind = dlg.wind
  1953. # test to see if it already exists and ask permission to overwrite
  1954. windpath = os.path.join(self.Map.env["GISDBASE"], self.Map.env["LOCATION_NAME"],
  1955. self.Map.env["MAPSET"],"windows",wind)
  1956. if windpath and not os.path.exists(windpath):
  1957. self.SaveRegion(wind)
  1958. elif windpath and os.path.exists(windpath):
  1959. overwrite = wx.MessageBox(_("Region file <%s> already exists. "
  1960. "Do you want to overwrite it?") % (wind),
  1961. _("Warning"), wx.YES_NO)
  1962. if (overwrite == wx.YES):
  1963. self.SaveRegion(wind)
  1964. else:
  1965. pass
  1966. dlg.Destroy()
  1967. def SaveRegion(self, wind):
  1968. """Save region settings"""
  1969. new = self.Map.AlignResolution()
  1970. cmdRegion = ["g.region",
  1971. "-u",
  1972. "n=%f" % new['n'],
  1973. "s=%f" % new['s'],
  1974. "e=%f" % new['e'],
  1975. "w=%f" % new['w'],
  1976. "rows=%d" % new['rows'],
  1977. "cols=%d" % new['cols'],
  1978. "save=%s" % wind,
  1979. "--o"]
  1980. tmpreg = os.getenv("GRASS_REGION")
  1981. os.unsetenv("GRASS_REGION")
  1982. p = gcmd.Command(cmdRegion)
  1983. if tmpreg:
  1984. os.environ["GRASS_REGION"] = tmpreg
  1985. def Distance(self, beginpt, endpt, screen=True):
  1986. """Calculete distance
  1987. LL-locations not supported
  1988. @todo Use m.distance
  1989. @param beginpt first point
  1990. @param endpt second point
  1991. @param screen True for screen coordinates otherwise EN
  1992. """
  1993. x1, y1 = beginpt
  1994. x2, y2 = endpt
  1995. if screen:
  1996. dEast = (x2 - x1) * self.Map.region["ewres"]
  1997. dNorth = (y2 - y1) * self.Map.region["nsres"]
  1998. else:
  1999. dEast = (x2 - x1)
  2000. dNorth = (y2 - y1)
  2001. return (math.sqrt(math.pow((dEast),2) + math.pow((dNorth),2)), (dEast, dNorth))
  2002. class MapFrame(wx.Frame):
  2003. """
  2004. Main frame for map display window. Drawing takes place in child double buffered
  2005. drawing window.
  2006. """
  2007. def __init__(self, parent=None, id=wx.ID_ANY, title=_("GRASS GIS - Map display"),
  2008. pos=wx.DefaultPosition, size=wx.DefaultSize,
  2009. style=wx.DEFAULT_FRAME_STYLE, toolbars=["map"],
  2010. tree=None, notebook=None, gismgr=None, page=None,
  2011. Map=None, auimgr=None):
  2012. """
  2013. Main map display window with toolbars, statusbar and
  2014. DrawWindow
  2015. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  2016. @param tree reference to layer tree
  2017. @param notebook control book ID in Layer Manager
  2018. @param gismgr Layer Manager panel
  2019. @param page notebook page with layer tree
  2020. @param Map instance of render.Map
  2021. """
  2022. wx.Frame.__init__(self, parent, id, title, pos, size, style)
  2023. self.gismanager = gismgr # GIS Manager object
  2024. self.Map = Map # instance of render.Map
  2025. self.tree = tree # GIS Manager layer tree object
  2026. self.page = page # Notebook page holding the layer tree
  2027. self.layerbook = notebook # GIS Manager layer tree notebook
  2028. self.parent = parent
  2029. #
  2030. # available cursors
  2031. #
  2032. self.cursors = {
  2033. # default: cross
  2034. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  2035. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  2036. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  2037. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  2038. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  2039. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  2040. }
  2041. #
  2042. # set the size & system icon
  2043. #
  2044. self.SetClientSize(size)
  2045. self.iconsize = (16, 16)
  2046. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  2047. #
  2048. # Fancy gui
  2049. #
  2050. # self._mgr = auimgr
  2051. self._mgr = wx.aui.AuiManager(self)
  2052. #
  2053. # Add toolbars
  2054. #
  2055. self.toolbars = { 'map' : None,
  2056. 'vdigit' : None,
  2057. 'georect' : None,
  2058. 'nviz' : None }
  2059. for toolb in toolbars:
  2060. self.AddToolbar(toolb)
  2061. #
  2062. # Add statusbar
  2063. #
  2064. self.statusbar = self.CreateStatusBar(number=3, style=0)
  2065. self.statusbar.SetStatusWidths([-5, -2, -1])
  2066. self.toggleStatus = wx.Choice(self.statusbar, wx.ID_ANY,
  2067. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  2068. self.toggleStatus.SetSelection(UserSettings.Get(group='display', key='statusbarMode', subkey='selection'))
  2069. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.toggleStatus)
  2070. # auto-rendering checkbox
  2071. self.autoRender = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  2072. label=_("Render"))
  2073. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.autoRender)
  2074. self.autoRender.SetValue(UserSettings.Get(group='display', key='autoRendering', subkey='enabled'))
  2075. self.autoRender.SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  2076. # show region
  2077. self.showRegion = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  2078. label=_("Show computational extent"))
  2079. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.showRegion)
  2080. self.showRegion.SetValue(False)
  2081. self.showRegion.Hide()
  2082. self.showRegion.SetToolTip(wx.ToolTip (_("Show/hide computational "
  2083. "region extent (set with g.region). "
  2084. "Display region drawn as a blue box inside the "
  2085. "computational region, "
  2086. "computational region inside a display region "
  2087. "as a red box).")))
  2088. # set resolution
  2089. self.compResolution = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  2090. label=_("Constrain display resolution to computational settings"))
  2091. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.compResolution)
  2092. self.compResolution.SetValue(UserSettings.Get(group='display', key='compResolution', subkey='enabled'))
  2093. self.compResolution.Hide()
  2094. self.compResolution.SetToolTip(wx.ToolTip (_("Constrain display resolution "
  2095. "to computational region settings. "
  2096. "Default value for new map displays can "
  2097. "be set up in 'User GUI settings' dialog.")))
  2098. # map scale
  2099. self.mapScale = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  2100. value="", style=wx.TE_PROCESS_ENTER,
  2101. size=(150, -1))
  2102. self.mapScale.Hide()
  2103. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.mapScale)
  2104. # on-render gauge
  2105. self.onRenderGauge = wx.Gauge(parent=self.statusbar, id=wx.ID_ANY,
  2106. range=0, style=wx.GA_HORIZONTAL)
  2107. self.onRenderGauge.Hide()
  2108. self.StatusbarReposition() # reposition statusbar
  2109. #
  2110. # Init map display (buffered DC & set default cursor)
  2111. #
  2112. self.MapWindow2D = BufferedWindow(self, id=wx.ID_ANY,
  2113. Map=self.Map, tree=self.tree, gismgr=self.gismanager)
  2114. # default is 2D display mode
  2115. self.MapWindow = self.MapWindow2D
  2116. self.MapWindow.Bind(wx.EVT_MOTION, self.OnMotion)
  2117. self.MapWindow.SetCursor(self.cursors["default"])
  2118. # used by Nviz (3D display mode)
  2119. self.MapWindow3D = None
  2120. #
  2121. # initialize region values
  2122. #
  2123. self.__InitDisplay()
  2124. #
  2125. # Bind various events
  2126. #
  2127. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  2128. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  2129. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  2130. #
  2131. # Update fancy gui style
  2132. #
  2133. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  2134. Dockable(False).BestSize((-1,-1)).
  2135. CloseButton(False).DestroyOnClose(True).
  2136. Layer(0))
  2137. self._mgr.Update()
  2138. #
  2139. # Init print module and classes
  2140. #
  2141. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  2142. #
  2143. # Current location information
  2144. #
  2145. self.projinfo = self.Map.ProjInfo()
  2146. #
  2147. # Initialization of digitization tool
  2148. #
  2149. self.digit = None
  2150. #
  2151. # Init zoom history
  2152. #
  2153. self.MapWindow.ZoomHistory(self.Map.region['n'],
  2154. self.Map.region['s'],
  2155. self.Map.region['e'],
  2156. self.Map.region['w'])
  2157. #
  2158. # Re-use dialogs
  2159. #
  2160. self.dialogs = {}
  2161. self.dialogs['attributes'] = None
  2162. self.dialogs['category'] = None
  2163. self.dialogs['barscale'] = None
  2164. self.dialogs['legend'] = None
  2165. self.decorationDialog = None # decoration/overlays
  2166. def AddToolbar(self, name):
  2167. """
  2168. Add defined toolbar to the window
  2169. Currently known toolbars are:
  2170. - map basic map toolbar
  2171. - digit vector digitizer
  2172. - georect georectifier
  2173. """
  2174. # default toolbar
  2175. if name == "map":
  2176. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  2177. self._mgr.AddPane(self.toolbars['map'].toolbar,
  2178. wx.aui.AuiPaneInfo().
  2179. Name("maptoolbar").Caption(_("Map Toolbar")).
  2180. ToolbarPane().Top().
  2181. LeftDockable(False).RightDockable(False).
  2182. BottomDockable(False).TopDockable(True).
  2183. CloseButton(False).Layer(2))
  2184. # vector digitizer
  2185. elif name == "vdigit":
  2186. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent=self, map=self.Map,
  2187. layerTree=self.tree,
  2188. log=self.gismanager.goutput)
  2189. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  2190. self._mgr.AddPane(self.toolbars['vdigit'].toolbar[toolRow],
  2191. wx.aui.AuiPaneInfo().
  2192. Name("vdigittoolbar" + str(toolRow)).Caption(_("Vector digitizer toolbar")).
  2193. ToolbarPane().Top().Row(toolRow + 1).
  2194. LeftDockable(False).RightDockable(False).
  2195. BottomDockable(False).TopDockable(True).
  2196. CloseButton(False).Layer(2))
  2197. # change mouse to draw digitized line
  2198. self.MapWindow.mouse['box'] = "point"
  2199. self.MapWindow.zoomtype = 0
  2200. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SOLID)
  2201. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SOLID)
  2202. # georectifier
  2203. elif name == "georect":
  2204. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  2205. self._mgr.AddPane(self.toolbars['georect'].toolbar,
  2206. wx.aui.AuiPaneInfo().
  2207. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  2208. ToolbarPane().Top().
  2209. LeftDockable(False).RightDockable(False).
  2210. BottomDockable(False).TopDockable(True).
  2211. CloseButton(False).Layer(2))
  2212. # nviz
  2213. elif name == "nviz":
  2214. import nviz
  2215. # check for GLCanvas and OpenGL
  2216. msg = None
  2217. if not nviz.haveGLCanvas:
  2218. msg = _("Unable to start Nviz. The GLCanvas class has not been "
  2219. "included with this build "
  2220. "of wxPython! Switching back to "
  2221. "2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  2222. if not nviz.haveOpenGL:
  2223. msg = _("Unable to start Nviz. The OpenGL package "
  2224. "was not found. You can get it "
  2225. "at http://PyOpenGL.sourceforge.net. "
  2226. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  2227. if not nviz.haveNviz:
  2228. msg = _("Unable to start Nviz. Python extension "
  2229. "for Nviz was not found or loaded properly. "
  2230. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  2231. if msg:
  2232. wx.MessageBox(parent=self,
  2233. message=msg,
  2234. caption=_("Error"))
  2235. return
  2236. #
  2237. # add Nviz toolbar and disable 2D display mode tools
  2238. #
  2239. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  2240. self.toolbars['map'].Enable2D(False)
  2241. #
  2242. # update layer tree (-> enable 3d-rasters)
  2243. #
  2244. self.tree.EnableItemType(type='3d-raster', enable=True)
  2245. #
  2246. # update status bar
  2247. #
  2248. self.toggleStatus.Enable(False)
  2249. #
  2250. # erase map window
  2251. #
  2252. self.MapWindow.EraseMap()
  2253. busy = wx.BusyInfo(message=_("Please wait, loading data..."),
  2254. parent=self)
  2255. wx.Yield()
  2256. #
  2257. # create GL window & NVIZ toolbar
  2258. #
  2259. if not self.MapWindow3D:
  2260. self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
  2261. Map=self.Map, tree=self.tree, gismgr=self.gismanager)
  2262. self.nvizToolWin = nviz.NvizToolWindow(self, id=wx.ID_ANY,
  2263. mapWindow=self.MapWindow3D)
  2264. self.MapWindow3D.OnPaint(None) # -> LoadData
  2265. busy.Destroy()
  2266. self.nvizToolWin.Show()
  2267. #
  2268. # switch from MapWindow to MapWindowGL
  2269. # add nviz toolbar
  2270. #
  2271. self._mgr.DetachPane(self.MapWindow2D)
  2272. self.MapWindow2D.Hide()
  2273. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  2274. Dockable(False).BestSize((-1,-1)).
  2275. CloseButton(False).DestroyOnClose(True).
  2276. Layer(0))
  2277. self._mgr.AddPane(self.toolbars['nviz'].toolbar,
  2278. wx.aui.AuiPaneInfo().
  2279. Name("nviztoolbar").Caption(_("Nviz toolbar")).
  2280. ToolbarPane().Top().Row(1).
  2281. LeftDockable(False).RightDockable(False).
  2282. BottomDockable(False).TopDockable(True).
  2283. CloseButton(False).Layer(2))
  2284. self.MapWindow = self.MapWindow3D
  2285. self.SetStatusText("", 0)
  2286. self._mgr.Update()
  2287. def RemoveToolbar (self, name):
  2288. """
  2289. Removes toolbar from the window
  2290. TODO: Only hide, activate by calling AddToolbar()
  2291. """
  2292. # cannot hide main toolbar
  2293. if name == "map":
  2294. return
  2295. elif name == "vdigit":
  2296. # TODO: not destroy only hide
  2297. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  2298. self._mgr.DetachPane (self.toolbars['vdigit'].toolbar[toolRow])
  2299. self.toolbars['vdigit'].toolbar[toolRow].Destroy()
  2300. else:
  2301. self._mgr.DetachPane (self.toolbars[name].toolbar)
  2302. self.toolbars[name].toolbar.Destroy()
  2303. self.toolbars[name] = None
  2304. if name == 'nviz':
  2305. # hide nviz tools
  2306. self.nvizToolWin.Hide()
  2307. # unload data
  2308. self.MapWindow3D.Reset()
  2309. # switch from MapWindowGL to MapWindow
  2310. self._mgr.DetachPane(self.MapWindow3D)
  2311. self.MapWindow3D.Hide()
  2312. self.MapWindow2D.Show()
  2313. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  2314. Dockable(False).BestSize((-1,-1)).
  2315. CloseButton(False).DestroyOnClose(True).
  2316. Layer(0))
  2317. self.MapWindow = self.MapWindow2D
  2318. #
  2319. # update layer tree (-> disable 3d-rasters)
  2320. #
  2321. self.tree.EnableItemType(type='3d-raster', enable=False)
  2322. self.toolbars['map'].combo.SetValue ("Tools")
  2323. self.toolbars['map'].Enable2D(True)
  2324. self.toggleStatus.Enable(True)
  2325. self._mgr.Update()
  2326. def __InitDisplay(self):
  2327. """
  2328. Initialize map display, set dimensions and map region
  2329. """
  2330. self.width, self.height = self.GetClientSize()
  2331. Debug.msg(2, "MapFrame.__InitDisplay():")
  2332. self.Map.ChangeMapSize(self.GetClientSize())
  2333. self.Map.region = self.Map.GetRegion() # g.region -upgc
  2334. # self.Map.SetRegion() # adjust region to match display window
  2335. def OnUpdateProgress(self, event):
  2336. """Update progress bar info"""
  2337. self.onRenderGauge.SetValue(event.value)
  2338. event.Skip()
  2339. def OnFocus(self, event):
  2340. """
  2341. Change choicebook page to match display.
  2342. Or set display for georectifying
  2343. """
  2344. if self.gismanager.georectifying:
  2345. # in georectifying session; display used to get get geographic
  2346. # coordinates for GCPs
  2347. self.OnPointer(event)
  2348. else:
  2349. # change bookcontrol page to page associated with display
  2350. if self.page:
  2351. pgnum = self.layerbook.GetPageIndex(self.page)
  2352. if pgnum > -1:
  2353. self.layerbook.SetSelection(pgnum)
  2354. event.Skip()
  2355. def OnMotion(self, event):
  2356. """
  2357. Mouse moved
  2358. Track mouse motion and update status bar
  2359. """
  2360. # update statusbar if required
  2361. if self.toggleStatus.GetSelection() == 0: # Coordinates
  2362. e, n = self.MapWindow.Pixel2Cell(event.GetPositionTuple())
  2363. if self.toolbars['vdigit'] and \
  2364. self.toolbars['vdigit'].GetAction() == 'addLine' and \
  2365. self.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
  2366. len(self.MapWindow.polycoords) > 0:
  2367. # for linear feature show segment and total length
  2368. distance_seg = self.MapWindow.Distance(self.MapWindow.polycoords[-1],
  2369. (e, n), screen=False)[0]
  2370. distance_tot = distance_seg
  2371. for idx in range(1, len(self.MapWindow.polycoords)):
  2372. distance_tot += self.MapWindow.Distance(self.MapWindow.polycoords[idx-1],
  2373. self.MapWindow.polycoords[idx],
  2374. screen=False )[0]
  2375. self.statusbar.SetStatusText("%.2f, %.2f (seg: %.2f; tot: %.2f)" % \
  2376. (e, n, distance_seg, distance_tot), 0)
  2377. else:
  2378. self.statusbar.SetStatusText("%.2f, %.2f" % (e, n), 0)
  2379. event.Skip()
  2380. def OnDraw(self, event):
  2381. """
  2382. Re-display current map composition
  2383. """
  2384. self.MapWindow.UpdateMap(render=False)
  2385. def OnRender(self, event):
  2386. """
  2387. Re-render map composition (each map layer)
  2388. """
  2389. # delete tmp map layers (queries)
  2390. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
  2391. for layer in qlayer:
  2392. self.Map.DeleteLayer(layer)
  2393. # deselect features in vdigit
  2394. if self.toolbars['vdigit'] and self.digit:
  2395. self.digit.driver.SetSelected([])
  2396. self.MapWindow.UpdateMap(render=True, renderVector=True)
  2397. else:
  2398. self.MapWindow.UpdateMap(render=True)
  2399. # update statusbar
  2400. self.StatusbarUpdate()
  2401. def OnPointer(self, event):
  2402. """Pointer button clicked"""
  2403. self.toolbars['map'].OnTool(event)
  2404. self.toolbars['map'].action['desc'] = ''
  2405. self.MapWindow.mouse['use'] = "pointer"
  2406. self.MapWindow.mouse['box'] = "point"
  2407. # change the cursor
  2408. if self.toolbars['vdigit']:
  2409. # digitization tool activated
  2410. self.MapWindow.SetCursor(self.cursors["cross"])
  2411. # reset mouse['box'] if needed
  2412. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  2413. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  2414. self.MapWindow.mouse['box'] = 'point'
  2415. else: # line, boundary
  2416. self.MapWindow.mouse['box'] = 'line'
  2417. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  2418. 'editLine', 'displayCats', 'displayAttrs',
  2419. 'copyCats']:
  2420. self.MapWindow.mouse['box'] = 'point'
  2421. else: # moveLine, deleteLine
  2422. self.MapWindow.mouse['box'] = 'box'
  2423. elif self.gismanager.georectifying:
  2424. self.MapWindow.SetCursor(self.cursors["cross"])
  2425. else:
  2426. self.MapWindow.SetCursor(self.cursors["default"])
  2427. def OnZoomIn(self, event):
  2428. """
  2429. Zoom in the map.
  2430. Set mouse cursor, zoombox attributes, and zoom direction
  2431. """
  2432. self.toolbars['map'].OnTool(event)
  2433. self.toolbars['map'].action['desc'] = ''
  2434. self.MapWindow.mouse['use'] = "zoom"
  2435. self.MapWindow.mouse['box'] = "box"
  2436. self.MapWindow.zoomtype = 1
  2437. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  2438. # change the cursor
  2439. self.MapWindow.SetCursor(self.cursors["cross"])
  2440. def OnZoomOut(self, event):
  2441. """
  2442. Zoom out the map.
  2443. Set mouse cursor, zoombox attributes, and zoom direction
  2444. """
  2445. self.toolbars['map'].OnTool(event)
  2446. self.toolbars['map'].action['desc'] = ''
  2447. self.MapWindow.mouse['use'] = "zoom"
  2448. self.MapWindow.mouse['box'] = "box"
  2449. self.MapWindow.zoomtype = -1
  2450. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  2451. # change the cursor
  2452. self.MapWindow.SetCursor(self.cursors["cross"])
  2453. def OnZoomBack(self, event):
  2454. """
  2455. Zoom last (previously stored position)
  2456. """
  2457. self.MapWindow.ZoomBack()
  2458. def OnPan(self, event):
  2459. """
  2460. Panning, set mouse to drag
  2461. """
  2462. self.toolbars['map'].OnTool(event)
  2463. self.toolbars['map'].action['desc'] = ''
  2464. self.MapWindow.mouse['use'] = "pan"
  2465. self.MapWindow.mouse['box'] = "pan"
  2466. self.MapWindow.zoomtype = 0
  2467. # change the cursor
  2468. self.MapWindow.SetCursor(self.cursors["hand"])
  2469. def OnErase(self, event):
  2470. """
  2471. Erase the canvas
  2472. """
  2473. self.MapWindow.EraseMap()
  2474. def OnZoomRegion(self, event):
  2475. """
  2476. Zoom to region
  2477. """
  2478. self.Map.getRegion()
  2479. self.Map.getResolution()
  2480. self.UpdateMap()
  2481. # event.Skip()
  2482. def OnAlignRegion(self, event):
  2483. """
  2484. Align region
  2485. """
  2486. if not self.Map.alignRegion:
  2487. self.Map.alignRegion = True
  2488. else:
  2489. self.Map.alignRegion = False
  2490. # event.Skip()
  2491. def OnToggleRender(self, event):
  2492. """Enable/disable auto-rendering"""
  2493. if self.autoRender.GetValue():
  2494. self.OnRender(None)
  2495. def OnToggleShowRegion(self, event):
  2496. """Show/Hide extent in map canvas"""
  2497. if self.showRegion.GetValue():
  2498. # show extent
  2499. self.MapWindow.regionCoords = []
  2500. else:
  2501. del self.MapWindow.regionCoords
  2502. # redraw map if auto-rendering is enabled
  2503. if self.autoRender.GetValue():
  2504. self.OnRender(None)
  2505. def OnToggleResolution(self, event):
  2506. """Use resolution of computation region settings
  2507. for redering image instead of display resolution"""
  2508. # redraw map if auto-rendering is enabled
  2509. if self.autoRender.GetValue():
  2510. self.OnRender(None)
  2511. def OnToggleStatus(self, event):
  2512. """Toggle status text"""
  2513. self.StatusbarUpdate()
  2514. def OnChangeMapScale(self, event):
  2515. """Map scale changed by user"""
  2516. scale = event.GetString()
  2517. try:
  2518. if scale[:2] != '1:':
  2519. raise ValueError
  2520. value = int(scale[2:])
  2521. except ValueError:
  2522. self.mapScale.SetValue('1:' + str(int(self.mapScaleValue)))
  2523. return
  2524. dEW = value * (self.Map.region['cols'] / self.ppm[0])
  2525. dNS = value * (self.Map.region['rows'] / self.ppm[1])
  2526. self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2
  2527. self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2
  2528. self.Map.region['w'] = self.Map.region['center_easting'] - dEW / 2
  2529. self.Map.region['e'] = self.Map.region['center_easting'] + dEW / 2
  2530. # add to zoom history
  2531. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2532. self.Map.region['e'], self.Map.region['w'])
  2533. # redraw a map
  2534. self.MapWindow.UpdateMap()
  2535. def StatusbarUpdate(self):
  2536. """Update statusbar content"""
  2537. self.showRegion.Hide()
  2538. self.compResolution.Hide()
  2539. self.mapScale.Hide()
  2540. self.mapScaleValue = self.ppm = None
  2541. if self.toggleStatus.GetSelection() == 0: # Coordinates
  2542. self.statusbar.SetStatusText("", 0)
  2543. # enable long help
  2544. self.StatusbarEnableLongHelp()
  2545. elif self.toggleStatus.GetSelection() == 1: # Extent
  2546. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f" %
  2547. (self.Map.region["w"], self.Map.region["e"],
  2548. self.Map.region["s"], self.Map.region["n"]), 0)
  2549. # enable long help
  2550. self.StatusbarEnableLongHelp()
  2551. elif self.toggleStatus.GetSelection() == 2: # Comp. region
  2552. compregion = self.Map.GetRegion()
  2553. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f (%.2f, %.2f)" %
  2554. (compregion["w"], compregion["e"],
  2555. compregion["s"], compregion["n"],
  2556. compregion["ewres"], compregion["nsres"]), 0)
  2557. # enable long help
  2558. self.StatusbarEnableLongHelp()
  2559. elif self.toggleStatus.GetSelection() == 3: # Show comp. extent
  2560. self.statusbar.SetStatusText("", 0)
  2561. self.showRegion.Show()
  2562. # disable long help
  2563. self.StatusbarEnableLongHelp(False)
  2564. elif self.toggleStatus.GetSelection() == 4: # Display mode
  2565. self.statusbar.SetStatusText("", 0)
  2566. self.compResolution.Show()
  2567. # disable long help
  2568. self.StatusbarEnableLongHelp(False)
  2569. elif self.toggleStatus.GetSelection() == 5: # Display geometry
  2570. self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  2571. (self.Map.region["rows"], self.Map.region["cols"],
  2572. self.Map.region["nsres"], self.Map.region["ewres"]), 0)
  2573. # enable long help
  2574. self.StatusbarEnableLongHelp()
  2575. elif self.toggleStatus.GetSelection() == 6: # Map scale
  2576. # TODO: need to be fixed...
  2577. ### screen X region problem
  2578. ### user should specify ppm
  2579. dc = wx.ScreenDC()
  2580. dpSizePx = wx.DisplaySize() # display size in pixels
  2581. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  2582. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  2583. sysPpi = dc.GetPPI()
  2584. comPpi = (dpSizePx[0] / dpSizeIn[0],
  2585. dpSizePx[1] / dpSizeIn[1])
  2586. ppi = comPpi # pixel per inch
  2587. self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  2588. (ppi[1] / 2.54) * 100)
  2589. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
  2590. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  2591. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  2592. dpSizeIn[0], dpSizeIn[1],
  2593. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  2594. self.ppm[0], self.ppm[1]))
  2595. region = self.Map.region
  2596. heightCm = region['rows'] / self.ppm[1] * 100
  2597. widthCm = region['cols'] / self.ppm[0] * 100
  2598. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
  2599. (widthCm, heightCm))
  2600. xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
  2601. yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
  2602. scale = (xscale + yscale) / 2
  2603. Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
  2604. (xscale, yscale, scale))
  2605. self.statusbar.SetStatusText("")
  2606. self.mapScale.SetValue("1:%ld" % scale)
  2607. self.mapScaleValue = scale
  2608. self.mapScale.Show()
  2609. # disable long help
  2610. self.StatusbarEnableLongHelp(False)
  2611. else:
  2612. self.statusbar.SetStatusText("", 1)
  2613. def StatusbarEnableLongHelp(self, enable=True):
  2614. """Enable/disable toolbars long help"""
  2615. for toolbar in self.toolbars.itervalues():
  2616. if toolbar:
  2617. toolbar.EnableLongHelp(enable)
  2618. def StatusbarReposition(self):
  2619. """Reposition checkbox in statusbar"""
  2620. # reposition checkbox
  2621. widgets = [(0, self.showRegion),
  2622. (0, self.compResolution),
  2623. (0, self.mapScale),
  2624. (0, self.onRenderGauge),
  2625. (1, self.toggleStatus),
  2626. (2, self.autoRender)]
  2627. for idx, win in widgets:
  2628. rect = self.statusbar.GetFieldRect(idx)
  2629. if idx == 0: # show region / mapscale / process bar
  2630. # -> size
  2631. wWin, hWin = win.GetBestSize()
  2632. if win == self.onRenderGauge:
  2633. wWin = rect.width - 6
  2634. # -> position
  2635. # if win == self.showRegion:
  2636. # x, y = rect.x + rect.width - wWin, rect.y - 1
  2637. # align left
  2638. # else:
  2639. x, y = rect.x + 3, rect.y - 1
  2640. w, h = wWin, rect.height + 2
  2641. else: # choice || auto-rendering
  2642. x, y = rect.x, rect.y - 1
  2643. w, h = rect.width, rect.height + 2
  2644. if idx == 2:
  2645. x += 5
  2646. win.SetPosition((x, y))
  2647. win.SetSize((w, h))
  2648. def SaveToFile(self, event):
  2649. """
  2650. Save image to file
  2651. """
  2652. filetype = "PNG file (*.png)|*.png|"\
  2653. "TIF file (*.tif)|*.tif|"\
  2654. "GIF file (*.gif)|*.gif"
  2655. dlg = wx.FileDialog(self, "Choose a file name to save the image as a PNG to",
  2656. defaultDir = "",
  2657. defaultFile = "",
  2658. wildcard = filetype,
  2659. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  2660. if dlg.ShowModal() == wx.ID_OK:
  2661. base = os.path.splitext(dlg.GetPath())[0]
  2662. ext = os.path.splitext(dlg.GetPath())[1]
  2663. if dlg.GetFilterIndex() == 0:
  2664. type = wx.BITMAP_TYPE_PNG
  2665. path = dlg.GetPath()
  2666. if ext != '.png': path = base+'.png'
  2667. elif dlg.GetFilterIndex() == 1:
  2668. type = wx.BITMAP_TYPE_TIF
  2669. if ext != '.tif': path = base+'.tif'
  2670. elif dlg.GetFilterIndex() == 2:
  2671. type = wx.BITMAP_TYPE_TIF
  2672. if ext != '.gif': path = base+'.gif'
  2673. self.MapWindow.SaveToFile(path, type)
  2674. dlg.Destroy()
  2675. def PrintMenu(self, event):
  2676. """
  2677. Print map display
  2678. """
  2679. """
  2680. Print options and output menu
  2681. """
  2682. point = wx.GetMousePosition()
  2683. printmenu = wx.Menu()
  2684. # Add items to the menu
  2685. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  2686. printmenu.AppendItem(setup)
  2687. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  2688. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  2689. printmenu.AppendItem(preview)
  2690. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  2691. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  2692. printmenu.AppendItem(doprint)
  2693. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  2694. # Popup the menu. If an item is selected then its handler
  2695. # will be called before PopupMenu returns.
  2696. self.PopupMenu(printmenu)
  2697. printmenu.Destroy()
  2698. def OnCloseWindow(self, event):
  2699. """
  2700. Window closed
  2701. Also close associated layer tree page
  2702. """
  2703. pgnum = None
  2704. self.Map.Clean()
  2705. # close edited map properly
  2706. digitToolbar = self.toolbars['vdigit']
  2707. if digitToolbar:
  2708. maplayer = digitToolbar.GetLayer()
  2709. if maplayer:
  2710. self.toolbars['vdigit'].OnExit()
  2711. self.imgVectorMap = None
  2712. if self.page:
  2713. pgnum = self.layerbook.GetPageIndex(self.page)
  2714. if pgnum > -1:
  2715. self.layerbook.DeletePage(pgnum)
  2716. ### self.Destroy()
  2717. # if event:
  2718. # event.Skip() <- causes application crash
  2719. def GetRender(self):
  2720. """
  2721. Returns the current instance of render.Map()
  2722. """
  2723. return self.Map
  2724. def OnQueryDisplay(self, event):
  2725. """
  2726. Query currrent raster/vector map layers (display mode)
  2727. """
  2728. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  2729. self.toolbars['map'].SelectDefault(event)
  2730. return
  2731. self.toolbars['map'].action['desc'] = 'displayAttrb'
  2732. # switch GIS Manager to output console to show query results
  2733. self.gismanager.notebook.SetSelection(1)
  2734. self.MapWindow.mouse['use'] = "query"
  2735. self.MapWindow.mouse['box'] = "point"
  2736. self.MapWindow.zoomtype = 0
  2737. # change the cursor
  2738. self.MapWindow.SetCursor(self.cursors["cross"])
  2739. def OnQueryModify(self, event):
  2740. """
  2741. Query vector map layer (edit mode)
  2742. """
  2743. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  2744. self.toolbars['map'].SelectDefault(event)
  2745. return
  2746. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  2747. self.MapWindow.mouse['use'] = "queryVector"
  2748. self.MapWindow.mouse['box'] = "box"
  2749. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  2750. self.MapWindow.zoomtype = 0
  2751. # change the cursor
  2752. self.MapWindow.SetCursor(self.cursors["cross"])
  2753. def QueryMap(self, x, y):
  2754. """
  2755. Query map layer features
  2756. Currently only raster and vector map layers are supported
  2757. """
  2758. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  2759. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  2760. east, north = self.MapWindow.Pixel2Cell((x, y))
  2761. if not self.tree.layer_selected:
  2762. dlg = wx.MessageDialog(parent=self,
  2763. message=_('No map layer selected for querying.'),
  2764. caption=_('Message'),
  2765. style=wx.OK | wx.ICON_INFORMATION)
  2766. dlg.ShowModal()
  2767. dlg.Destroy()
  2768. return
  2769. mapname = None
  2770. raststr = ''
  2771. vectstr = ''
  2772. rcmd = []
  2773. vcmd = []
  2774. for layer in self.tree.GetSelections():
  2775. type = self.tree.GetPyData(layer)[0]['maplayer'].type
  2776. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  2777. name = utils.GetLayerNameFromCmd(dcmd)
  2778. if name == '':
  2779. continue
  2780. if type in ('raster', 'rgb', 'his'):
  2781. raststr += "%s," % name
  2782. elif type in ('vector', 'thememap', 'themechart'):
  2783. vectstr += "%s," % name
  2784. # build query commands for any selected rasters and vectors
  2785. if raststr != '':
  2786. rcmd = ['r.what', '--q',
  2787. '-f',
  2788. 'input=%s' % raststr.rstrip(','),
  2789. 'east_north=%f,%f' % (float(east), float(north))]
  2790. if vectstr != '':
  2791. # check for vector maps open to be edited
  2792. digitToolbar = self.toolbars['vdigit']
  2793. if digitToolbar:
  2794. map = digitToolbar.GetLayer().GetName()
  2795. vect = []
  2796. for vector in vectstr.split(','):
  2797. if map == vector:
  2798. self.gismanager.goutput.WriteWarning("Vector map <%s> "
  2799. "opened for editing - skipped." % map)
  2800. continue
  2801. vect.append(vector)
  2802. vectstr = ','.join(vect)
  2803. if len(vectstr) <= 1:
  2804. self.gismanager.goutput.WriteCmdLog("Nothing to query.")
  2805. return
  2806. vcmd = ['v.what', '--q',
  2807. '-a',
  2808. 'map=%s' % vectstr.rstrip(','),
  2809. 'east_north=%f,%f' % (float(east), float(north)),
  2810. 'distance=%f' % qdist]
  2811. # parse query command(s)
  2812. if self.gismanager:
  2813. if rcmd:
  2814. self.gismanager.goutput.RunCmd(rcmd)
  2815. if vcmd:
  2816. self.gismanager.goutput.RunCmd(vcmd)
  2817. else:
  2818. if rcmd:
  2819. gcmd.Command(rcmd)
  2820. if vcmd:
  2821. gcmd.Command(vcmd)
  2822. def QueryVector(self, x, y):
  2823. """
  2824. Query vector map layer features
  2825. Attribute data of selected vector object are displayed in GUI dialog.
  2826. Data can be modified (On Submit)
  2827. """
  2828. if not self.tree.layer_selected or \
  2829. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  2830. wx.MessageBox(parent=self,
  2831. message=_("No vector map selected for querying."),
  2832. caption=_("Message"),
  2833. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  2834. return
  2835. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  2836. y + self.MapWindow.dialogOffset))
  2837. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / \
  2838. self.Map.width)
  2839. east, north = self.MapWindow.Pixel2Cell((x, y))
  2840. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  2841. if self.dialogs['attributes'] is None:
  2842. self.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self.MapWindow,
  2843. map=mapName,
  2844. query=((east, north), qdist),
  2845. pos=posWindow,
  2846. action="update")
  2847. else:
  2848. # selection changed?
  2849. if not self.dialogs['attributes'].mapDBInfo or \
  2850. self.dialogs['attributes'].mapDBInfo.map != mapName:
  2851. self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
  2852. else:
  2853. self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
  2854. cats = self.dialogs['attributes'].GetLine(id=False)
  2855. try:
  2856. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
  2857. except IndexError:
  2858. qlayer = None
  2859. if self.dialogs['attributes'].mapDBInfo and cats:
  2860. # highlight feature & re-draw map
  2861. if qlayer:
  2862. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  2863. useId=False,
  2864. addLayer=False))
  2865. else:
  2866. self.AddTmpVectorMapLayer(mapName, cats, useId=False)
  2867. self.MapWindow.UpdateMap(render=False, renderVector=False)
  2868. # digitClass.driver.SetSelected([line])
  2869. if not self.dialogs['attributes'].IsShown():
  2870. self.dialogs['attributes'].Show()
  2871. else:
  2872. if qlayer:
  2873. self.Map.DeleteLayer(qlayer)
  2874. self.MapWindow.UpdateMap(render=False, renderVector=False)
  2875. if self.dialogs['attributes'].IsShown():
  2876. self.dialogs['attributes'].Hide()
  2877. def OnQuery(self, event):
  2878. """Query tools menu"""
  2879. self.toolbars['map'].OnTool(event)
  2880. action = self.toolbars['map'].GetAction()
  2881. point = wx.GetMousePosition()
  2882. toolsmenu = wx.Menu()
  2883. # Add items to the menu
  2884. display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  2885. text=_("Query raster/vector map(s) (display mode)"),
  2886. kind=wx.ITEM_CHECK)
  2887. toolsmenu.AppendItem(display)
  2888. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  2889. if action == "displayAttrb":
  2890. display.Check(True)
  2891. modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  2892. text=_("Query vector map (edit mode)"),
  2893. kind=wx.ITEM_CHECK)
  2894. toolsmenu.AppendItem(modify)
  2895. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  2896. digitToolbar = self.toolbars['vdigit']
  2897. if self.tree.layer_selected:
  2898. layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  2899. if digitToolbar and \
  2900. digitToolbar.GetLayer() == layer_selected:
  2901. modify.Enable(False)
  2902. else:
  2903. if action == "modifyAttrb":
  2904. modify.Check(True)
  2905. self.PopupMenu(toolsmenu)
  2906. toolsmenu.Destroy()
  2907. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  2908. """
  2909. Add temporal vector map layer to map composition
  2910. @param name name of map layer
  2911. @param useId use feature id instead of category
  2912. """
  2913. # color settings from ATM
  2914. color = UserSettings.Get(group='atm', key='highlight', subkey='color')
  2915. colorStr = str(color[0]) + ":" + \
  2916. str(color[1]) + ":" + \
  2917. str(color[2])
  2918. pattern = ["d.vect",
  2919. "map=%s" % name,
  2920. "color=%s" % colorStr,
  2921. "fcolor=%s" % colorStr,
  2922. "width=%d" % UserSettings.Get(group='atm', key='highlight', subkey='width')]
  2923. if useId:
  2924. cmd = pattern
  2925. cmd.append('-i')
  2926. cmd.append('cats=%s' % str(cats))
  2927. else:
  2928. cmd = []
  2929. for layer in cats.keys():
  2930. cmd.append(copy.copy(pattern))
  2931. lcats = cats[layer]
  2932. cmd[-1].append("layer=%d" % layer)
  2933. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  2934. # if self.icon:
  2935. # cmd.append("icon=%s" % (self.icon))
  2936. # if self.pointsize:
  2937. # cmd.append("size=%s" % (self.pointsize))
  2938. if addLayer:
  2939. if useId:
  2940. return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
  2941. l_active=True, l_hidden=True, l_opacity=1.0)
  2942. else:
  2943. return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
  2944. l_active=True, l_hidden=True, l_opacity=1.0)
  2945. else:
  2946. return cmd
  2947. def OnAnalyze(self, event):
  2948. """
  2949. Analysis tools menu
  2950. """
  2951. point = wx.GetMousePosition()
  2952. toolsmenu = wx.Menu()
  2953. # Add items to the menu
  2954. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  2955. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  2956. toolsmenu.AppendItem(measure)
  2957. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  2958. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  2959. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  2960. toolsmenu.AppendItem(profile)
  2961. self.Bind(wx.EVT_MENU, self.Profile, profile)
  2962. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  2963. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  2964. toolsmenu.AppendItem(histogram)
  2965. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  2966. # Popup the menu. If an item is selected then its handler
  2967. # will be called before PopupMenu returns.
  2968. self.PopupMenu(toolsmenu)
  2969. toolsmenu.Destroy()
  2970. def OnMeasure(self, event):
  2971. """
  2972. Init measurement routine that calculates
  2973. map distance along transect drawn on
  2974. map display
  2975. """
  2976. self.totaldist = 0.0 # total measured distance
  2977. # switch GIS Manager to output console to show measure results
  2978. self.gismanager.notebook.SetSelection(1)
  2979. # change mouse to draw line for measurement
  2980. self.MapWindow.mouse['use'] = "measure"
  2981. self.MapWindow.mouse['box'] = "line"
  2982. self.MapWindow.zoomtype = 0
  2983. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  2984. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
  2985. # change the cursor
  2986. self.MapWindow.SetCursor(self.cursors["pencil"])
  2987. # initiating output
  2988. style = self.gismanager.goutput.cmd_output.StyleWarning
  2989. self.gismanager.goutput.WriteLog(_('Click and drag with left mouse button '
  2990. 'to measure.%s'
  2991. 'Double click with left button to clear.') % \
  2992. (os.linesep), style)
  2993. if self.projinfo['proj'] != 'xy':
  2994. units = self.projinfo['units']
  2995. style = self.gismanager.goutput.cmd_output.StyleCommand
  2996. self.gismanager.goutput.WriteLog(_('Measuring distance') + ' ('
  2997. + units + '):',
  2998. style)
  2999. else:
  3000. self.gismanager.goutput.WriteLog(_('Measuring distance:'),
  3001. style)
  3002. def MeasureDist(self, beginpt, endpt):
  3003. """
  3004. Calculate map distance from screen distance
  3005. and print to output window
  3006. """
  3007. if self.gismanager.notebook.GetSelection() != 1:
  3008. self.gismanager.notebook.SetSelection(1)
  3009. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  3010. dist = round(dist, 3)
  3011. d, dunits = self.FormatDist(dist)
  3012. self.totaldist += dist
  3013. td, tdunits = self.FormatDist(self.totaldist)
  3014. strdist = str(d)
  3015. strtotdist = str(td)
  3016. if self.projinfo['proj'] == 'xy' or 'degree' not in self.projinfo['unit']:
  3017. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  3018. angle = angle+90
  3019. if angle < 0: angle = 360+angle
  3020. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  3021. % (strdist,dunits,strtotdist,tdunits,angle)
  3022. else:
  3023. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  3024. % (strdist,dunits,strtotdist,tdunits)
  3025. self.gismanager.goutput.WriteLog(mstring)
  3026. return dist
  3027. def Profile(self, event):
  3028. """
  3029. Init profile canvas and tools
  3030. """
  3031. raster = []
  3032. if self.tree.layer_selected and \
  3033. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  3034. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  3035. self.profile = profile.ProfileFrame(self,
  3036. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
  3037. style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
  3038. self.profile.Show()
  3039. def FormatDist(self, dist):
  3040. """Format length numbers and units in a nice way,
  3041. as a function of length. From code by Hamish Bowman
  3042. Grass Development Team 2006"""
  3043. mapunits = self.projinfo['units']
  3044. if mapunits == 'metres': mapunits = 'meters'
  3045. outunits = mapunits
  3046. dist = float(dist)
  3047. divisor = 1.0
  3048. # figure out which units to use
  3049. if mapunits == 'meters':
  3050. if dist > 2500.0:
  3051. outunits = 'km'
  3052. divisor = 1000.0
  3053. else: outunits = 'm'
  3054. elif mapunits == 'feet':
  3055. # nano-bug: we match any "feet", but US Survey feet is really
  3056. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  3057. # miles the tick markers are rounded to the nearest 10th of a
  3058. # mile (528'), the difference in foot flavours is ignored.
  3059. if dist > 5280.0:
  3060. outunits = 'miles'
  3061. divisor = 5280.0
  3062. else:
  3063. outunits = 'ft'
  3064. elif 'degree' in mapunits:
  3065. if dist < 1:
  3066. outunits = 'min'
  3067. divisor = (1/60.0)
  3068. else:
  3069. outunits = 'deg'
  3070. # format numbers in a nice way
  3071. if (dist/divisor) >= 2500.0:
  3072. outdist = round(dist/divisor)
  3073. elif (dist/divisor) >= 1000.0:
  3074. outdist = round(dist/divisor,1)
  3075. elif (dist/divisor) > 0.0:
  3076. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  3077. else:
  3078. outdist = float(dist/divisor)
  3079. return (outdist, outunits)
  3080. def Histogram(self, event):
  3081. """
  3082. Init histogram display canvas and tools
  3083. """
  3084. self.histogram = histogram.HistFrame(self,
  3085. id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
  3086. style=wx.DEFAULT_FRAME_STYLE)
  3087. #show new display
  3088. self.histogram.Show()
  3089. self.histogram.Refresh()
  3090. self.histogram.Update()
  3091. def OnDecoration(self, event):
  3092. """
  3093. Decorations overlay menu
  3094. """
  3095. point = wx.GetMousePosition()
  3096. decmenu = wx.Menu()
  3097. # Add items to the menu
  3098. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  3099. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  3100. decmenu.AppendItem(AddScale)
  3101. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  3102. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  3103. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  3104. decmenu.AppendItem(AddLegend)
  3105. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  3106. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  3107. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  3108. decmenu.AppendItem(AddText)
  3109. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  3110. # Popup the menu. If an item is selected then its handler
  3111. # will be called before PopupMenu returns.
  3112. self.PopupMenu(decmenu)
  3113. decmenu.Destroy()
  3114. def OnAddBarscale(self, event):
  3115. """
  3116. Handler for scale/arrow map decoration menu selection.
  3117. """
  3118. if self.dialogs['barscale']:
  3119. return
  3120. id = 0 # unique index for overlay layer
  3121. # If location is latlon, only display north arrow (scale won't work)
  3122. # proj = self.projinfo['proj']
  3123. # if proj == 'll':
  3124. # barcmd = 'd.barscale -n'
  3125. # else:
  3126. # barcmd = 'd.barscale'
  3127. # decoration overlay control dialog
  3128. self.dialogs['barscale'] = \
  3129. gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
  3130. size=(350, 200),
  3131. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  3132. cmd=['d.barscale'],
  3133. ovlId=id,
  3134. name='barscale',
  3135. checktxt = _("Show/hide scale and North arrow"),
  3136. ctrltxt = _("scale object"))
  3137. self.dialogs['barscale'].Show()
  3138. def OnAddLegend(self, event):
  3139. """
  3140. Handler for legend map decoration menu selection.
  3141. """
  3142. if self.dialogs['legend']:
  3143. return
  3144. id = 1 # index for overlay layer in render
  3145. cmd = ['d.legend']
  3146. if self.tree.layer_selected and \
  3147. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  3148. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  3149. # Decoration overlay control dialog
  3150. self.dialogs['legend'] = \
  3151. gdialogs.DecorationDialog(parent=self, title=('Legend'),
  3152. size=(350, 200),
  3153. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  3154. cmd=cmd,
  3155. ovlId=id,
  3156. name='legend',
  3157. checktxt = _("Show/hide legend"),
  3158. ctrltxt = _("legend object"))
  3159. self.dialogs['legend'].Show()
  3160. def OnAddText(self, event):
  3161. """
  3162. Handler for text decoration menu selection.
  3163. """
  3164. id = 2 # index for overlay layer in render
  3165. # default values
  3166. text = ''
  3167. font = self.GetFont()
  3168. color = wx.BLACK
  3169. coords = [10, 10, 10, 10]
  3170. rotation = 0.0
  3171. # if self.MapWindow.currtxtid == None: # text doesn't already exist
  3172. # id = wx.NewId() + 100
  3173. # else: # text already exists
  3174. # id = self.MapWindow.currtxtid
  3175. # textcoords = self.ovlcoords[id]
  3176. dlg = gdialogs.TextLayerDialog(parent=self, ovlId=id, title=_('Add text layer'),
  3177. size=(400, 200))
  3178. dlg.CenterOnScreen()
  3179. # If OK button pressed in decoration control dialog
  3180. if dlg.ShowModal() == wx.ID_OK:
  3181. text = dlg.GetValues()[0]
  3182. coords, w, h = self.MapWindow.TextBounds(dlg.GetValues(),
  3183. coords)
  3184. # delete object if it has no text
  3185. if text == '':
  3186. try:
  3187. self.MapWindow.pdc.ClearId(id)
  3188. self.MapWindow.pdc.RemoveId(id)
  3189. del self.MapWindow.textdict[id]
  3190. # del self.ovlcoords[id]
  3191. except:
  3192. pass
  3193. return
  3194. self.MapWindow.pdc.ClearId(id)
  3195. self.MapWindow.pdc.SetId(id)
  3196. self.MapWindow.textdict[id] = (text, font, color, rotation)
  3197. self.MapWindow.Draw(self.MapWindow.pdc, img=self.MapWindow.textdict[id],
  3198. drawid=id, pdctype='text', coords=coords)
  3199. self.MapWindow.UpdateMap(render=False, renderVector=False)
  3200. def GetOptData(self, dcmd, type, params, propwin):
  3201. """
  3202. Callback method for decoration overlay command generated by
  3203. dialog created in menuform.py
  3204. """
  3205. # Reset comand and rendering options in render.Map. Always render decoration.
  3206. # Showing/hiding handled by PseudoDC
  3207. self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
  3208. l_active=True, l_render=False)
  3209. self.params[type] = params
  3210. self.propwin[type] = propwin
  3211. def OnZoomMenu(self, event):
  3212. """
  3213. Zoom menu
  3214. """
  3215. point = wx.GetMousePosition()
  3216. zoommenu = wx.Menu()
  3217. # Add items to the menu
  3218. zoommap = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to selected map'))
  3219. zoommenu.AppendItem(zoommap)
  3220. self.Bind(wx.EVT_MENU, self.MapWindow.OnZoomToMap, zoommap)
  3221. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  3222. zoommenu.AppendItem(zoomwind)
  3223. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToWind, zoomwind)
  3224. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  3225. zoommenu.AppendItem(zoomdefault)
  3226. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToDefault, zoomdefault)
  3227. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  3228. zoommenu.AppendItem(zoomsaved)
  3229. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToSaved, zoomsaved)
  3230. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  3231. zoommenu.AppendItem(savewind)
  3232. self.Bind(wx.EVT_MENU, self.MapWindow.DisplayToWind, savewind)
  3233. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  3234. zoommenu.AppendItem(savezoom)
  3235. self.Bind(wx.EVT_MENU, self.MapWindow.SaveDisplayRegion, savezoom)
  3236. # Popup the menu. If an item is selected then its handler
  3237. # will be called before PopupMenu returns.
  3238. self.PopupMenu(zoommenu)
  3239. zoommenu.Destroy()
  3240. def SetProperties(self, render=False, mode=0, showCompExtent=False):
  3241. """Set properies of map display window"""
  3242. self.autoRender.SetValue(render)
  3243. self.toggleStatus.SetSelection(mode)
  3244. self.StatusbarUpdate()
  3245. self.showRegion.SetValue(showCompExtent)
  3246. if showCompExtent:
  3247. self.MapWindow.regionCoords = []
  3248. # end of class MapFrame
  3249. class MapApp(wx.App):
  3250. """
  3251. MapApp class
  3252. """
  3253. def OnInit(self):
  3254. wx.InitAllImageHandlers()
  3255. if __name__ == "__main__":
  3256. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  3257. else:
  3258. Map = None
  3259. self.mapFrm = MapFrame(parent=None, id=wx.ID_ANY, Map=Map, size=(640,480))
  3260. #self.SetTopWindow(Map)
  3261. self.mapFrm.Show()
  3262. if __name__ == "__main__":
  3263. # redraw map, if new command appears
  3264. self.redraw = False
  3265. status = Command(self, Map)
  3266. status.start()
  3267. self.timer = wx.PyTimer(self.watcher)
  3268. # check each 0.1s
  3269. self.timer.Start(100)
  3270. return 1
  3271. def OnExit(self):
  3272. if __name__ == "__main__":
  3273. # stop the timer
  3274. self.timer.Stop()
  3275. # terminate thread (a bit ugly)
  3276. os.system("""echo "quit" >> %s""" % (cmdfilename))
  3277. def watcher(self):
  3278. """Redraw, if new layer appears"""
  3279. if self.redraw:
  3280. self.mapFrm.OnDraw(None)
  3281. self.redraw = False
  3282. return
  3283. # end of class MapApp
  3284. if __name__ == "__main__":
  3285. ###### SET command variable
  3286. if len(sys.argv) != 3:
  3287. print __doc__
  3288. sys.exit()
  3289. title = sys.argv[1]
  3290. cmdfilename = sys.argv[2]
  3291. import gettext
  3292. gettext.install("gm_map") # replace with the appropriate catalog name
  3293. print "Starting monitor <%s>" % (title)
  3294. gm_map = MapApp(0)
  3295. # set title
  3296. gm_map.mapFrm.SetTitle ("GRASS GIS - Map Display: " + title + " - Location: " + \
  3297. grassenv.GetGRASSVariable("LOCATION_NAME"))
  3298. gm_map.MainLoop()
  3299. os.remove(cmdfilename)
  3300. os.system("""g.gisenv set="GRASS_PYCMDFILE" """)
  3301. print "Stoping monitor <%s>" % (title)
  3302. sys.exit()