mapdisp.py 134 KB

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