dialogs.py 93 KB

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