mapdisp.py 143 KB

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