mapdisp.py 141 KB

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