dialogs.py 94 KB

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