dialogs.py 103 KB

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