mapdisp.py 144 KB

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