mapdisp.py 141 KB

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