dialogs.py 98 KB

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