mapdisp.py 155 KB

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