dialogs.py 96 KB

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