dialogs.py 97 KB

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