dialogs.py 93 KB

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