mapdisp.py 143 KB

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