mapdisp.py 146 KB

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