mapdisp.py 143 KB

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