dialogs.py 95 KB

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