mapdisp.py 132 KB

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