mapdisp.py 154 KB

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