mapdisp.py 140 KB

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