mapdisp.py 142 KB

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