mapdisp.py 149 KB

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