mapdisp.py 144 KB

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