dialogs.py 98 KB

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