mapdisp.py 147 KB

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