dialogs.py 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  1. """!
  2. @package gui_core.dialogs
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - dialogs::ElementDialog
  6. - dialogs::LocationDialog
  7. - dialogs::MapsetDialog
  8. - dialogs::NewVectorDialog
  9. - dialogs::SavedRegion
  10. - dialogs::DecorationDialog
  11. - dialogs::TextLayerDialog
  12. - dialogs::GroupDialog
  13. - dialogs::MapLayersDialog
  14. - dialogs::ImportDialog
  15. - dialogs::GdalImportDialog
  16. - dialogs::GdalOutputDialog
  17. - dialogs::DxfImportDialog
  18. - dialogs::LayersList (used by MultiImport)
  19. - dialogs::SetOpacityDialog
  20. - dialogs::ImageSizeDialog
  21. - dialogs::SqlQueryFrame
  22. - dialogs::SymbolDialog
  23. (C) 2008-2011 by the GRASS Development Team
  24. This program is free software under the GNU General Public License
  25. (>=v2). Read the file COPYING that comes with GRASS for details.
  26. @author Martin Landa <landa.martin gmail.com>
  27. @author Anna Kratochvilova <kratochanna gmail.com> (GroupDialog, SymbolDialog)
  28. """
  29. import os
  30. import sys
  31. import re
  32. from bisect import bisect
  33. import wx
  34. import wx.lib.filebrowsebutton as filebrowse
  35. import wx.lib.mixins.listctrl as listmix
  36. from wx.lib.newevent import NewEvent
  37. from grass.script import core as grass
  38. from grass.script import task as gtask
  39. from core import globalvar
  40. from core.gcmd import GError, RunCommand, GMessage
  41. from gui_core.gselect import ElementSelect, LocationSelect, MapsetSelect, Select, OgrTypeSelect, GdalSelect, MapsetSelect
  42. from gui_core.forms import GUI
  43. from gui_core.widgets import SingleSymbolPanel, EVT_SYMBOL_SELECTION_CHANGED
  44. from core.utils import GetListOfMapsets, GetLayerNameFromCmd, GetValidLayerName
  45. from core.settings import UserSettings, GetDisplayVectSettings
  46. from core.debug import Debug
  47. wxApplyMapLayers, EVT_APPLY_MAP_LAYERS = NewEvent()
  48. wxApplyOpacity, EVT_APPLY_OPACITY = NewEvent()
  49. class ElementDialog(wx.Dialog):
  50. def __init__(self, parent, title, label, id = wx.ID_ANY,
  51. etype = False, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  52. **kwargs):
  53. """!General dialog to choose given element (location, mapset, vector map, etc.)
  54. @param parent window
  55. @param title window title
  56. @param label element label
  57. @param etype show also ElementSelect
  58. """
  59. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  60. self.etype = etype
  61. self.label = label
  62. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  63. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  64. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  65. self.btnOK.SetDefault()
  66. self.btnOK.Enable(False)
  67. if self.etype:
  68. self.typeSelect = ElementSelect(parent = self.panel,
  69. size = globalvar.DIALOG_GSELECT_SIZE)
  70. self.typeSelect.Bind(wx.EVT_CHOICE, self.OnType)
  71. self.element = None # must be defined
  72. self.__layout()
  73. def PostInit(self):
  74. self.element.SetFocus()
  75. self.element.Bind(wx.EVT_TEXT, self.OnElement)
  76. def OnType(self, event):
  77. """!Select element type"""
  78. if not self.etype:
  79. return
  80. evalue = self.typeSelect.GetValue(event.GetString())
  81. self.element.SetType(evalue)
  82. def OnElement(self, event):
  83. """!Name for vector map layer given"""
  84. if len(event.GetString()) > 0:
  85. self.btnOK.Enable(True)
  86. else:
  87. self.btnOK.Enable(False)
  88. def __layout(self):
  89. """!Do layout"""
  90. self.sizer = wx.BoxSizer(wx.VERTICAL)
  91. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  92. if self.etype:
  93. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  94. label = _("Type of element:")),
  95. proportion = 0, flag = wx.ALL, border = 1)
  96. self.dataSizer.Add(item = self.typeSelect,
  97. proportion = 0, flag = wx.ALL, border = 1)
  98. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  99. label = self.label),
  100. proportion = 0, flag = wx.ALL, border = 1)
  101. # buttons
  102. btnSizer = wx.StdDialogButtonSizer()
  103. btnSizer.AddButton(self.btnCancel)
  104. btnSizer.AddButton(self.btnOK)
  105. btnSizer.Realize()
  106. self.sizer.Add(item = self.dataSizer, proportion = 1,
  107. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  108. self.sizer.Add(item = btnSizer, proportion = 0,
  109. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  110. def GetElement(self):
  111. """!Return (mapName, overwrite)"""
  112. return self.element.GetValue()
  113. def GetType(self):
  114. """!Get element type"""
  115. return self.element.tcp.GetType()
  116. class LocationDialog(ElementDialog):
  117. """!Dialog used to select location"""
  118. def __init__(self, parent, title = _("Select GRASS location and mapset"), id = wx.ID_ANY):
  119. ElementDialog.__init__(self, parent, title, label = _("Name of GRASS location:"))
  120. self.element = LocationSelect(parent = self.panel, id = wx.ID_ANY,
  121. size = globalvar.DIALOG_GSELECT_SIZE)
  122. self.element1 = MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  123. size = globalvar.DIALOG_GSELECT_SIZE,
  124. setItems = False, skipCurrent = True)
  125. self.PostInit()
  126. self._layout()
  127. self.SetMinSize(self.GetSize())
  128. def _layout(self):
  129. """!Do layout"""
  130. self.dataSizer.Add(self.element, proportion = 0,
  131. flag = wx.EXPAND | wx.ALL, border = 1)
  132. self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  133. label = _("Name of mapset:")), proportion = 0,
  134. flag = wx.EXPAND | wx.ALL, border = 1)
  135. self.dataSizer.Add(self.element1, proportion = 0,
  136. flag = wx.EXPAND | wx.ALL, border = 1)
  137. self.panel.SetSizer(self.sizer)
  138. self.sizer.Fit(self)
  139. def OnElement(self, event):
  140. """!Select mapset given location name"""
  141. location = event.GetString()
  142. if location:
  143. dbase = grass.gisenv()['GISDBASE']
  144. self.element1.UpdateItems(dbase = dbase, location = location)
  145. self.element1.SetSelection(0)
  146. mapset = self.element1.GetStringSelection()
  147. if location and mapset:
  148. self.btnOK.Enable(True)
  149. else:
  150. self.btnOK.Enable(False)
  151. def GetValues(self):
  152. """!Get location, mapset"""
  153. return (self.GetElement(), self.element1.GetStringSelection())
  154. class MapsetDialog(ElementDialog):
  155. """!Dialog used to select mapset"""
  156. def __init__(self, parent, title = _("Select mapset in GRASS location"),
  157. location = None, id = wx.ID_ANY):
  158. ElementDialog.__init__(self, parent, title, label = _("Name of mapset:"))
  159. if location:
  160. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  161. else:
  162. self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
  163. self.element = MapsetSelect(parent = self.panel, id = wx.ID_ANY, skipCurrent = True,
  164. size = globalvar.DIALOG_GSELECT_SIZE)
  165. self.PostInit()
  166. self.__Layout()
  167. self.SetMinSize(self.GetSize())
  168. def __Layout(self):
  169. """!Do layout"""
  170. self.dataSizer.Add(self.element, proportion = 0,
  171. flag = wx.EXPAND | wx.ALL, border = 1)
  172. self.panel.SetSizer(self.sizer)
  173. self.sizer.Fit(self)
  174. def GetMapset(self):
  175. return self.GetElement()
  176. class NewVectorDialog(ElementDialog):
  177. def __init__(self, parent, id = wx.ID_ANY, title = _('Create new vector map'),
  178. disableAdd = False, disableTable = False, showType = False,
  179. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  180. """!Dialog for creating new vector map
  181. @param parent parent window
  182. @param id window id
  183. @param title window title
  184. @param disableAdd disable 'add layer' checkbox
  185. @param disableTable disable 'create table' checkbox
  186. @param showType True to show feature type selector (used for creating new empty OGR layers)
  187. @param style window style
  188. @param kwargs other argumentes for ElementDialog
  189. @return dialog instance
  190. """
  191. ElementDialog.__init__(self, parent, title, label = _("Name for new vector map:"))
  192. self.element = Select(parent = self.panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  193. type = 'vector', mapsets = [grass.gisenv()['MAPSET'],])
  194. # determine output format
  195. if showType:
  196. self.ftype = OgrTypeSelect(parent = self, panel = self.panel)
  197. else:
  198. self.ftype = None
  199. self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  200. label = _("Create attribute table"))
  201. self.table.SetValue(True)
  202. if disableTable:
  203. self.table.Enable(False)
  204. if showType:
  205. self.keycol = None
  206. else:
  207. self.keycol = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  208. size = globalvar.DIALOG_SPIN_SIZE)
  209. self.keycol.SetValue(UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
  210. if disableTable:
  211. self.keycol.Enable(False)
  212. self.addbox = wx.CheckBox(parent = self.panel,
  213. label = _('Add created map into layer tree'), style = wx.NO_BORDER)
  214. if disableAdd:
  215. self.addbox.SetValue(True)
  216. self.addbox.Enable(False)
  217. else:
  218. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  219. self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
  220. self.PostInit()
  221. self._layout()
  222. self.SetMinSize(self.GetSize())
  223. def OnMapName(self, event):
  224. """!Name for vector map layer given"""
  225. self.OnElement(event)
  226. def OnTable(self, event):
  227. if self.keycol:
  228. self.keycol.Enable(event.IsChecked())
  229. def _layout(self):
  230. """!Do layout"""
  231. self.dataSizer.Add(item = self.element, proportion = 0,
  232. flag = wx.EXPAND | wx.ALL, border = 1)
  233. if self.ftype:
  234. self.dataSizer.AddSpacer(1)
  235. self.dataSizer.Add(item = self.ftype, proportion = 0,
  236. flag = wx.EXPAND | wx.ALL, border = 1)
  237. self.dataSizer.Add(item = self.table, proportion = 0,
  238. flag = wx.EXPAND | wx.ALL, border = 1)
  239. if self.keycol:
  240. keySizer = wx.BoxSizer(wx.HORIZONTAL)
  241. keySizer.Add(item = wx.StaticText(parent = self.panel, label = _("Key column:")),
  242. proportion = 0,
  243. flag = wx.ALIGN_CENTER_VERTICAL)
  244. keySizer.AddSpacer(10)
  245. keySizer.Add(item = self.keycol, proportion = 0,
  246. flag = wx.ALIGN_RIGHT)
  247. self.dataSizer.Add(item = keySizer, proportion = 1,
  248. flag = wx.EXPAND | wx.ALL, border = 1)
  249. self.dataSizer.AddSpacer(5)
  250. self.dataSizer.Add(item = self.addbox, proportion = 0,
  251. flag = wx.EXPAND | wx.ALL, border = 1)
  252. self.panel.SetSizer(self.sizer)
  253. self.sizer.Fit(self)
  254. def GetName(self, full = False):
  255. """!Get name of vector map to be created
  256. @param full True to get fully qualified name
  257. """
  258. name = self.GetElement()
  259. if full:
  260. if '@' in name:
  261. return name
  262. else:
  263. return name + '@' + grass.gisenv()['MAPSET']
  264. return name.split('@', 1)[0]
  265. def GetKey(self):
  266. """!Get key column name"""
  267. if self.keycol:
  268. return self.keycol.GetValue()
  269. return UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value')
  270. def IsChecked(self, key):
  271. """!Get dialog properties
  272. @param key window key ('add', 'table')
  273. @return True/False
  274. @return None on error
  275. """
  276. if key == 'add':
  277. return self.addbox.IsChecked()
  278. elif key == 'table':
  279. return self.table.IsChecked()
  280. return None
  281. def GetFeatureType(self):
  282. """!Get feature type for OGR
  283. @return feature type as string
  284. @return None for native format
  285. """
  286. if self.ftype:
  287. return self.ftype.GetType()
  288. return None
  289. def CreateNewVector(parent, cmd, title = _('Create new vector map'),
  290. exceptMap = None, log = None,
  291. disableAdd = False, disableTable = False):
  292. """!Create new vector map layer
  293. @param cmd (prog, **kwargs)
  294. @param title window title
  295. @param exceptMap list of maps to be excepted
  296. @param log
  297. @param disableAdd disable 'add layer' checkbox
  298. @param disableTable disable 'create table' checkbox
  299. @return dialog instance
  300. @return None on error
  301. """
  302. vExternalOut = grass.parse_command('v.external.out', flags = 'g')
  303. isNative = vExternalOut['format'] == 'native'
  304. if cmd[0] == 'v.edit' and not isNative:
  305. showType = True
  306. else:
  307. showType = False
  308. dlg = NewVectorDialog(parent, title = title,
  309. disableAdd = disableAdd, disableTable = disableTable,
  310. showType = showType)
  311. if dlg.ShowModal() != wx.ID_OK:
  312. dlg.Destroy()
  313. return None
  314. outmap = dlg.GetName()
  315. key = dlg.GetKey()
  316. if outmap == exceptMap:
  317. GError(parent = parent,
  318. message = _("Unable to create vector map <%s>.") % outmap)
  319. dlg.Destroy()
  320. return None
  321. if dlg.table.IsEnabled() and not key:
  322. GError(parent = parent,
  323. message = _("Invalid or empty key column.\n"
  324. "Unable to create vector map <%s>.") % outmap)
  325. dlg.Destroy()
  326. return
  327. if outmap == '': # should not happen
  328. dlg.Destroy()
  329. return None
  330. # update cmd -> output name defined
  331. cmd[1][cmd[2]] = outmap
  332. if showType:
  333. cmd[1]['type'] = dlg.GetFeatureType()
  334. if isNative:
  335. listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
  336. else:
  337. listOfVectors = RunCommand('v.external',
  338. quiet = True,
  339. parent = parent,
  340. read = True,
  341. flags = 'l',
  342. dsn = vExternalOut['dsn']).splitlines()
  343. overwrite = False
  344. if not UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  345. outmap in listOfVectors:
  346. dlgOw = wx.MessageDialog(parent, message = _("Vector map <%s> already exists "
  347. "in the current mapset. "
  348. "Do you want to overwrite it?") % outmap,
  349. caption = _("Overwrite?"),
  350. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  351. if dlgOw.ShowModal() == wx.ID_YES:
  352. overwrite = True
  353. else:
  354. dlgOw.Destroy()
  355. dlg.Destroy()
  356. return None
  357. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  358. overwrite = True
  359. ret = RunCommand(prog = cmd[0],
  360. parent = parent,
  361. overwrite = overwrite,
  362. **cmd[1])
  363. if ret != 0:
  364. dlg.Destroy()
  365. return None
  366. if not isNative:
  367. # create link for OGR layers
  368. RunCommand('v.external',
  369. overwrite = overwrite,
  370. parent = parent,
  371. dsn = vExternalOut['dsn'],
  372. layer = outmap)
  373. # create attribute table
  374. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  375. if isNative:
  376. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  377. RunCommand('db.connect',
  378. flags = 'c')
  379. Debug.msg(1, "SQL: %s" % sql)
  380. RunCommand('db.execute',
  381. quiet = True,
  382. parent = parent,
  383. input = '-',
  384. stdin = sql)
  385. RunCommand('v.db.connect',
  386. quiet = True,
  387. parent = parent,
  388. map = outmap,
  389. table = outmap,
  390. key = key,
  391. layer = '1')
  392. # TODO: how to deal with attribute tables for OGR layers?
  393. # return fully qualified map name
  394. if '@' not in outmap:
  395. outmap += '@' + grass.gisenv()['MAPSET']
  396. if log:
  397. log.WriteLog(_("New vector map <%s> created") % outmap)
  398. return dlg
  399. class SavedRegion(wx.Dialog):
  400. def __init__(self, parent, id = wx.ID_ANY, title = "", loadsave = 'load',
  401. **kwargs):
  402. """!Loading and saving of display extents to saved region file
  403. @param loadsave load or save region?
  404. """
  405. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  406. self.loadsave = loadsave
  407. self.wind = ''
  408. sizer = wx.BoxSizer(wx.VERTICAL)
  409. box = wx.BoxSizer(wx.HORIZONTAL)
  410. label = wx.StaticText(parent = self, id = wx.ID_ANY)
  411. box.Add(item = label, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  412. if loadsave == 'load':
  413. label.SetLabel(_("Load region:"))
  414. selection = Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  415. type = 'windows')
  416. elif loadsave == 'save':
  417. label.SetLabel(_("Save region:"))
  418. selection = Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  419. type = 'windows', mapsets = [grass.gisenv()['MAPSET']])
  420. box.Add(item = selection, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  421. selection.SetFocus()
  422. selection.Bind(wx.EVT_TEXT, self.OnRegion)
  423. sizer.Add(item = box, proportion = 0, flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL,
  424. border = 5)
  425. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
  426. sizer.Add(item = line, proportion = 0,
  427. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 5)
  428. btnsizer = wx.StdDialogButtonSizer()
  429. btn = wx.Button(parent = self, id = wx.ID_OK)
  430. btn.SetDefault()
  431. btnsizer.AddButton(btn)
  432. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  433. btnsizer.AddButton(btn)
  434. btnsizer.Realize()
  435. sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  436. self.SetSizer(sizer)
  437. sizer.Fit(self)
  438. self.Layout()
  439. def OnRegion(self, event):
  440. self.wind = event.GetString()
  441. class DecorationDialog(wx.Dialog):
  442. """!Controls setting options and displaying/hiding map overlay
  443. decorations
  444. """
  445. def __init__(self, parent, ovlId, title, cmd, name = None,
  446. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE,
  447. checktxt = '', ctrltxt = ''):
  448. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  449. self.ovlId = ovlId # PseudoDC id
  450. self.cmd = cmd
  451. self.name = name # overlay name
  452. self.parent = parent # MapFrame
  453. sizer = wx.BoxSizer(wx.VERTICAL)
  454. box = wx.BoxSizer(wx.HORIZONTAL)
  455. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY, label = checktxt)
  456. if self.parent.Map.GetOverlay(self.ovlId) is None:
  457. self.chkbox.SetValue(True)
  458. else:
  459. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  460. box.Add(item = self.chkbox, proportion = 0,
  461. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  462. sizer.Add(item = box, proportion = 0,
  463. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  464. box = wx.BoxSizer(wx.HORIZONTAL)
  465. optnbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set options"))
  466. box.Add(item = optnbtn, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  467. sizer.Add(item = box, proportion = 0,
  468. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  469. if self.name == 'legend':
  470. box = wx.BoxSizer(wx.HORIZONTAL)
  471. resize = wx.ToggleButton(parent = self, id = wx.ID_ANY, label = _("Set size and position"))
  472. resize.SetToolTipString(_("Click and drag on the map display to set legend"
  473. " size and position and then press OK"))
  474. resize.SetName('resize')
  475. if self.parent.IsPaneShown('3d'):
  476. resize.Disable()
  477. box.Add(item = resize, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  478. sizer.Add(item = box, proportion = 0,
  479. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  480. box = wx.BoxSizer(wx.HORIZONTAL)
  481. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  482. label = _("Drag %s with mouse in pointer mode to position.\n"
  483. "Double-click to change options." % ctrltxt))
  484. if self.name == 'legend':
  485. label.SetLabel(label.GetLabel() + _('\nDefine raster map name for legend in '
  486. 'properties dialog.'))
  487. box.Add(item = label, proportion = 0,
  488. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  489. sizer.Add(item = box, proportion = 0,
  490. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  491. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20,-1), style = wx.LI_HORIZONTAL)
  492. sizer.Add(item = line, proportion = 0,
  493. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  494. # buttons
  495. btnsizer = wx.StdDialogButtonSizer()
  496. self.btnOK = wx.Button(parent = self, id = wx.ID_OK)
  497. self.btnOK.SetDefault()
  498. if self.name == 'legend':
  499. self.btnOK.Enable(False)
  500. btnsizer.AddButton(self.btnOK)
  501. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  502. btnsizer.AddButton(btnCancel)
  503. btnsizer.Realize()
  504. sizer.Add(item = btnsizer, proportion = 0,
  505. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  506. #
  507. # bindings
  508. #
  509. self.Bind(wx.EVT_BUTTON, self.OnOptions, optnbtn)
  510. if self.name == 'legend':
  511. self.Bind(wx.EVT_TOGGLEBUTTON, self.OnResize, resize)
  512. self.Bind(wx.EVT_BUTTON, self.OnCancel, btnCancel)
  513. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  514. self.SetSizer(sizer)
  515. sizer.Fit(self)
  516. # create overlay if doesn't exist
  517. self._createOverlay()
  518. if len(self.parent.MapWindow.overlays[self.ovlId]['cmd']) > 1:
  519. if name == 'legend':
  520. mapName, found = GetLayerNameFromCmd(self.parent.MapWindow.overlays[self.ovlId]['cmd'])
  521. if found:
  522. # enable 'OK' button
  523. self.btnOK.Enable()
  524. # set title
  525. self.SetTitle(_('Legend of raster map <%s>') % \
  526. mapName)
  527. def _createOverlay(self):
  528. """!Creates overlay"""
  529. if not self.parent.GetMap().GetOverlay(self.ovlId):
  530. self.newOverlay = self.parent.Map.AddOverlay(id = self.ovlId, type = self.name,
  531. command = self.cmd,
  532. l_active = False, l_render = False, l_hidden = True)
  533. prop = { 'layer' : self.newOverlay,
  534. 'params' : None,
  535. 'propwin' : None,
  536. 'cmd' : self.cmd,
  537. 'coords': (0, 0),
  538. 'pdcType': 'image' }
  539. self.parent.MapWindow2D.overlays[self.ovlId] = prop
  540. if self.parent.MapWindow3D:
  541. self.parent.MapWindow3D.overlays[self.ovlId] = prop
  542. else:
  543. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] == None:
  544. return
  545. self.parent.MapWindow.overlays[self.ovlId]['propwin'].get_dcmd = self.GetOptData
  546. def OnOptions(self, event):
  547. """!Sets option for decoration map overlays
  548. """
  549. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None:
  550. # build properties dialog
  551. GUI(parent = self.parent).ParseCommand(cmd = self.cmd,
  552. completed = (self.GetOptData, self.name, ''))
  553. else:
  554. if self.parent.MapWindow.overlays[self.ovlId]['propwin'].IsShown():
  555. self.parent.MapWindow.overlays[self.ovlId]['propwin'].SetFocus()
  556. else:
  557. self.parent.MapWindow.overlays[self.ovlId]['propwin'].Show()
  558. def OnResize(self, event):
  559. if self.FindWindowByName('resize').GetValue():
  560. self.parent.SwitchTool(self.parent.toolbars['map'], event)
  561. self.parent.MapWindow.SetCursor(self.parent.cursors["cross"])
  562. self.parent.MapWindow.mouse['use'] = 'legend'
  563. self.parent.MapWindow.mouse['box'] = 'box'
  564. self.parent.MapWindow.pen = wx.Pen(colour = 'Black', width = 2, style = wx.SHORT_DASH)
  565. else:
  566. self.parent.MapWindow.SetCursor(self.parent.cursors["default"])
  567. self.parent.MapWindow.mouse['use'] = 'pointer'
  568. def OnCancel(self, event):
  569. """!Cancel dialog"""
  570. if self.name == 'legend' and self.FindWindowByName('resize').GetValue():
  571. self.FindWindowByName('resize').SetValue(False)
  572. self.OnResize(None)
  573. self.parent.dialogs['barscale'] = None
  574. if event and hasattr(self, 'newOverlay'):
  575. self.parent.Map.DeleteOverlay(self.newOverlay)
  576. self.Destroy()
  577. def OnOK(self, event):
  578. """!Button 'OK' pressed"""
  579. # enable or disable overlay
  580. self.parent.Map.GetOverlay(self.ovlId).SetActive(self.chkbox.IsChecked())
  581. # update map
  582. if self.parent.IsPaneShown('3d'):
  583. self.parent.MapWindow.UpdateOverlays()
  584. self.parent.MapWindow.UpdateMap()
  585. # close dialog
  586. self.OnCancel(None)
  587. def GetOptData(self, dcmd, layer, params, propwin):
  588. """!Process decoration layer data"""
  589. # update layer data
  590. if params:
  591. self.parent.MapWindow.overlays[self.ovlId]['params'] = params
  592. if dcmd:
  593. self.parent.MapWindow.overlays[self.ovlId]['cmd'] = dcmd
  594. self.parent.MapWindow.overlays[self.ovlId]['propwin'] = propwin
  595. # change parameters for item in layers list in render.Map
  596. # "Use mouse..." (-m) flag causes GUI freeze and is pointless here, trac #119
  597. try:
  598. self.parent.MapWindow.overlays[self.ovlId]['cmd'].remove('-m')
  599. except ValueError:
  600. pass
  601. self.parent.Map.ChangeOverlay(id = self.ovlId, type = self.name,
  602. command = self.parent.MapWindow.overlays[self.ovlId]['cmd'],
  603. l_active = self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive(),
  604. l_render = False, l_hidden = True)
  605. if self.name == 'legend':
  606. if params and not self.btnOK.IsEnabled():
  607. self.btnOK.Enable()
  608. class TextLayerDialog(wx.Dialog):
  609. """
  610. Controls setting options and displaying/hiding map overlay decorations
  611. """
  612. def __init__(self, parent, ovlId, title, name = 'text',
  613. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE):
  614. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  615. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  616. self.ovlId = ovlId
  617. self.parent = parent
  618. if self.ovlId in self.parent.MapWindow.textdict.keys():
  619. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  620. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  621. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  622. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  623. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  624. self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
  625. else:
  626. self.currClr = wx.BLACK
  627. self.currText = ''
  628. self.currFont = self.GetFont()
  629. self.currRot = 0.0
  630. self.currCoords = [10, 10]
  631. self.currBB = wx.Rect()
  632. self.sizer = wx.BoxSizer(wx.VERTICAL)
  633. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  634. # show/hide
  635. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY,
  636. label = _('Show text object'))
  637. if self.parent.Map.GetOverlay(self.ovlId) is None:
  638. self.chkbox.SetValue(True)
  639. else:
  640. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  641. box.Add(item = self.chkbox, span = (1,2),
  642. flag = wx.ALIGN_LEFT|wx.ALL, border = 5,
  643. pos = (0, 0))
  644. # text entry
  645. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Enter text:"))
  646. box.Add(item = label,
  647. flag = wx.ALIGN_CENTER_VERTICAL,
  648. pos = (1, 0))
  649. self.textentry = ExpandoTextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (300,-1))
  650. self.textentry.SetFont(self.currFont)
  651. self.textentry.SetForegroundColour(self.currClr)
  652. self.textentry.SetValue(self.currText)
  653. # get rid of unneeded scrollbar when text box first opened
  654. self.textentry.SetClientSize((300,-1))
  655. box.Add(item = self.textentry,
  656. pos = (1, 1))
  657. # rotation
  658. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Rotation:"))
  659. box.Add(item = label,
  660. flag = wx.ALIGN_CENTER_VERTICAL,
  661. pos = (2, 0))
  662. self.rotation = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
  663. size = (75,-1), style = wx.SP_ARROW_KEYS)
  664. self.rotation.SetRange(-360, 360)
  665. self.rotation.SetValue(int(self.currRot))
  666. box.Add(item = self.rotation,
  667. flag = wx.ALIGN_RIGHT,
  668. pos = (2, 1))
  669. # font
  670. fontbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set font"))
  671. box.Add(item = fontbtn,
  672. flag = wx.ALIGN_RIGHT,
  673. pos = (3, 1))
  674. self.sizer.Add(item = box, proportion = 1,
  675. flag = wx.ALL, border = 10)
  676. # note
  677. box = wx.BoxSizer(wx.HORIZONTAL)
  678. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  679. label = _("Drag text with mouse in pointer mode "
  680. "to position.\nDouble-click to change options"))
  681. box.Add(item = label, proportion = 0,
  682. flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  683. self.sizer.Add(item = box, proportion = 0,
  684. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border = 5)
  685. line = wx.StaticLine(parent = self, id = wx.ID_ANY,
  686. size = (20,-1), style = wx.LI_HORIZONTAL)
  687. self.sizer.Add(item = line, proportion = 0,
  688. flag = wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border = 5)
  689. btnsizer = wx.StdDialogButtonSizer()
  690. btn = wx.Button(parent = self, id = wx.ID_OK)
  691. btn.SetDefault()
  692. btnsizer.AddButton(btn)
  693. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  694. btnsizer.AddButton(btn)
  695. btnsizer.Realize()
  696. self.sizer.Add(item = btnsizer, proportion = 0,
  697. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  698. self.SetSizer(self.sizer)
  699. self.sizer.Fit(self)
  700. # bindings
  701. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  702. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  703. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  704. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  705. def OnRefit(self, event):
  706. """!Resize text entry to match text"""
  707. self.sizer.Fit(self)
  708. def OnText(self, event):
  709. """!Change text string"""
  710. self.currText = event.GetString()
  711. def OnRotation(self, event):
  712. """!Change rotation"""
  713. self.currRot = event.GetInt()
  714. event.Skip()
  715. def OnSelectFont(self, event):
  716. """!Change font"""
  717. data = wx.FontData()
  718. data.EnableEffects(True)
  719. data.SetColour(self.currClr) # set colour
  720. data.SetInitialFont(self.currFont)
  721. dlg = wx.FontDialog(self, data)
  722. if dlg.ShowModal() == wx.ID_OK:
  723. data = dlg.GetFontData()
  724. self.currFont = data.GetChosenFont()
  725. self.currClr = data.GetColour()
  726. self.textentry.SetFont(self.currFont)
  727. self.textentry.SetForegroundColour(self.currClr)
  728. self.Layout()
  729. dlg.Destroy()
  730. def GetValues(self):
  731. """!Get text properties"""
  732. return { 'text' : self.currText,
  733. 'font' : self.currFont,
  734. 'color' : self.currClr,
  735. 'rotation' : self.currRot,
  736. 'coords' : self.currCoords,
  737. 'active' : self.chkbox.IsChecked() }
  738. class GroupDialog(wx.Dialog):
  739. """!Dialog for creating/editing groups"""
  740. def __init__(self, parent = None, defaultGroup = None,
  741. title = _("Create or edit imagery groups"),
  742. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  743. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  744. style = style, **kwargs)
  745. self.parent = parent
  746. self.defaultGroup = defaultGroup
  747. self.currentGroup = self.defaultGroup
  748. self.groupChanged = False
  749. self.bodySizer = self._createDialogBody()
  750. # buttons
  751. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  752. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  753. btnClose = wx.Button(parent = self, id = wx.ID_CANCEL)
  754. btnOk.SetToolTipString(_("Apply changes to selected group and close dialog"))
  755. btnApply.SetToolTipString(_("Apply changes to selected group"))
  756. btnClose.SetToolTipString(_("Close dialog, changes are not applied"))
  757. btnOk.SetDefault()
  758. # sizers & do layout
  759. # btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  760. # btnSizer.Add(item = btnClose, proportion = 0,
  761. # flag = wx.RIGHT | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
  762. # btnSizer.Add(item = btnApply, proportion = 0,
  763. # flag = wx.LEFT, border = 5)
  764. btnSizer = wx.StdDialogButtonSizer()
  765. btnSizer.AddButton(btnOk)
  766. btnSizer.AddButton(btnApply)
  767. btnSizer.AddButton(btnClose)
  768. btnSizer.Realize()
  769. mainSizer = wx.BoxSizer(wx.VERTICAL)
  770. mainSizer.Add(item = self.bodySizer, proportion = 1,
  771. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
  772. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  773. style = wx.LI_HORIZONTAL), proportion = 0,
  774. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
  775. mainSizer.Add(item = btnSizer, proportion = 0,
  776. flag = wx.ALL | wx.ALIGN_RIGHT, border = 10)
  777. self.SetSizer(mainSizer)
  778. mainSizer.Fit(self)
  779. btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  780. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  781. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  782. # set dialog min size
  783. self.SetMinSize(self.GetSize())
  784. def _createDialogBody(self):
  785. bodySizer = wx.BoxSizer(wx.VERTICAL)
  786. # group selection
  787. bodySizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  788. label = _("Select the group you want to edit or "
  789. "enter name of new group:")),
  790. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP, border = 10)
  791. self.groupSelect = Select(parent = self, type = 'group',
  792. mapsets = [grass.gisenv()['MAPSET']],
  793. size = globalvar.DIALOG_GSELECT_SIZE) # searchpath?
  794. bodySizer.Add(item = self.groupSelect, flag = wx.TOP | wx.EXPAND, border = 5)
  795. bodySizer.AddSpacer(10)
  796. # layers in group
  797. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Layers in selected group:")),
  798. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, border = 5)
  799. gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
  800. gridSizer.AddGrowableCol(0)
  801. self.layerBox = wx.ListBox(parent = self, id = wx.ID_ANY, size = (-1, 150),
  802. style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
  803. gridSizer.Add(item = self.layerBox, pos = (0, 0), span = (2, 1), flag = wx.EXPAND)
  804. self.addLayer = wx.Button(self, id = wx.ID_ADD)
  805. self.addLayer.SetToolTipString(_("Select map layers and add them to the list."))
  806. gridSizer.Add(item = self.addLayer, pos = (0, 1), flag = wx.EXPAND)
  807. self.removeLayer = wx.Button(self, id = wx.ID_REMOVE)
  808. self.removeLayer.SetToolTipString(_("Remove selected layer(s) from list."))
  809. gridSizer.Add(item = self.removeLayer, pos = (1, 1))
  810. bodySizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND)
  811. self.infoLabel = wx.StaticText(parent = self, id = wx.ID_ANY)
  812. bodySizer.Add(item = self.infoLabel,
  813. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, border = 5)
  814. self.subGroup = wx.CheckBox(parent = self, id = wx.ID_ANY,
  815. label = _("Define also sub-group (same name as group)"))
  816. bodySizer.Add(item = self.subGroup, flag = wx.BOTTOM | wx.EXPAND, border = 5)
  817. # bindings
  818. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnGroupSelected)
  819. self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  820. self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
  821. if self.defaultGroup:
  822. self.groupSelect.SetValue(self.defaultGroup)
  823. return bodySizer
  824. def OnAddLayer(self, event):
  825. """!Add new layer to listbox"""
  826. dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
  827. if dlg.ShowModal() != wx.ID_OK:
  828. dlg.Destroy()
  829. return
  830. layers = dlg.GetMapLayers()
  831. for layer in layers:
  832. if layer not in self.GetLayers():
  833. self.layerBox.Append(layer)
  834. self.groupChanged = True
  835. def OnRemoveLayer(self, event):
  836. """!Remove layer from listbox"""
  837. while self.layerBox.GetSelections():
  838. sel = self.layerBox.GetSelections()[0]
  839. self.layerBox.Delete(sel)
  840. self.groupChanged = True
  841. def GetLayers(self):
  842. """!Get layers"""
  843. return self.layerBox.GetItems()
  844. def OnGroupSelected(self, event):
  845. """!Text changed in group selector"""
  846. # callAfter must be called to close popup before other actions
  847. wx.CallAfter(self.GroupSelected)
  848. def GroupSelected(self):
  849. """!Group was selected, check if changes were apllied"""
  850. group = self.GetSelectedGroup()
  851. if self.groupChanged:
  852. dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
  853. "do you want to apply changes?") % self.currentGroup,
  854. caption = _("Unapplied changes"),
  855. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  856. if dlg.ShowModal() == wx.ID_YES:
  857. self.ApplyChanges(showResult = True)
  858. dlg.Destroy()
  859. groups = self.GetExistGroups()
  860. if group in groups:
  861. self.ShowGroupLayers(self.GetGroupLayers(group))
  862. self.currentGroup = group
  863. self.groupChanged = False
  864. self.ClearNotification()
  865. def ShowGroupLayers(self, mapList):
  866. """!Show map layers in currently selected group"""
  867. self.layerBox.Set(mapList)
  868. def EditGroup(self, group):
  869. """!Edit selected group"""
  870. layersNew = self.GetLayers()
  871. layersOld = self.GetGroupLayers(group)
  872. add = []
  873. remove = []
  874. for layerNew in layersNew:
  875. if layerNew not in layersOld:
  876. add.append(layerNew)
  877. for layerOld in layersOld:
  878. if layerOld not in layersNew:
  879. remove.append(layerOld)
  880. kwargs = {}
  881. if self.subGroup.IsChecked():
  882. kwargs['subgroup'] = group
  883. ret = None
  884. if remove:
  885. ret = RunCommand('i.group',
  886. parent = self,
  887. group = group,
  888. flags = 'r',
  889. input = ','.join(remove),
  890. **kwargs)
  891. if add:
  892. ret = RunCommand('i.group',
  893. parent = self,
  894. group = group,
  895. input = ','.join(add),
  896. **kwargs)
  897. return ret
  898. def CreateNewGroup(self, group):
  899. """!Create new group"""
  900. layers = self.GetLayers()
  901. kwargs = {}
  902. if self.subGroup.IsChecked():
  903. kwargs['subgroup'] = group
  904. return RunCommand('i.group',
  905. parent = self,
  906. group = group,
  907. input = layers,
  908. **kwargs)
  909. def GetExistGroups(self):
  910. """!Returns existing groups in current mapset"""
  911. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  912. def ShowResult(self, group, returnCode, create):
  913. """!Show if operation was successfull."""
  914. group += '@' + grass.gisenv()['MAPSET']
  915. if returnCode is None:
  916. label = _("No changes to apply in group <%s>.") % group
  917. elif returnCode == 0:
  918. if create:
  919. label = _("Group <%s> was successfully created.") % group
  920. else:
  921. label = _("Group <%s> was successfully changed.") % group
  922. else:
  923. if create:
  924. label = _("Creating of new group <%s> failed.") % group
  925. else:
  926. label = _("Changing of group <%s> failed.") % group
  927. self.infoLabel.SetLabel(label)
  928. wx.FutureCall(4000, self.ClearNotification)
  929. def GetSelectedGroup(self):
  930. """!Return currently selected group (without mapset)"""
  931. return self.groupSelect.GetValue().split('@')[0]
  932. def GetGroupLayers(self, group):
  933. """!Get layers in group"""
  934. res = RunCommand('i.group',
  935. parent = self,
  936. flags = 'g',
  937. group = group,
  938. read = True).strip()
  939. if res.split('\n')[0]:
  940. return res.split('\n')
  941. return []
  942. def ClearNotification(self):
  943. """!Clear notification string"""
  944. self.infoLabel.SetLabel("")
  945. def ApplyChanges(self, showResult):
  946. """!Create or edit group"""
  947. group = self.currentGroup
  948. if not group:
  949. GMessage(parent = self,
  950. message = _("No group selected."))
  951. return False
  952. groups = self.GetExistGroups()
  953. if group in groups:
  954. ret = self.EditGroup(group)
  955. self.ShowResult(group = group, returnCode = ret, create = False)
  956. else:
  957. ret = self.CreateNewGroup(group)
  958. self.ShowResult(group = group, returnCode = ret, create = True)
  959. self.groupChanged = False
  960. return True
  961. def OnApply(self, event):
  962. """!Apply changes"""
  963. self.ApplyChanges(showResult = True)
  964. def OnOk(self, event):
  965. """!Apply changes and close dialog"""
  966. if self.ApplyChanges(showResult = False):
  967. self.OnClose(event)
  968. def OnClose(self, event):
  969. """!Close dialog"""
  970. if not self.IsModal():
  971. self.Destroy()
  972. event.Skip()
  973. class MapLayersDialogBase(wx.Dialog):
  974. """!Base dialog for selecting map layers (raster, vector).
  975. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  976. MapLayersDialog. Base class contains core functionality.
  977. """
  978. def __init__(self, parent, title,
  979. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  980. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  981. style = style, **kwargs)
  982. self.parent = parent # GMFrame or ?
  983. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  984. # dialog body
  985. self.bodySizer = self._createDialogBody()
  986. self.mainSizer.Add(item = self.bodySizer, proportion = 1,
  987. flag = wx.EXPAND | wx.ALL, border = 5)
  988. # update list of layer to be loaded
  989. self.map_layers = [] # list of map layers (full list type/mapset)
  990. self.LoadMapLayers(self.GetLayerType(cmd = True),
  991. self.mapset.GetStringSelection())
  992. self._fullyQualifiedNames()
  993. self._modelerDSeries()
  994. # buttons
  995. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  996. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  997. btnOk.SetDefault()
  998. # sizers & do layout
  999. self.btnSizer = wx.StdDialogButtonSizer()
  1000. self.btnSizer.AddButton(btnCancel)
  1001. self.btnSizer.AddButton(btnOk)
  1002. self._addApplyButton()
  1003. self.btnSizer.Realize()
  1004. self.mainSizer.Add(item = self.btnSizer, proportion = 0,
  1005. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  1006. self.SetSizer(self.mainSizer)
  1007. self.mainSizer.Fit(self)
  1008. # set dialog min size
  1009. self.SetMinSize(self.GetSize())
  1010. def _modelerDSeries(self):
  1011. """!Method used only by MapLayersDialogForModeler,
  1012. for other subclasses does nothing.
  1013. """
  1014. pass
  1015. def _addApplyButton(self):
  1016. """!Method used only by MapLayersDialog,
  1017. for other subclasses does nothing.
  1018. """
  1019. pass
  1020. def _fullyQualifiedNames(self):
  1021. """!Adds CheckBox which determines is fully qualified names are retuned.
  1022. """
  1023. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1024. label = _("Use fully-qualified map names"))
  1025. self.fullyQualified.SetValue(True)
  1026. self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
  1027. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1028. def _useFullyQualifiedNames(self):
  1029. return self.fullyQualified.IsChecked()
  1030. def _layerTypes(self):
  1031. """!Determines which layer types can be chosen.
  1032. Valid values:
  1033. - raster
  1034. - raster3d
  1035. - vector
  1036. """
  1037. return [_('raster'), _('3D raster'), _('vector')]
  1038. def _selectAll(self):
  1039. """!Check all layers by default"""
  1040. return True
  1041. def _createDialogBody(self):
  1042. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  1043. bodySizer.AddGrowableCol(1)
  1044. bodySizer.AddGrowableRow(3)
  1045. # layer type
  1046. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  1047. flag = wx.ALIGN_CENTER_VERTICAL,
  1048. pos = (0,0))
  1049. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  1050. choices = self._layerTypes(), size = (100,-1))
  1051. self.layerType.SetSelection(0)
  1052. bodySizer.Add(item = self.layerType,
  1053. pos = (0,1))
  1054. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  1055. # select toggle
  1056. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1057. label = _("Select toggle"))
  1058. self.toggle.SetValue(self._selectAll())
  1059. bodySizer.Add(item = self.toggle,
  1060. flag = wx.ALIGN_CENTER_VERTICAL,
  1061. pos = (0,2))
  1062. # mapset filter
  1063. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  1064. flag = wx.ALIGN_CENTER_VERTICAL,
  1065. pos = (1,0))
  1066. self.mapset = MapsetSelect(parent = self, searchPath = True)
  1067. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  1068. bodySizer.Add(item = self.mapset,
  1069. pos = (1,1), span = (1, 2))
  1070. # map name filter
  1071. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  1072. flag = wx.ALIGN_CENTER_VERTICAL,
  1073. pos = (2,0))
  1074. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1075. value = "",
  1076. size = (250,-1))
  1077. bodySizer.Add(item = self.filter,
  1078. flag = wx.EXPAND,
  1079. pos = (2,1), span = (1, 2))
  1080. self.filter.SetFocus()
  1081. self.filter.SetToolTipString(_("Put here regular expression."
  1082. "'.*' means anything, '^' beginning and '$' end."))
  1083. # layer list
  1084. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  1085. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  1086. pos = (3,0))
  1087. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1088. size = (250, 100),
  1089. choices = [])
  1090. bodySizer.Add(item = self.layers,
  1091. flag = wx.EXPAND,
  1092. pos = (3,1), span = (1, 2))
  1093. # bindings
  1094. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  1095. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  1096. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  1097. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  1098. return bodySizer
  1099. def LoadMapLayers(self, type, mapset):
  1100. """!Load list of map layers
  1101. @param type layer type ('raster' or 'vector')
  1102. @param mapset mapset name
  1103. """
  1104. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  1105. self.layers.Set(self.map_layers)
  1106. # check all items by default
  1107. for item in range(self.layers.GetCount()):
  1108. self.layers.Check(item, check = self._selectAll())
  1109. def OnChangeParams(self, event):
  1110. """!Filter parameters changed by user"""
  1111. # update list of layer to be loaded
  1112. self.LoadMapLayers(self.GetLayerType(cmd = True),
  1113. self.mapset.GetStringSelection())
  1114. event.Skip()
  1115. def OnMenu(self, event):
  1116. """!Table description area, context menu"""
  1117. if not hasattr(self, "popupID1"):
  1118. self.popupDataID1 = wx.NewId()
  1119. self.popupDataID2 = wx.NewId()
  1120. self.popupDataID3 = wx.NewId()
  1121. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1122. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  1123. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  1124. # generate popup-menu
  1125. menu = wx.Menu()
  1126. menu.Append(self.popupDataID1, _("Select all"))
  1127. menu.Append(self.popupDataID2, _("Invert selection"))
  1128. menu.Append(self.popupDataID3, _("Deselect all"))
  1129. self.PopupMenu(menu)
  1130. menu.Destroy()
  1131. def OnSelectAll(self, event):
  1132. """!Select all map layer from list"""
  1133. for item in range(self.layers.GetCount()):
  1134. self.layers.Check(item, True)
  1135. def OnSelectInvert(self, event):
  1136. """!Invert current selection"""
  1137. for item in range(self.layers.GetCount()):
  1138. if self.layers.IsChecked(item):
  1139. self.layers.Check(item, False)
  1140. else:
  1141. self.layers.Check(item, True)
  1142. def OnDeselectAll(self, event):
  1143. """!Select all map layer from list"""
  1144. for item in range(self.layers.GetCount()):
  1145. self.layers.Check(item, False)
  1146. def OnFilter(self, event):
  1147. """!Apply filter for map names"""
  1148. if len(event.GetString()) == 0:
  1149. self.layers.Set(self.map_layers)
  1150. return
  1151. list = []
  1152. for layer in self.map_layers:
  1153. try:
  1154. if re.compile(event.GetString()).search(layer):
  1155. list.append(layer)
  1156. except:
  1157. pass
  1158. self.layers.Set(list)
  1159. self.OnSelectAll(None)
  1160. event.Skip()
  1161. def OnToggle(self, event):
  1162. """!Select toggle (check or uncheck all layers)"""
  1163. check = event.Checked()
  1164. for item in range(self.layers.GetCount()):
  1165. self.layers.Check(item, check)
  1166. event.Skip()
  1167. def GetMapLayers(self):
  1168. """!Return list of checked map layers"""
  1169. layerNames = []
  1170. for indx in self.layers.GetSelections():
  1171. # layers.append(self.layers.GetStringSelec(indx))
  1172. pass
  1173. mapset = self.mapset.GetStringSelection()
  1174. for item in range(self.layers.GetCount()):
  1175. if not self.layers.IsChecked(item):
  1176. continue
  1177. if self._useFullyQualifiedNames():
  1178. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  1179. else:
  1180. layerNames.append(self.layers.GetString(item))
  1181. return layerNames
  1182. def GetLayerType(self, cmd = False):
  1183. """!Get selected layer type
  1184. @param cmd True for g.mlist
  1185. """
  1186. if not cmd:
  1187. return self.layerType.GetStringSelection()
  1188. sel = self.layerType.GetSelection()
  1189. if sel == 0:
  1190. ltype = 'rast'
  1191. elif sel == 1:
  1192. ltype = 'rast3d'
  1193. else:
  1194. ltype = 'vect'
  1195. return ltype
  1196. class MapLayersDialog(MapLayersDialogBase):
  1197. """!Subclass of MapLayersDialogBase used in Layer Manager.
  1198. Contains apply button, which sends wxApplyMapLayers event.
  1199. """
  1200. def __init__(self, parent, title, **kwargs):
  1201. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1202. def _addApplyButton(self):
  1203. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  1204. self.btnSizer.AddButton(btnApply)
  1205. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1206. def OnApply(self, event):
  1207. event = wxApplyMapLayers(mapLayers = self.GetMapLayers(), ltype = self.GetLayerType(cmd = True))
  1208. wx.PostEvent(self, event)
  1209. class MapLayersDialogForGroups(MapLayersDialogBase):
  1210. """!Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  1211. Shows only raster maps.
  1212. """
  1213. def __init__(self, parent, title, **kwargs):
  1214. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1215. def _layerTypes(self):
  1216. return [_('raster'),]
  1217. def _selectAll(self):
  1218. """!Could be overriden"""
  1219. return False
  1220. def _fullyQualifiedNames(self):
  1221. pass
  1222. def _useFullyQualifiedNames(self):
  1223. return True
  1224. class MapLayersDialogForModeler(MapLayersDialogBase):
  1225. """!Subclass of MapLayersDialogBase used in Modeler.
  1226. """
  1227. def __init__(self, parent, title, **kwargs):
  1228. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1229. def _modelerDSeries(self):
  1230. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1231. label = _("Dynamic series (%s)") % 'g.mlist')
  1232. self.dseries.SetValue(False)
  1233. self.mainSizer.Add(item = self.dseries, proportion = 0,
  1234. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1235. def GetDSeries(self):
  1236. """!Used by modeler only
  1237. @return g.mlist command
  1238. """
  1239. if not self.dseries or not self.dseries.IsChecked():
  1240. return ''
  1241. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  1242. patt = self.filter.GetValue()
  1243. if patt:
  1244. cond += 'pattern=%s ' % patt
  1245. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1246. return cond
  1247. class ImportDialog(wx.Dialog):
  1248. """!Dialog for bulk import of various data (base class)"""
  1249. def __init__(self, parent, itype,
  1250. id = wx.ID_ANY, title = _("Multiple import"),
  1251. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1252. self.parent = parent # GMFrame
  1253. self.importType = itype
  1254. self.options = dict() # list of options
  1255. self.commandId = -1 # id of running command
  1256. wx.Dialog.__init__(self, parent, id, title, style = style,
  1257. name = "MultiImportDialog")
  1258. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1259. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1260. label = _(" List of %s layers ") % self.importType.upper())
  1261. #
  1262. # list of layers
  1263. #
  1264. columns = [_('Layer id'),
  1265. _('Layer name'),
  1266. _('Name for GRASS map (editable)')]
  1267. if itype == 'ogr':
  1268. columns.insert(2, _('Feature type'))
  1269. self.list = LayersList(parent = self.panel, columns = columns)
  1270. self.list.LoadData()
  1271. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1272. label = "%s" % _("Options"))
  1273. cmd = self._getCommand()
  1274. task = gtask.parse_interface(cmd)
  1275. for f in task.get_options()['flags']:
  1276. name = f.get('name', '')
  1277. desc = f.get('label', '')
  1278. if not desc:
  1279. desc = f.get('description', '')
  1280. if not name and not desc:
  1281. continue
  1282. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  1283. continue
  1284. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  1285. continue
  1286. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  1287. continue
  1288. elif cmd == 'v.external' and name not in ('b'):
  1289. continue
  1290. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  1291. continue
  1292. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1293. label = desc)
  1294. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1295. label = _("Allow output files to overwrite existing files"))
  1296. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1297. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  1298. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1299. label = _("Close dialog on finish"))
  1300. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1301. #
  1302. # buttons
  1303. #
  1304. # cancel
  1305. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1306. self.btn_close.SetToolTipString(_("Close dialog"))
  1307. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1308. # run
  1309. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1310. self.btn_run.SetToolTipString(_("Import selected layers"))
  1311. self.btn_run.SetDefault()
  1312. self.btn_run.Enable(False)
  1313. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1314. # run command dialog
  1315. self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  1316. label = _("Command dialog"))
  1317. self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  1318. def doLayout(self):
  1319. """!Do layout"""
  1320. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1321. # dsn input
  1322. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1323. flag = wx.EXPAND)
  1324. #
  1325. # list of DXF layers
  1326. #
  1327. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1328. layerSizer.Add(item = self.list, proportion = 1,
  1329. flag = wx.ALL | wx.EXPAND, border = 5)
  1330. dialogSizer.Add(item = layerSizer, proportion = 1,
  1331. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1332. # options
  1333. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1334. for key in self.options.keys():
  1335. optionSizer.Add(item = self.options[key], proportion = 0)
  1336. dialogSizer.Add(item = optionSizer, proportion = 0,
  1337. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1338. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1339. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1340. dialogSizer.Add(item = self.add, proportion = 0,
  1341. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1342. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1343. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1344. #
  1345. # buttons
  1346. #
  1347. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1348. btnsizer.Add(item = self.btn_cmd, proportion = 0,
  1349. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1350. border = 10)
  1351. btnsizer.Add(item = self.btn_close, proportion = 0,
  1352. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1353. border = 10)
  1354. btnsizer.Add(item = self.btn_run, proportion = 0,
  1355. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1356. border = 10)
  1357. dialogSizer.Add(item = btnsizer, proportion = 0,
  1358. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1359. border = 10)
  1360. # dialogSizer.SetSizeHints(self.panel)
  1361. self.panel.SetAutoLayout(True)
  1362. self.panel.SetSizer(dialogSizer)
  1363. dialogSizer.Fit(self.panel)
  1364. # auto-layout seems not work here - FIXME
  1365. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1366. self.SetMinSize(size)
  1367. self.SetSize((size.width, size.height + 100))
  1368. # width = self.GetSize()[0]
  1369. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1370. self.Layout()
  1371. def _getCommand(self):
  1372. """!Get command"""
  1373. return ''
  1374. def OnClose(self, event = None):
  1375. """!Close dialog"""
  1376. self.Close()
  1377. def OnRun(self, event):
  1378. """!Import/Link data (each layes as separate vector map)"""
  1379. pass
  1380. def OnCmdDialog(self, event):
  1381. """!Show command dialog"""
  1382. pass
  1383. def AddLayers(self, returncode, cmd = None):
  1384. """!Add imported/linked layers into layer tree"""
  1385. if not self.add.IsChecked() or returncode != 0:
  1386. return
  1387. self.commandId += 1
  1388. maptree = self.parent.curr_page.maptree
  1389. layer, output = self.list.GetLayers()[self.commandId]
  1390. if '@' not in output:
  1391. name = output + '@' + grass.gisenv()['MAPSET']
  1392. else:
  1393. name = output
  1394. # add imported layers into layer tree
  1395. if self.importType == 'gdal':
  1396. cmd = ['d.rast',
  1397. 'map=%s' % name]
  1398. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1399. cmd.append('-n')
  1400. item = maptree.AddLayer(ltype = 'raster',
  1401. lname = name, lchecked = False,
  1402. lcmd = cmd, multiple = False)
  1403. else:
  1404. item = maptree.AddLayer(ltype = 'vector',
  1405. lname = name, lchecked = False,
  1406. lcmd = ['d.vect',
  1407. 'map=%s' % name] + GetDisplayVectSettings(),
  1408. multiple = False)
  1409. maptree.mapdisplay.MapWindow.ZoomToMap()
  1410. def OnAbort(self, event):
  1411. """!Abort running import
  1412. @todo not yet implemented
  1413. """
  1414. pass
  1415. class GdalImportDialog(ImportDialog):
  1416. def __init__(self, parent, ogr = False, link = False):
  1417. """!Dialog for bulk import of various raster/vector data
  1418. @param parent parent window
  1419. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1420. @param link True for linking data otherwise importing data
  1421. """
  1422. self.link = link
  1423. self.ogr = ogr
  1424. if ogr:
  1425. ImportDialog.__init__(self, parent, itype = 'ogr')
  1426. if link:
  1427. self.SetTitle(_("Link external vector data"))
  1428. else:
  1429. self.SetTitle(_("Import vector data"))
  1430. else:
  1431. ImportDialog.__init__(self, parent, itype = 'gdal')
  1432. if link:
  1433. self.SetTitle(_("Link external raster data"))
  1434. else:
  1435. self.SetTitle(_("Import raster data"))
  1436. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1437. ogr = ogr, link = link)
  1438. if link:
  1439. self.add.SetLabel(_("Add linked layers into layer tree"))
  1440. else:
  1441. self.add.SetLabel(_("Add imported layers into layer tree"))
  1442. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1443. if link:
  1444. self.btn_run.SetLabel(_("&Link"))
  1445. self.btn_run.SetToolTipString(_("Link selected layers"))
  1446. if ogr:
  1447. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.external')
  1448. else:
  1449. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.external')
  1450. else:
  1451. self.btn_run.SetLabel(_("&Import"))
  1452. self.btn_run.SetToolTipString(_("Import selected layers"))
  1453. if ogr:
  1454. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.in.ogr')
  1455. else:
  1456. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.in.gdal')
  1457. self.doLayout()
  1458. def OnRun(self, event):
  1459. """!Import/Link data (each layes as separate vector map)"""
  1460. self.commandId = -1
  1461. data = self.list.GetLayers()
  1462. if not data:
  1463. GMessage(_("No layers selected. Operation canceled."),
  1464. parent = self)
  1465. return
  1466. dsn = self.dsnInput.GetDsn()
  1467. ext = self.dsnInput.GetFormatExt()
  1468. # determine data driver for PostGIS links
  1469. popOGR = False
  1470. if self.importType == 'ogr' and \
  1471. self.dsnInput.GetType() == 'db' and \
  1472. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1473. 'GRASS_VECTOR_OGR' not in os.environ:
  1474. popOGR = True
  1475. os.environ['GRASS_VECTOR_OGR'] = '1'
  1476. for layer, output in data:
  1477. if self.importType == 'ogr':
  1478. if ext and layer.rfind(ext) > -1:
  1479. layer = layer.replace('.' + ext, '')
  1480. if self.link:
  1481. cmd = ['v.external',
  1482. 'dsn=%s' % dsn,
  1483. 'output=%s' % output,
  1484. 'layer=%s' % layer]
  1485. else:
  1486. cmd = ['v.in.ogr',
  1487. 'dsn=%s' % dsn,
  1488. 'layer=%s' % layer,
  1489. 'output=%s' % output]
  1490. else: # gdal
  1491. if self.dsnInput.GetType() == 'dir':
  1492. idsn = os.path.join(dsn, layer)
  1493. else:
  1494. idsn = dsn
  1495. if self.link:
  1496. cmd = ['r.external',
  1497. 'input=%s' % idsn,
  1498. 'output=%s' % output]
  1499. else:
  1500. cmd = ['r.in.gdal',
  1501. 'input=%s' % idsn,
  1502. 'output=%s' % output]
  1503. if self.overwrite.IsChecked():
  1504. cmd.append('--overwrite')
  1505. for key in self.options.keys():
  1506. if self.options[key].IsChecked():
  1507. cmd.append('-%s' % key)
  1508. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1509. '--overwrite' not in cmd:
  1510. cmd.append('--overwrite')
  1511. # run in Layer Manager
  1512. self.parent.goutput.RunCmd(cmd, switchPage = True,
  1513. onDone = self.AddLayers)
  1514. if popOGR:
  1515. os.environ.pop('GRASS_VECTOR_OGR')
  1516. if self.closeOnFinish.IsChecked():
  1517. self.Close()
  1518. def _getCommand(self):
  1519. """!Get command"""
  1520. if self.link:
  1521. if self.ogr:
  1522. return 'v.external'
  1523. else:
  1524. return 'r.external'
  1525. else:
  1526. if self.ogr:
  1527. return 'v.in.ogr'
  1528. else:
  1529. return 'r.in.gdal'
  1530. return ''
  1531. def OnCmdDialog(self, event):
  1532. """!Show command dialog"""
  1533. name = self._getCommand()
  1534. GUI(parent = self, modal = False).ParseCommand(cmd = [name])
  1535. class GdalOutputDialog(wx.Dialog):
  1536. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1537. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1538. """!Dialog for setting output format for rasters/vectors
  1539. @param parent parent window
  1540. @param id window id
  1541. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1542. @param style window style
  1543. @param *kwargs other wx.Dialog's arguments
  1544. """
  1545. self.parent = parent # GMFrame
  1546. self.ogr = ogr
  1547. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1548. if self.ogr:
  1549. self.SetTitle(_("Define output format for vector data"))
  1550. else:
  1551. self.SetTitle(_("Define output format for raster data"))
  1552. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1553. # buttons
  1554. self.btnCmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  1555. label = _("Command dialog"))
  1556. self.btnCmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  1557. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1558. self.btnCancel.SetToolTipString(_("Close dialog"))
  1559. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1560. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1561. self.btnOk.SetDefault()
  1562. self.btnOk.Enable(False)
  1563. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1564. ogr = ogr,
  1565. exclude = ['file', 'protocol'], dest = True)
  1566. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1567. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1568. self._layout()
  1569. def _layout(self):
  1570. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1571. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1572. flag = wx.EXPAND)
  1573. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1574. btnSizer.Add(item = self.btnCmd, proportion = 0,
  1575. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1576. border = 10)
  1577. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1578. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1579. border = 10)
  1580. btnSizer.Add(item = self.btnOk, proportion = 0,
  1581. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1582. border = 10)
  1583. dialogSizer.Add(item = btnSizer, proportion = 0,
  1584. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1585. border = 10)
  1586. self.panel.SetAutoLayout(True)
  1587. self.panel.SetSizer(dialogSizer)
  1588. dialogSizer.Fit(self.panel)
  1589. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1590. self.SetMinSize(size)
  1591. self.SetSize((size.width, size.height))
  1592. self.Layout()
  1593. def OnCmdDialog(self, event):
  1594. GUI(parent = self, modal = True).ParseCommand(cmd = ['v.external.out'])
  1595. def OnCancel(self, event):
  1596. self.Destroy()
  1597. def OnOK(self, event):
  1598. if self.dsnInput.GetType() == 'native':
  1599. RunCommand('v.external.out',
  1600. parent = self,
  1601. flags = 'r')
  1602. else:
  1603. dsn = self.dsnInput.GetDsn()
  1604. frmt = self.dsnInput.GetFormat()
  1605. options = self.dsnInput.GetOptions()
  1606. RunCommand('v.external.out',
  1607. parent = self,
  1608. dsn = dsn, format = frmt,
  1609. options = options)
  1610. self.Close()
  1611. class DxfImportDialog(ImportDialog):
  1612. """!Dialog for bulk import of DXF layers"""
  1613. def __init__(self, parent):
  1614. ImportDialog.__init__(self, parent, itype = 'dxf',
  1615. title = _("Import DXF layers"))
  1616. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1617. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1618. dialogTitle = _('Choose DXF file to import'),
  1619. buttonText = _('Browse'),
  1620. startDirectory = os.getcwd(), fileMode = 0,
  1621. changeCallback = self.OnSetDsn,
  1622. fileMask = "DXF File (*.dxf)|*.dxf")
  1623. self.add.SetLabel(_("Add imported layers into layer tree"))
  1624. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1625. self.doLayout()
  1626. def _getCommand(self):
  1627. """!Get command"""
  1628. return 'v.in.dxf'
  1629. def OnRun(self, event):
  1630. """!Import/Link data (each layes as separate vector map)"""
  1631. data = self.list.GetLayers()
  1632. # hide dialog
  1633. self.Hide()
  1634. inputDxf = self.dsnInput.GetValue()
  1635. for layer, output in data:
  1636. cmd = ['v.in.dxf',
  1637. 'input=%s' % inputDxf,
  1638. 'layers=%s' % layer,
  1639. 'output=%s' % output]
  1640. for key in self.options.keys():
  1641. if self.options[key].IsChecked():
  1642. cmd.append('-%s' % key)
  1643. if self.overwrite.IsChecked() or \
  1644. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1645. cmd.append('--overwrite')
  1646. # run in Layer Manager
  1647. self.parent.goutput.RunCmd(cmd, switchPage = True,
  1648. onDone = self.AddLayers)
  1649. self.OnCancel()
  1650. def OnSetDsn(self, event):
  1651. """!Input DXF file defined, update list of layer widget"""
  1652. path = event.GetString()
  1653. if not path:
  1654. return
  1655. data = list()
  1656. ret = RunCommand('v.in.dxf',
  1657. quiet = True,
  1658. parent = self,
  1659. read = True,
  1660. flags = 'l',
  1661. input = path)
  1662. if not ret:
  1663. self.list.LoadData()
  1664. self.btn_run.Enable(False)
  1665. return
  1666. for line in ret.splitlines():
  1667. layerId = line.split(':')[0].split(' ')[1]
  1668. layerName = line.split(':')[1].strip()
  1669. grassName = GetValidLayerName(layerName)
  1670. data.append((layerId, layerName.strip(), grassName.strip()))
  1671. self.list.LoadData(data)
  1672. if len(data) > 0:
  1673. self.btn_run.Enable(True)
  1674. else:
  1675. self.btn_run.Enable(False)
  1676. def OnCmdDialog(self, event):
  1677. """!Show command dialog"""
  1678. GUI(parent = self, modal = True).ParseCommand(cmd = ['v.in.dxf'])
  1679. class LayersList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin,
  1680. listmix.CheckListCtrlMixin, listmix.TextEditMixin):
  1681. """!List of layers to be imported (dxf, shp...)"""
  1682. def __init__(self, parent, columns, log = None):
  1683. self.parent = parent
  1684. wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
  1685. style = wx.LC_REPORT)
  1686. listmix.CheckListCtrlMixin.__init__(self)
  1687. self.log = log
  1688. # setup mixins
  1689. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1690. listmix.TextEditMixin.__init__(self)
  1691. for i in range(len(columns)):
  1692. self.InsertColumn(i, columns[i])
  1693. if len(columns) == 3:
  1694. width = (65, 200)
  1695. else:
  1696. width = (65, 180, 110)
  1697. for i in range(len(width)):
  1698. self.SetColumnWidth(col = i, width = width[i])
  1699. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) #wxMSW
  1700. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) #wxGTK
  1701. def LoadData(self, data = None):
  1702. """!Load data into list"""
  1703. self.DeleteAllItems()
  1704. if data is None:
  1705. return
  1706. for item in data:
  1707. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1708. for i in range(1, len(item)):
  1709. self.SetStringItem(index, i, "%s" % str(item[i]))
  1710. # check by default only on one item
  1711. if len(data) == 1:
  1712. self.CheckItem(index, True)
  1713. def OnPopupMenu(self, event):
  1714. """!Show popup menu"""
  1715. if self.GetItemCount() < 1:
  1716. return
  1717. if not hasattr(self, "popupDataID1"):
  1718. self.popupDataID1 = wx.NewId()
  1719. self.popupDataID2 = wx.NewId()
  1720. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1721. self.Bind(wx.EVT_MENU, self.OnSelectNone, id = self.popupDataID2)
  1722. # generate popup-menu
  1723. menu = wx.Menu()
  1724. menu.Append(self.popupDataID1, _("Select all"))
  1725. menu.Append(self.popupDataID2, _("Deselect all"))
  1726. self.PopupMenu(menu)
  1727. menu.Destroy()
  1728. def OnSelectAll(self, event):
  1729. """!Select all items"""
  1730. item = -1
  1731. while True:
  1732. item = self.GetNextItem(item)
  1733. if item == -1:
  1734. break
  1735. self.CheckItem(item, True)
  1736. event.Skip()
  1737. def OnSelectNone(self, event):
  1738. """!Deselect items"""
  1739. item = -1
  1740. while True:
  1741. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  1742. if item == -1:
  1743. break
  1744. self.CheckItem(item, False)
  1745. event.Skip()
  1746. def OnLeftDown(self, event):
  1747. """!Allow editing only output name
  1748. Code taken from TextEditMixin class.
  1749. """
  1750. x, y = event.GetPosition()
  1751. colLocs = [0]
  1752. loc = 0
  1753. for n in range(self.GetColumnCount()):
  1754. loc = loc + self.GetColumnWidth(n)
  1755. colLocs.append(loc)
  1756. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1757. if col == self.GetColumnCount() - 1:
  1758. listmix.TextEditMixin.OnLeftDown(self, event)
  1759. else:
  1760. event.Skip()
  1761. def GetLayers(self):
  1762. """!Get list of layers (layer name, output name)"""
  1763. data = []
  1764. item = -1
  1765. while True:
  1766. item = self.GetNextItem(item)
  1767. if item == -1:
  1768. break
  1769. if not self.IsChecked(item):
  1770. continue
  1771. # layer / output name
  1772. data.append((self.GetItem(item, 1).GetText(),
  1773. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1774. return data
  1775. class SetOpacityDialog(wx.Dialog):
  1776. """!Set opacity of map layers"""
  1777. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1778. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1779. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1780. self.parent = parent # GMFrame
  1781. self.opacity = opacity # current opacity
  1782. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1783. size = size, style = style, title = title)
  1784. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1785. sizer = wx.BoxSizer(wx.VERTICAL)
  1786. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1787. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1788. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1789. wx.SL_TOP | wx.SL_LABELS,
  1790. minValue = 0, maxValue = 100,
  1791. size = (350, -1))
  1792. box.Add(item = self.value,
  1793. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1794. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1795. label = _("transparent")),
  1796. pos = (1, 0))
  1797. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1798. label = _("opaque")),
  1799. flag = wx.ALIGN_RIGHT,
  1800. pos = (1, 1))
  1801. sizer.Add(item = box, proportion = 0,
  1802. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1803. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1804. style = wx.LI_HORIZONTAL)
  1805. sizer.Add(item = line, proportion = 0,
  1806. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1807. # buttons
  1808. btnsizer = wx.StdDialogButtonSizer()
  1809. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1810. btnOK.SetDefault()
  1811. btnsizer.AddButton(btnOK)
  1812. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1813. btnsizer.AddButton(btnCancel)
  1814. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1815. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1816. btnsizer.AddButton(btnApply)
  1817. btnsizer.Realize()
  1818. sizer.Add(item = btnsizer, proportion = 0,
  1819. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1820. panel.SetSizer(sizer)
  1821. sizer.Fit(panel)
  1822. self.SetSize(self.GetBestSize())
  1823. self.Layout()
  1824. def GetOpacity(self):
  1825. """!Button 'OK' pressed"""
  1826. # return opacity value
  1827. opacity = float(self.value.GetValue()) / 100
  1828. return opacity
  1829. def OnApply(self, event):
  1830. event = wxApplyOpacity(value = self.GetOpacity())
  1831. wx.PostEvent(self, event)
  1832. def GetImageHandlers(image):
  1833. """!Get list of supported image handlers"""
  1834. lext = list()
  1835. ltype = list()
  1836. for h in image.GetHandlers():
  1837. lext.append(h.GetExtension())
  1838. filetype = ''
  1839. if 'png' in lext:
  1840. filetype += "PNG file (*.png)|*.png|"
  1841. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1842. 'ext' : 'png' })
  1843. filetype += "BMP file (*.bmp)|*.bmp|"
  1844. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1845. 'ext' : 'bmp' })
  1846. if 'gif' in lext:
  1847. filetype += "GIF file (*.gif)|*.gif|"
  1848. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1849. 'ext' : 'gif' })
  1850. if 'jpg' in lext:
  1851. filetype += "JPG file (*.jpg)|*.jpg|"
  1852. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1853. 'ext' : 'jpg' })
  1854. if 'pcx' in lext:
  1855. filetype += "PCX file (*.pcx)|*.pcx|"
  1856. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1857. 'ext' : 'pcx' })
  1858. if 'pnm' in lext:
  1859. filetype += "PNM file (*.pnm)|*.pnm|"
  1860. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1861. 'ext' : 'pnm' })
  1862. if 'tif' in lext:
  1863. filetype += "TIF file (*.tif)|*.tif|"
  1864. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1865. 'ext' : 'tif' })
  1866. if 'xpm' in lext:
  1867. filetype += "XPM file (*.xpm)|*.xpm"
  1868. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1869. 'ext' : 'xpm' })
  1870. return filetype, ltype
  1871. class ImageSizeDialog(wx.Dialog):
  1872. """!Set size for saved graphic file"""
  1873. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1874. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1875. self.parent = parent
  1876. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1877. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1878. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1879. label = ' % s' % _("Image size"))
  1880. size = self.parent.GetWindow().GetClientSize()
  1881. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1882. style = wx.SP_ARROW_KEYS)
  1883. self.width.SetRange(20, 1e6)
  1884. self.width.SetValue(size.width)
  1885. wx.CallAfter(self.width.SetFocus)
  1886. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1887. style = wx.SP_ARROW_KEYS)
  1888. self.height.SetRange(20, 1e6)
  1889. self.height.SetValue(size.height)
  1890. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1891. size = (125, -1),
  1892. choices = [ "",
  1893. "640x480",
  1894. "800x600",
  1895. "1024x768",
  1896. "1280x960",
  1897. "1600x1200",
  1898. "1920x1440" ])
  1899. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1900. self.btnOK.SetDefault()
  1901. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1902. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1903. self._layout()
  1904. self.SetSize(self.GetBestSize())
  1905. def _layout(self):
  1906. """!Do layout"""
  1907. sizer = wx.BoxSizer(wx.VERTICAL)
  1908. # body
  1909. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1910. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1911. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1912. label = _("Width:")),
  1913. flag = wx.ALIGN_CENTER_VERTICAL)
  1914. fbox.Add(item = self.width)
  1915. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1916. label = _("Height:")),
  1917. flag = wx.ALIGN_CENTER_VERTICAL)
  1918. fbox.Add(item = self.height)
  1919. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1920. label = _("Template:")),
  1921. flag = wx.ALIGN_CENTER_VERTICAL)
  1922. fbox.Add(item = self.template)
  1923. box.Add(item = fbox, proportion = 1,
  1924. flag = wx.EXPAND | wx.ALL, border = 5)
  1925. sizer.Add(item = box, proportion = 1,
  1926. flag=wx.EXPAND | wx.ALL, border = 3)
  1927. # buttons
  1928. btnsizer = wx.StdDialogButtonSizer()
  1929. btnsizer.AddButton(self.btnOK)
  1930. btnsizer.AddButton(self.btnCancel)
  1931. btnsizer.Realize()
  1932. sizer.Add(item = btnsizer, proportion = 0,
  1933. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1934. self.panel.SetSizer(sizer)
  1935. sizer.Fit(self.panel)
  1936. self.Layout()
  1937. def GetValues(self):
  1938. """!Get width/height values"""
  1939. return self.width.GetValue(), self.height.GetValue()
  1940. def OnTemplate(self, event):
  1941. """!Template selected"""
  1942. sel = event.GetString()
  1943. if not sel:
  1944. width, height = self.parent.GetWindow().GetClientSize()
  1945. else:
  1946. width, height = map(int, sel.split('x'))
  1947. self.width.SetValue(width)
  1948. self.height.SetValue(height)
  1949. class SqlQueryFrame(wx.Frame):
  1950. def __init__(self, parent, id = wx.ID_ANY,
  1951. title = _("GRASS GIS SQL Query Utility"),
  1952. *kwargs):
  1953. """!SQL Query Utility window
  1954. """
  1955. self.parent = parent
  1956. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1957. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1958. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1959. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1960. label = _(" SQL statement "))
  1961. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1962. style = wx.TE_MULTILINE)
  1963. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1964. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1965. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1966. self._layout()
  1967. self.SetMinSize(wx.Size(300, 150))
  1968. self.SetSize(wx.Size(500, 200))
  1969. def _layout(self):
  1970. """!Do layout"""
  1971. sizer = wx.BoxSizer(wx.VERTICAL)
  1972. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1973. sqlSizer.Add(item = self.sql, proportion = 1,
  1974. flag = wx.EXPAND)
  1975. btnSizer = wx.StdDialogButtonSizer()
  1976. btnSizer.AddButton(self.btnApply)
  1977. btnSizer.AddButton(self.btnCancel)
  1978. btnSizer.Realize()
  1979. sizer.Add(item = sqlSizer, proportion = 1,
  1980. flag = wx.EXPAND | wx.ALL, border = 5)
  1981. sizer.Add(item = btnSizer, proportion = 0,
  1982. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1983. self.panel.SetSizer(sizer)
  1984. self.Layout()
  1985. def OnCloseWindow(self, event):
  1986. """!Close window
  1987. """
  1988. self.Close()
  1989. class SymbolDialog(wx.Dialog):
  1990. """!Dialog for GRASS symbols selection.
  1991. Dialog is called in gui_core::forms module.
  1992. """
  1993. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  1994. """!Dialog constructor.
  1995. It is assumed that symbolPath contains folders with symbols.
  1996. @param parent dialog parent
  1997. @param symbolPath absolute path to symbols
  1998. @param currentSymbol currently selected symbol (e.g. 'basic/x')
  1999. @param title dialog title
  2000. """
  2001. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  2002. self.symbolPath = symbolPath
  2003. self.currentSymbol = currentSymbol # default basic/x
  2004. self.selected = None
  2005. self.selectedDir = None
  2006. self._layout()
  2007. def _layout(self):
  2008. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  2009. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2010. vSizer = wx.BoxSizer( wx.VERTICAL)
  2011. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  2012. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  2013. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  2014. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  2015. proportion = 0,
  2016. flag = wx.ALIGN_CENTER_VERTICAL)
  2017. fgSizer.Add(item = self.folderChoice, proportion = 0,
  2018. flag = wx.ALIGN_CENTER, border = 0)
  2019. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  2020. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  2021. flag = wx.ALIGN_CENTRE_VERTICAL)
  2022. fgSizer.Add(self.infoLabel, proportion = 0,
  2023. flag = wx.ALIGN_CENTRE_VERTICAL)
  2024. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  2025. self.panels = self._createSymbolPanels(mainPanel)
  2026. for panel in self.panels:
  2027. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2028. panel.Bind(EVT_SYMBOL_SELECTION_CHANGED, self.SelectionChanged)
  2029. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  2030. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  2031. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  2032. self.btnOK.SetDefault()
  2033. self.btnOK.Enable(False)
  2034. # buttons
  2035. btnSizer = wx.StdDialogButtonSizer()
  2036. btnSizer.AddButton(self.btnCancel)
  2037. btnSizer.AddButton(self.btnOK)
  2038. btnSizer.Realize()
  2039. mainSizer.Add(item = btnSizer, proportion = 0,
  2040. flag = wx.EXPAND | wx.ALL, border = 5)
  2041. # show panel with the largest number of images and fit size
  2042. count = []
  2043. for folder in os.listdir(self.symbolPath):
  2044. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  2045. index = count.index(max(count))
  2046. self.folderChoice.SetSelection(index)
  2047. self.OnFolderSelect(None)
  2048. self.infoLabel.Show()
  2049. mainPanel.SetSizerAndFit(mainSizer)
  2050. self.SetSize(self.GetBestSize())
  2051. # show currently selected symbol
  2052. if self.currentSymbol:
  2053. # set directory
  2054. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  2055. self.folderChoice.SetStringSelection(self.selectedDir)
  2056. # select symbol
  2057. panelIdx = self.folderChoice.GetSelection()
  2058. for panel in self.symbolPanels[panelIdx]:
  2059. if panel.GetName() == self.selected:
  2060. panel.Select()
  2061. else:
  2062. self.folderChoice.SetSelection(0)
  2063. self.OnFolderSelect(None)
  2064. def _createSymbolPanels(self, parent):
  2065. """!Creates multiple panels with symbols.
  2066. Panels are shown/hidden according to selected folder."""
  2067. folders = os.listdir(self.symbolPath)
  2068. panels = []
  2069. self.symbolPanels = []
  2070. maxImages = 0
  2071. for folder in folders:
  2072. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  2073. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  2074. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  2075. symbolPanels = []
  2076. for img in images:
  2077. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  2078. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  2079. symbolPanels.append(iP)
  2080. panel.SetSizerAndFit(sizer)
  2081. panel.Hide()
  2082. panels.append(panel)
  2083. self.symbolPanels.append(symbolPanels)
  2084. return panels
  2085. def _getSymbols(self, path):
  2086. # we assume that images are in subfolders (1 level only)
  2087. imageList = []
  2088. for image in os.listdir(path):
  2089. imageList.append(os.path.join(path, image))
  2090. return sorted(imageList)
  2091. def OnFolderSelect(self, event):
  2092. """!Selected folder with symbols changed."""
  2093. idx = self.folderChoice.GetSelection()
  2094. for i in range(len(self.panels)):
  2095. sizer = self.panels[i].GetContainingSizer()
  2096. sizer.Show(self.panels[i], i == idx, recursive = True)
  2097. sizer.Layout()
  2098. if self.selectedDir == self.folderChoice.GetStringSelection():
  2099. self.btnOK.Enable()
  2100. self.infoLabel.SetLabel(self.selected)
  2101. else:
  2102. self.btnOK.Disable()
  2103. self.infoLabel.SetLabel('')
  2104. def SelectionChanged(self, event):
  2105. """!Selected symbol changed."""
  2106. if event.doubleClick:
  2107. self.EndModal(wx.ID_OK)
  2108. # deselect all
  2109. for i in range(len(self.panels)):
  2110. for panel in self.symbolPanels[i]:
  2111. if panel.GetName() != event.name:
  2112. panel.Deselect()
  2113. self.btnOK.Enable()
  2114. self.selected = event.name
  2115. self.selectedDir = self.folderChoice.GetStringSelection()
  2116. self.infoLabel.SetLabel(event.name)
  2117. def GetSelectedSymbolName(self):
  2118. """!Returns currently selected symbol name (e.g. 'basic/x').
  2119. """
  2120. # separator must be '/' and not dependent on OS
  2121. return self.selectedDir + '/' + self.selected
  2122. def GetSelectedSymbolPath(self):
  2123. """!Returns currently selected symbol full path.
  2124. """
  2125. return os.path.join(self.symbolPath, self.selectedDir, self.selected)