dialogs.py 97 KB

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