dialogs.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592
  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,
  733. fullyQualified = False) # searchpath?
  734. bodySizer.Add(item = self.groupSelect, flag = wx.TOP | wx.EXPAND, border = 5)
  735. bodySizer.AddSpacer(10)
  736. # layers in group
  737. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Raster maps in selected group:")),
  738. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, border = 5)
  739. buttonSizer = wx.BoxSizer(wx.VERTICAL)
  740. listSizer = wx.BoxSizer(wx.HORIZONTAL)
  741. self.layerBox = wx.ListBox(parent = self, id = wx.ID_ANY, size = (-1, 150),
  742. style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
  743. listSizer.Add(item = self.layerBox, proportion = 1, flag = wx.EXPAND)
  744. self.addLayer = wx.Button(self, id = wx.ID_ADD)
  745. self.addLayer.SetToolTipString(_("Select map layers and add them to the list."))
  746. buttonSizer.Add(item = self.addLayer, flag = wx.BOTTOM, border = 10)
  747. self.removeLayer = wx.Button(self, id = wx.ID_REMOVE)
  748. self.removeLayer.SetToolTipString(_("Remove selected layer(s) from list."))
  749. buttonSizer.Add(item = self.removeLayer)
  750. listSizer.Add(item = buttonSizer, flag = wx.LEFT, border = 5)
  751. bodySizer.Add(item = listSizer, proportion = 1, flag = wx.EXPAND)
  752. self.infoLabel = wx.StaticText(parent = self, id = wx.ID_ANY)
  753. bodySizer.Add(item = self.infoLabel,
  754. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, border = 5)
  755. # TODO: subgroup can have a different name than the group
  756. # self.subGroup must be a text field, not a checkbox
  757. #self.subGroup = wx.CheckBox(parent = self, id = wx.ID_ANY,
  758. # label = _("Define also sub-group (same name as group)"))
  759. #self.subGroup.SetValue(True) # most of imagery modules requires also subgroup
  760. #bodySizer.Add(item = self.subGroup, flag = wx.BOTTOM | wx.EXPAND, border = 5)
  761. # bindings
  762. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnGroupSelected)
  763. self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  764. self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
  765. if self.defaultGroup:
  766. self.groupSelect.SetValue(self.defaultGroup)
  767. return bodySizer
  768. def OnAddLayer(self, event):
  769. """!Add new layer to listbox"""
  770. dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
  771. if dlg.ShowModal() != wx.ID_OK:
  772. dlg.Destroy()
  773. return
  774. layers = dlg.GetMapLayers()
  775. for layer in layers:
  776. if layer not in self.GetLayers():
  777. self.layerBox.Append(layer)
  778. self.groupChanged = True
  779. def OnRemoveLayer(self, event):
  780. """!Remove layer from listbox"""
  781. while self.layerBox.GetSelections():
  782. sel = self.layerBox.GetSelections()[0]
  783. self.layerBox.Delete(sel)
  784. self.groupChanged = True
  785. def GetLayers(self):
  786. """!Get layers"""
  787. return self.layerBox.GetItems()
  788. def OnGroupSelected(self, event):
  789. """!Text changed in group selector"""
  790. # callAfter must be called to close popup before other actions
  791. wx.CallAfter(self.GroupSelected)
  792. def GroupSelected(self):
  793. """!Group was selected, check if changes were apllied"""
  794. group = self.GetSelectedGroup()
  795. if self.currentGroup and self.groupChanged:
  796. dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
  797. "do you want to apply changes?") % self.currentGroup,
  798. caption = _("Unapplied changes"),
  799. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  800. if dlg.ShowModal() == wx.ID_YES:
  801. self.ApplyChanges()
  802. dlg.Destroy()
  803. maps = list()
  804. groups = self.GetExistGroups()
  805. if group in groups:
  806. maps = self.GetGroupLayers(group)
  807. self.ShowGroupLayers(maps)
  808. self.currentGroup = group
  809. self.groupChanged = False
  810. self.ClearNotification()
  811. def ShowGroupLayers(self, mapList):
  812. """!Show map layers in currently selected group"""
  813. self.layerBox.Set(mapList)
  814. def EditGroup(self, group):
  815. """!Edit selected group"""
  816. layersNew = self.GetLayers()
  817. layersOld = self.GetGroupLayers(group)
  818. add = []
  819. remove = []
  820. for layerNew in layersNew:
  821. if layerNew not in layersOld:
  822. add.append(layerNew)
  823. for layerOld in layersOld:
  824. if layerOld not in layersNew:
  825. remove.append(layerOld)
  826. kwargs = {}
  827. # TODO: self.subGroup must be a text field
  828. #if self.subGroup.IsChecked():
  829. # kwargs['subgroup'] = group
  830. ret = None
  831. if remove:
  832. ret = RunCommand('i.group',
  833. parent = self,
  834. group = group,
  835. flags = 'r',
  836. input = ','.join(remove),
  837. **kwargs)
  838. if add:
  839. ret = RunCommand('i.group',
  840. parent = self,
  841. group = group,
  842. input = ','.join(add),
  843. **kwargs)
  844. return ret
  845. def CreateNewGroup(self, group):
  846. """!Create new group"""
  847. layers = self.GetLayers()
  848. if not layers:
  849. GMessage(parent = self,
  850. message = _("No raster maps selected."))
  851. return 1
  852. kwargs = {}
  853. # TODO: self.subGroup must be a text field
  854. #if self.subGroup.IsChecked():
  855. # kwargs['subgroup'] = group
  856. return RunCommand('i.group',
  857. parent = self,
  858. group = group,
  859. input = layers,
  860. **kwargs)
  861. def GetExistGroups(self):
  862. """!Returns existing groups in current mapset"""
  863. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  864. def ShowResult(self, group, returnCode, create):
  865. """!Show if operation was successfull."""
  866. group += '@' + grass.gisenv()['MAPSET']
  867. if returnCode is None:
  868. label = _("No changes to apply in group <%s>.") % group
  869. elif returnCode == 0:
  870. if create:
  871. label = _("Group <%s> was successfully created.") % group
  872. else:
  873. label = _("Group <%s> was successfully changed.") % group
  874. else:
  875. if create:
  876. label = _("Creating of new group <%s> failed.") % group
  877. else:
  878. label = _("Changing of group <%s> failed.") % group
  879. self.infoLabel.SetLabel(label)
  880. wx.FutureCall(4000, self.ClearNotification)
  881. def GetSelectedGroup(self):
  882. """!Return currently selected group (without mapset)"""
  883. return self.groupSelect.GetValue().split('@')[0]
  884. def GetGroupLayers(self, group):
  885. """!Get layers in group"""
  886. kwargs = dict()
  887. kwargs['group'] = group
  888. # TODO: self.subGroup must be a text field
  889. #if self.subGroup.IsChecked():
  890. # kwargs['subgroup'] = group
  891. res = RunCommand('i.group',
  892. parent = self,
  893. flags = 'g',
  894. read = True, **kwargs)
  895. if not res:
  896. return []
  897. return res.splitlines()
  898. def ClearNotification(self):
  899. """!Clear notification string"""
  900. self.infoLabel.SetLabel("")
  901. def ApplyChanges(self):
  902. """!Create or edit group"""
  903. group = self.currentGroup
  904. if not group:
  905. GMessage(parent = self,
  906. message = _("No group selected."))
  907. return False
  908. groups = self.GetExistGroups()
  909. if group in groups:
  910. ret = self.EditGroup(group)
  911. self.ShowResult(group = group, returnCode = ret, create = False)
  912. else:
  913. ret = self.CreateNewGroup(group)
  914. self.ShowResult(group = group, returnCode = ret, create = True)
  915. self.groupChanged = False
  916. return True
  917. def OnApply(self, event):
  918. """!Apply changes"""
  919. self.ApplyChanges()
  920. def OnOk(self, event):
  921. """!Apply changes and close dialog"""
  922. if self.ApplyChanges():
  923. self.OnClose(event)
  924. def OnClose(self, event):
  925. """!Close dialog"""
  926. if not self.IsModal():
  927. self.Destroy()
  928. event.Skip()
  929. class MapLayersDialogBase(wx.Dialog):
  930. """!Base dialog for selecting map layers (raster, vector).
  931. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  932. MapLayersDialog. Base class contains core functionality.
  933. """
  934. def __init__(self, parent, title,
  935. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  936. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  937. style = style, **kwargs)
  938. self.parent = parent # GMFrame or ?
  939. self.applyAddingMapLayers = Signal('MapLayersDialogBase.applyAddingMapLayers')
  940. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  941. # dialog body
  942. self.bodySizer = self._createDialogBody()
  943. self.mainSizer.Add(item = self.bodySizer, proportion = 1,
  944. flag = wx.EXPAND | wx.ALL, border = 5)
  945. # update list of layer to be loaded
  946. self.map_layers = [] # list of map layers (full list type/mapset)
  947. self.LoadMapLayers(self.GetLayerType(cmd = True),
  948. self.mapset.GetStringSelection())
  949. self._fullyQualifiedNames()
  950. self._modelerDSeries()
  951. # buttons
  952. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  953. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  954. btnOk.SetDefault()
  955. # sizers & do layout
  956. self.btnSizer = wx.StdDialogButtonSizer()
  957. self.btnSizer.AddButton(btnCancel)
  958. self.btnSizer.AddButton(btnOk)
  959. self._addApplyButton()
  960. self.btnSizer.Realize()
  961. self.mainSizer.Add(item = self.btnSizer, proportion = 0,
  962. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  963. self.SetSizer(self.mainSizer)
  964. self.mainSizer.Fit(self)
  965. # set dialog min size
  966. self.SetMinSize(self.GetSize())
  967. def _modelerDSeries(self):
  968. """!Method used only by MapLayersDialogForModeler,
  969. for other subclasses does nothing.
  970. """
  971. pass
  972. def _addApplyButton(self):
  973. """!Method used only by MapLayersDialog,
  974. for other subclasses does nothing.
  975. """
  976. pass
  977. def _fullyQualifiedNames(self):
  978. """!Adds CheckBox which determines is fully qualified names are retuned.
  979. """
  980. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  981. label = _("Use fully-qualified map names"))
  982. self.fullyQualified.SetValue(True)
  983. self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
  984. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  985. def _useFullyQualifiedNames(self):
  986. return self.fullyQualified.IsChecked()
  987. def _layerTypes(self):
  988. """!Determines which layer types can be chosen.
  989. Valid values:
  990. - raster
  991. - raster3d
  992. - vector
  993. """
  994. return [_('raster'), _('3D raster'), _('vector')]
  995. def _selectAll(self):
  996. """!Check all layers by default"""
  997. return True
  998. def _createDialogBody(self):
  999. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  1000. # layer type
  1001. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  1002. flag = wx.ALIGN_CENTER_VERTICAL,
  1003. pos = (0,0))
  1004. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  1005. choices = self._layerTypes(), size = (100,-1))
  1006. self.layerType.SetSelection(0)
  1007. bodySizer.Add(item = self.layerType,
  1008. pos = (0,1))
  1009. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  1010. # select toggle
  1011. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1012. label = _("Select toggle"))
  1013. self.toggle.SetValue(self._selectAll())
  1014. bodySizer.Add(item = self.toggle,
  1015. flag = wx.ALIGN_CENTER_VERTICAL,
  1016. pos = (0,2))
  1017. # mapset filter
  1018. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  1019. flag = wx.ALIGN_CENTER_VERTICAL,
  1020. pos = (1,0))
  1021. self.mapset = MapsetSelect(parent = self, searchPath = True)
  1022. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  1023. bodySizer.Add(item = self.mapset,
  1024. pos = (1,1), span = (1, 2))
  1025. # map name filter
  1026. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  1027. flag = wx.ALIGN_CENTER_VERTICAL,
  1028. pos = (2,0))
  1029. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1030. value = "",
  1031. size = (250,-1))
  1032. bodySizer.Add(item = self.filter,
  1033. flag = wx.EXPAND,
  1034. pos = (2,1), span = (1, 2))
  1035. self.filter.SetFocus()
  1036. self.filter.SetToolTipString(_("Put here a regular expression."
  1037. " Characters '.*' stand for anything,"
  1038. " character '^' stands for the beginning"
  1039. " and '$' for the end."))
  1040. # layer list
  1041. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  1042. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  1043. pos = (3,0))
  1044. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1045. size = (250, 100),
  1046. choices = [])
  1047. bodySizer.Add(item = self.layers,
  1048. flag = wx.EXPAND,
  1049. pos = (3,1), span = (1, 2))
  1050. bodySizer.AddGrowableCol(1)
  1051. bodySizer.AddGrowableRow(3)
  1052. # bindings
  1053. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  1054. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  1055. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  1056. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  1057. return bodySizer
  1058. def LoadMapLayers(self, type, mapset):
  1059. """!Load list of map layers
  1060. @param type layer type ('raster' or 'vector')
  1061. @param mapset mapset name
  1062. """
  1063. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  1064. self.layers.Set(self.map_layers)
  1065. # check all items by default
  1066. for item in range(self.layers.GetCount()):
  1067. self.layers.Check(item, check = self._selectAll())
  1068. def OnChangeParams(self, event):
  1069. """!Filter parameters changed by user"""
  1070. # update list of layer to be loaded
  1071. self.LoadMapLayers(self.GetLayerType(cmd = True),
  1072. self.mapset.GetStringSelection())
  1073. event.Skip()
  1074. def OnMenu(self, event):
  1075. """!Table description area, context menu"""
  1076. if not hasattr(self, "popupID1"):
  1077. self.popupDataID1 = wx.NewId()
  1078. self.popupDataID2 = wx.NewId()
  1079. self.popupDataID3 = wx.NewId()
  1080. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1081. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  1082. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  1083. # generate popup-menu
  1084. menu = wx.Menu()
  1085. menu.Append(self.popupDataID1, _("Select all"))
  1086. menu.Append(self.popupDataID2, _("Invert selection"))
  1087. menu.Append(self.popupDataID3, _("Deselect all"))
  1088. self.PopupMenu(menu)
  1089. menu.Destroy()
  1090. def OnSelectAll(self, event):
  1091. """!Select all map layer from list"""
  1092. for item in range(self.layers.GetCount()):
  1093. self.layers.Check(item, True)
  1094. def OnSelectInvert(self, event):
  1095. """!Invert current selection"""
  1096. for item in range(self.layers.GetCount()):
  1097. if self.layers.IsChecked(item):
  1098. self.layers.Check(item, False)
  1099. else:
  1100. self.layers.Check(item, True)
  1101. def OnDeselectAll(self, event):
  1102. """!Select all map layer from list"""
  1103. for item in range(self.layers.GetCount()):
  1104. self.layers.Check(item, False)
  1105. def OnFilter(self, event):
  1106. """!Apply filter for map names"""
  1107. if len(event.GetString()) == 0:
  1108. self.layers.Set(self.map_layers)
  1109. return
  1110. list = []
  1111. for layer in self.map_layers:
  1112. try:
  1113. if re.compile(event.GetString()).search(layer):
  1114. list.append(layer)
  1115. except:
  1116. pass
  1117. self.layers.Set(list)
  1118. self.OnSelectAll(None)
  1119. event.Skip()
  1120. def OnToggle(self, event):
  1121. """!Select toggle (check or uncheck all layers)"""
  1122. check = event.Checked()
  1123. for item in range(self.layers.GetCount()):
  1124. self.layers.Check(item, check)
  1125. event.Skip()
  1126. def GetMapLayers(self):
  1127. """!Return list of checked map layers"""
  1128. layerNames = []
  1129. for indx in self.layers.GetSelections():
  1130. # layers.append(self.layers.GetStringSelec(indx))
  1131. pass
  1132. mapset = self.mapset.GetStringSelection()
  1133. for item in range(self.layers.GetCount()):
  1134. if not self.layers.IsChecked(item):
  1135. continue
  1136. if self._useFullyQualifiedNames():
  1137. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  1138. else:
  1139. layerNames.append(self.layers.GetString(item))
  1140. return layerNames
  1141. def GetLayerType(self, cmd = False):
  1142. """!Get selected layer type
  1143. @param cmd True for g.mlist
  1144. """
  1145. if not cmd:
  1146. return self.layerType.GetStringSelection()
  1147. sel = self.layerType.GetSelection()
  1148. if sel == 0:
  1149. ltype = 'rast'
  1150. elif sel == 1:
  1151. ltype = 'rast3d'
  1152. else:
  1153. ltype = 'vect'
  1154. return ltype
  1155. class MapLayersDialog(MapLayersDialogBase):
  1156. """!Subclass of MapLayersDialogBase used in Layer Manager.
  1157. Contains apply button, which sends wxApplyMapLayers event.
  1158. """
  1159. def __init__(self, parent, title, **kwargs):
  1160. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1161. def _addApplyButton(self):
  1162. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  1163. self.btnSizer.AddButton(btnApply)
  1164. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1165. def OnApply(self, event):
  1166. self.applyAddingMapLayers.emit(mapLayers = self.GetMapLayers(),
  1167. ltype = self.GetLayerType(cmd = True))
  1168. class MapLayersDialogForGroups(MapLayersDialogBase):
  1169. """!Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  1170. Shows only raster maps.
  1171. """
  1172. def __init__(self, parent, title, **kwargs):
  1173. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1174. def _layerTypes(self):
  1175. return [_('raster'),]
  1176. def _selectAll(self):
  1177. """!Could be overriden"""
  1178. return False
  1179. def _fullyQualifiedNames(self):
  1180. pass
  1181. def _useFullyQualifiedNames(self):
  1182. return True
  1183. class MapLayersDialogForModeler(MapLayersDialogBase):
  1184. """!Subclass of MapLayersDialogBase used in Modeler.
  1185. """
  1186. def __init__(self, parent, title, **kwargs):
  1187. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1188. def _modelerDSeries(self):
  1189. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1190. label = _("Dynamic series (%s)") % 'g.mlist')
  1191. self.dseries.SetValue(False)
  1192. self.mainSizer.Add(item = self.dseries, proportion = 0,
  1193. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1194. def GetDSeries(self):
  1195. """!Used by modeler only
  1196. @return g.mlist command
  1197. """
  1198. if not self.dseries or not self.dseries.IsChecked():
  1199. return ''
  1200. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  1201. patt = self.filter.GetValue()
  1202. if patt:
  1203. cond += 'pattern=%s ' % patt
  1204. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1205. return cond
  1206. class ImportDialog(wx.Dialog):
  1207. """!Dialog for bulk import of various data (base class)"""
  1208. def __init__(self, parent, itype,
  1209. id = wx.ID_ANY, title = _("Multiple import"),
  1210. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1211. self.parent = parent # GMFrame
  1212. self.importType = itype
  1213. self.options = dict() # list of options
  1214. self.commandId = -1 # id of running command
  1215. wx.Dialog.__init__(self, parent, id, title, style = style,
  1216. name = "MultiImportDialog")
  1217. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1218. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
  1219. if self.importType == 'gdal':
  1220. label = _("List of raster layers")
  1221. elif self.importType == 'ogr':
  1222. label = _("List of vector layers")
  1223. else:
  1224. label = _("List of %s layers") % self.importType.upper()
  1225. self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
  1226. # list of layers
  1227. columns = [_('Layer id'),
  1228. _('Layer name'),
  1229. _('Name for output GRASS map (editable)')]
  1230. if itype == 'ogr':
  1231. columns.insert(2, _('Feature type'))
  1232. columns.insert(3, _('Projection match'))
  1233. self.list = LayersList(parent = self.panel, columns = columns)
  1234. self.list.LoadData()
  1235. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1236. label = "%s" % _("Options"))
  1237. cmd = self._getCommand()
  1238. task = gtask.parse_interface(cmd)
  1239. for f in task.get_options()['flags']:
  1240. name = f.get('name', '')
  1241. desc = f.get('label', '')
  1242. if not desc:
  1243. desc = f.get('description', '')
  1244. if not name and not desc:
  1245. continue
  1246. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  1247. continue
  1248. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  1249. continue
  1250. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  1251. continue
  1252. elif cmd == 'v.external' and name not in ('b'):
  1253. continue
  1254. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  1255. continue
  1256. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1257. label = desc)
  1258. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1259. label = _("Allow output files to overwrite existing files"))
  1260. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1261. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  1262. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1263. label = _("Close dialog on finish"))
  1264. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1265. #
  1266. # buttons
  1267. #
  1268. # cancel
  1269. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1270. self.btn_close.SetToolTipString(_("Close dialog"))
  1271. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1272. # run
  1273. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1274. self.btn_run.SetToolTipString(_("Import selected layers"))
  1275. self.btn_run.SetDefault()
  1276. self.btn_run.Enable(False)
  1277. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1278. def doLayout(self):
  1279. """!Do layout"""
  1280. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1281. # dsn input
  1282. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1283. flag = wx.EXPAND)
  1284. #
  1285. # list of DXF layers
  1286. #
  1287. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1288. layerSizer.Add(item = self.list, proportion = 1,
  1289. flag = wx.ALL | wx.EXPAND, border = 5)
  1290. dialogSizer.Add(item = layerSizer, proportion = 1,
  1291. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1292. # options
  1293. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1294. for key in self.options.keys():
  1295. optionSizer.Add(item = self.options[key], proportion = 0)
  1296. dialogSizer.Add(item = optionSizer, proportion = 0,
  1297. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1298. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1299. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1300. dialogSizer.Add(item = self.add, proportion = 0,
  1301. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1302. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1303. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1304. #
  1305. # buttons
  1306. #
  1307. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1308. btnsizer.Add(item = self.btn_close, proportion = 0,
  1309. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1310. border = 10)
  1311. btnsizer.Add(item = self.btn_run, proportion = 0,
  1312. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1313. border = 10)
  1314. dialogSizer.Add(item = btnsizer, proportion = 0,
  1315. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1316. border = 10)
  1317. # dialogSizer.SetSizeHints(self.panel)
  1318. self.panel.SetAutoLayout(True)
  1319. self.panel.SetSizer(dialogSizer)
  1320. dialogSizer.Fit(self.panel)
  1321. # auto-layout seems not work here - FIXME
  1322. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1323. self.SetMinSize(size)
  1324. self.SetSize((size.width, size.height + 100))
  1325. # width = self.GetSize()[0]
  1326. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1327. self.Layout()
  1328. def _getCommand(self):
  1329. """!Get command"""
  1330. return ''
  1331. def OnClose(self, event = None):
  1332. """!Close dialog"""
  1333. self.Close()
  1334. def OnRun(self, event):
  1335. """!Import/Link data (each layes as separate vector map)"""
  1336. pass
  1337. def AddLayers(self, returncode, cmd = None):
  1338. """!Add imported/linked layers into layer tree"""
  1339. if not self.add.IsChecked() or returncode != 0:
  1340. return
  1341. self.commandId += 1
  1342. maptree = self.parent.GetLayerTree()
  1343. layer, output = self.list.GetLayers()[self.commandId]
  1344. if '@' not in output:
  1345. name = output + '@' + grass.gisenv()['MAPSET']
  1346. else:
  1347. name = output
  1348. # add imported layers into layer tree
  1349. if self.importType == 'gdal':
  1350. cmd = ['d.rast',
  1351. 'map=%s' % name]
  1352. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1353. cmd.append('-n')
  1354. item = maptree.AddLayer(ltype = 'raster',
  1355. lname = name, lchecked = False,
  1356. lcmd = cmd, multiple = False)
  1357. else:
  1358. item = maptree.AddLayer(ltype = 'vector',
  1359. lname = name, lchecked = False,
  1360. lcmd = ['d.vect',
  1361. 'map=%s' % name] + GetDisplayVectSettings(),
  1362. multiple = False)
  1363. maptree.mapdisplay.MapWindow.ZoomToMap()
  1364. def OnAbort(self, event):
  1365. """!Abort running import
  1366. @todo not yet implemented
  1367. """
  1368. pass
  1369. class GdalImportDialog(ImportDialog):
  1370. def __init__(self, parent, giface, ogr = False, link = False):
  1371. """!Dialog for bulk import of various raster/vector data
  1372. @todo Split into GdalImportDialog and OgrImportDialog
  1373. @param parent parent window
  1374. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1375. @param link True for linking data otherwise importing data
  1376. """
  1377. self._giface = giface
  1378. self.link = link
  1379. self.ogr = ogr
  1380. if ogr:
  1381. ImportDialog.__init__(self, parent, itype = 'ogr')
  1382. if link:
  1383. self.SetTitle(_("Link external vector data"))
  1384. else:
  1385. self.SetTitle(_("Import vector data"))
  1386. else:
  1387. ImportDialog.__init__(self, parent, itype = 'gdal')
  1388. if link:
  1389. self.SetTitle(_("Link external raster data"))
  1390. else:
  1391. self.SetTitle(_("Import raster data"))
  1392. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1393. ogr = ogr, link = link)
  1394. if link:
  1395. self.add.SetLabel(_("Add linked layers into layer tree"))
  1396. else:
  1397. self.add.SetLabel(_("Add imported layers into layer tree"))
  1398. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1399. if link:
  1400. self.btn_run.SetLabel(_("&Link"))
  1401. self.btn_run.SetToolTipString(_("Link selected layers"))
  1402. else:
  1403. self.btn_run.SetLabel(_("&Import"))
  1404. self.btn_run.SetToolTipString(_("Import selected layers"))
  1405. self.doLayout()
  1406. def OnRun(self, event):
  1407. """!Import/Link data (each layes as separate vector map)"""
  1408. self.commandId = -1
  1409. data = self.list.GetLayers()
  1410. if not data:
  1411. GMessage(_("No layers selected. Operation canceled."),
  1412. parent = self)
  1413. return
  1414. dsn = self.dsnInput.GetDsn()
  1415. ext = self.dsnInput.GetFormatExt()
  1416. # determine data driver for PostGIS links
  1417. popOGR = False
  1418. if self.importType == 'ogr' and \
  1419. self.dsnInput.GetType() == 'db' and \
  1420. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1421. 'GRASS_VECTOR_OGR' not in os.environ:
  1422. popOGR = True
  1423. os.environ['GRASS_VECTOR_OGR'] = '1'
  1424. for layer, output in data:
  1425. if self.importType == 'ogr':
  1426. if ext and layer.rfind(ext) > -1:
  1427. layer = layer.replace('.' + ext, '')
  1428. if self.link:
  1429. cmd = ['v.external',
  1430. 'dsn=%s' % dsn,
  1431. 'output=%s' % output,
  1432. 'layer=%s' % layer]
  1433. else:
  1434. cmd = ['v.in.ogr',
  1435. 'dsn=%s' % dsn,
  1436. 'layer=%s' % layer,
  1437. 'output=%s' % output]
  1438. else: # gdal
  1439. if self.dsnInput.GetType() == 'dir':
  1440. idsn = os.path.join(dsn, layer)
  1441. else:
  1442. idsn = dsn
  1443. if self.link:
  1444. cmd = ['r.external',
  1445. 'input=%s' % idsn,
  1446. 'output=%s' % output]
  1447. else:
  1448. cmd = ['r.in.gdal',
  1449. 'input=%s' % idsn,
  1450. 'output=%s' % output]
  1451. if self.overwrite.IsChecked():
  1452. cmd.append('--overwrite')
  1453. for key in self.options.keys():
  1454. if self.options[key].IsChecked():
  1455. cmd.append('-%s' % key)
  1456. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1457. '--overwrite' not in cmd:
  1458. cmd.append('--overwrite')
  1459. # run in Layer Manager
  1460. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1461. if popOGR:
  1462. os.environ.pop('GRASS_VECTOR_OGR')
  1463. if self.closeOnFinish.IsChecked():
  1464. self.Close()
  1465. def _getCommand(self):
  1466. """!Get command"""
  1467. if self.link:
  1468. if self.ogr:
  1469. return 'v.external'
  1470. else:
  1471. return 'r.external'
  1472. else:
  1473. if self.ogr:
  1474. return 'v.in.ogr'
  1475. else:
  1476. return 'r.in.gdal'
  1477. return ''
  1478. class GdalOutputDialog(wx.Dialog):
  1479. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1480. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1481. """!Dialog for setting output format for rasters/vectors
  1482. @todo Split into GdalOutputDialog and OgrOutputDialog
  1483. @param parent parent window
  1484. @param id window id
  1485. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1486. @param style window style
  1487. @param *kwargs other wx.Dialog's arguments
  1488. """
  1489. self.parent = parent # GMFrame
  1490. self.ogr = ogr
  1491. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1492. if self.ogr:
  1493. self.SetTitle(_("Define output format for vector data"))
  1494. else:
  1495. self.SetTitle(_("Define output format for raster data"))
  1496. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1497. # buttons
  1498. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1499. self.btnCancel.SetToolTipString(_("Close dialog"))
  1500. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1501. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1502. self.btnOk.SetDefault()
  1503. self.btnOk.Enable(False)
  1504. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1505. ogr = ogr,
  1506. exclude = ['file', 'protocol'], dest = True)
  1507. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1508. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1509. self._layout()
  1510. def _layout(self):
  1511. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1512. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1513. flag = wx.EXPAND)
  1514. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1515. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1516. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1517. border = 10)
  1518. btnSizer.Add(item = self.btnOk, proportion = 0,
  1519. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1520. border = 10)
  1521. dialogSizer.Add(item = btnSizer, proportion = 0,
  1522. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1523. border = 10)
  1524. self.panel.SetAutoLayout(True)
  1525. self.panel.SetSizer(dialogSizer)
  1526. dialogSizer.Fit(self.panel)
  1527. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1528. self.SetMinSize(size)
  1529. self.SetSize((size.width, size.height))
  1530. self.Layout()
  1531. def OnCancel(self, event):
  1532. self.Destroy()
  1533. def OnOK(self, event):
  1534. if self.dsnInput.GetType() == 'native':
  1535. RunCommand('v.external.out',
  1536. parent = self,
  1537. flags = 'r')
  1538. else:
  1539. dsn = self.dsnInput.GetDsn()
  1540. frmt = self.dsnInput.GetFormat()
  1541. options = self.dsnInput.GetOptions()
  1542. RunCommand('v.external.out',
  1543. parent = self,
  1544. dsn = dsn, format = frmt,
  1545. options = options)
  1546. self.Close()
  1547. class DxfImportDialog(ImportDialog):
  1548. """!Dialog for bulk import of DXF layers"""
  1549. def __init__(self, parent, giface):
  1550. ImportDialog.__init__(self, parent, itype = 'dxf',
  1551. title = _("Import DXF layers"))
  1552. self._giface = giface
  1553. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1554. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1555. dialogTitle = _('Choose DXF file to import'),
  1556. buttonText = _('Browse'),
  1557. startDirectory = os.getcwd(), fileMode = 0,
  1558. changeCallback = self.OnSetDsn,
  1559. fileMask = "DXF File (*.dxf)|*.dxf")
  1560. self.add.SetLabel(_("Add imported layers into layer tree"))
  1561. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1562. self.doLayout()
  1563. def _getCommand(self):
  1564. """!Get command"""
  1565. return 'v.in.dxf'
  1566. def OnRun(self, event):
  1567. """!Import/Link data (each layes as separate vector map)"""
  1568. data = self.list.GetLayers()
  1569. # hide dialog
  1570. self.Hide()
  1571. inputDxf = self.dsnInput.GetValue()
  1572. for layer, output in data:
  1573. cmd = ['v.in.dxf',
  1574. 'input=%s' % inputDxf,
  1575. 'layers=%s' % layer,
  1576. 'output=%s' % output]
  1577. for key in self.options.keys():
  1578. if self.options[key].IsChecked():
  1579. cmd.append('-%s' % key)
  1580. if self.overwrite.IsChecked() or \
  1581. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1582. cmd.append('--overwrite')
  1583. # run in Layer Manager
  1584. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1585. self.OnCancel()
  1586. def OnSetDsn(self, event):
  1587. """!Input DXF file defined, update list of layer widget"""
  1588. path = event.GetString()
  1589. if not path:
  1590. return
  1591. data = list()
  1592. ret = RunCommand('v.in.dxf',
  1593. quiet = True,
  1594. parent = self,
  1595. read = True,
  1596. flags = 'l',
  1597. input = path)
  1598. if not ret:
  1599. self.list.LoadData()
  1600. self.btn_run.Enable(False)
  1601. return
  1602. for line in ret.splitlines():
  1603. layerId = line.split(':')[0].split(' ')[1]
  1604. layerName = line.split(':')[1].strip()
  1605. grassName = GetValidLayerName(layerName)
  1606. data.append((layerId, layerName.strip(), grassName.strip()))
  1607. self.list.LoadData(data)
  1608. if len(data) > 0:
  1609. self.btn_run.Enable(True)
  1610. else:
  1611. self.btn_run.Enable(False)
  1612. class LayersList(GListCtrl, listmix.TextEditMixin):
  1613. """!List of layers to be imported (dxf, shp...)"""
  1614. def __init__(self, parent, columns, log = None):
  1615. GListCtrl.__init__(self, parent)
  1616. self.log = log
  1617. # setup mixins
  1618. listmix.TextEditMixin.__init__(self)
  1619. for i in range(len(columns)):
  1620. self.InsertColumn(i, columns[i])
  1621. if len(columns) == 3:
  1622. width = (65, 200)
  1623. else:
  1624. width = (65, 180, 90, 70)
  1625. for i in range(len(width)):
  1626. self.SetColumnWidth(col = i, width = width[i])
  1627. def LoadData(self, data = None):
  1628. """!Load data into list"""
  1629. self.DeleteAllItems()
  1630. if data is None:
  1631. return
  1632. for item in data:
  1633. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1634. for i in range(1, len(item)):
  1635. self.SetStringItem(index, i, "%s" % str(item[i]))
  1636. # check by default only on one item
  1637. if len(data) == 1:
  1638. self.CheckItem(index, True)
  1639. def OnLeftDown(self, event):
  1640. """!Allow editing only output name
  1641. Code taken from TextEditMixin class.
  1642. """
  1643. x, y = event.GetPosition()
  1644. colLocs = [0]
  1645. loc = 0
  1646. for n in range(self.GetColumnCount()):
  1647. loc = loc + self.GetColumnWidth(n)
  1648. colLocs.append(loc)
  1649. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1650. if col == self.GetColumnCount() - 1:
  1651. listmix.TextEditMixin.OnLeftDown(self, event)
  1652. else:
  1653. event.Skip()
  1654. def GetLayers(self):
  1655. """!Get list of layers (layer name, output name)"""
  1656. data = []
  1657. item = -1
  1658. while True:
  1659. item = self.GetNextItem(item)
  1660. if item == -1:
  1661. break
  1662. if not self.IsChecked(item):
  1663. continue
  1664. # layer / output name
  1665. data.append((self.GetItem(item, 1).GetText(),
  1666. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1667. return data
  1668. class SetOpacityDialog(wx.Dialog):
  1669. """!Set opacity of map layers"""
  1670. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1671. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1672. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1673. self.parent = parent # GMFrame
  1674. self.opacity = opacity # current opacity
  1675. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1676. size = size, style = style, title = title)
  1677. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1678. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1679. sizer = wx.BoxSizer(wx.VERTICAL)
  1680. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1681. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1682. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1683. wx.SL_TOP | wx.SL_LABELS,
  1684. minValue = 0, maxValue = 100,
  1685. size = (350, -1))
  1686. box.Add(item = self.value,
  1687. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1688. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1689. label = _("transparent")),
  1690. pos = (1, 0))
  1691. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1692. label = _("opaque")),
  1693. flag = wx.ALIGN_RIGHT,
  1694. pos = (1, 1))
  1695. sizer.Add(item = box, proportion = 0,
  1696. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1697. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1698. style = wx.LI_HORIZONTAL)
  1699. sizer.Add(item = line, proportion = 0,
  1700. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1701. # buttons
  1702. btnsizer = wx.StdDialogButtonSizer()
  1703. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1704. btnOK.SetDefault()
  1705. btnsizer.AddButton(btnOK)
  1706. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1707. btnsizer.AddButton(btnCancel)
  1708. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1709. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1710. btnsizer.AddButton(btnApply)
  1711. btnsizer.Realize()
  1712. sizer.Add(item = btnsizer, proportion = 0,
  1713. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1714. panel.SetSizer(sizer)
  1715. sizer.Fit(panel)
  1716. self.SetSize(self.GetBestSize())
  1717. self.Layout()
  1718. def GetOpacity(self):
  1719. """!Button 'OK' pressed"""
  1720. # return opacity value
  1721. opacity = float(self.value.GetValue()) / 100
  1722. return opacity
  1723. def OnApply(self, event):
  1724. self.applyOpacity.emit(value = self.GetOpacity())
  1725. def GetImageHandlers(image):
  1726. """!Get list of supported image handlers"""
  1727. lext = list()
  1728. ltype = list()
  1729. for h in image.GetHandlers():
  1730. lext.append(h.GetExtension())
  1731. filetype = ''
  1732. if 'png' in lext:
  1733. filetype += "PNG file (*.png)|*.png|"
  1734. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1735. 'ext' : 'png' })
  1736. filetype += "BMP file (*.bmp)|*.bmp|"
  1737. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1738. 'ext' : 'bmp' })
  1739. if 'gif' in lext:
  1740. filetype += "GIF file (*.gif)|*.gif|"
  1741. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1742. 'ext' : 'gif' })
  1743. if 'jpg' in lext:
  1744. filetype += "JPG file (*.jpg)|*.jpg|"
  1745. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1746. 'ext' : 'jpg' })
  1747. if 'pcx' in lext:
  1748. filetype += "PCX file (*.pcx)|*.pcx|"
  1749. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1750. 'ext' : 'pcx' })
  1751. if 'pnm' in lext:
  1752. filetype += "PNM file (*.pnm)|*.pnm|"
  1753. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1754. 'ext' : 'pnm' })
  1755. if 'tif' in lext:
  1756. filetype += "TIF file (*.tif)|*.tif|"
  1757. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1758. 'ext' : 'tif' })
  1759. if 'xpm' in lext:
  1760. filetype += "XPM file (*.xpm)|*.xpm"
  1761. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1762. 'ext' : 'xpm' })
  1763. return filetype, ltype
  1764. class ImageSizeDialog(wx.Dialog):
  1765. """!Set size for saved graphic file"""
  1766. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1767. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1768. self.parent = parent
  1769. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1770. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1771. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1772. label = ' % s' % _("Image size"))
  1773. size = self.parent.GetWindow().GetClientSize()
  1774. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1775. style = wx.SP_ARROW_KEYS)
  1776. self.width.SetRange(20, 1e6)
  1777. self.width.SetValue(size.width)
  1778. wx.CallAfter(self.width.SetFocus)
  1779. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1780. style = wx.SP_ARROW_KEYS)
  1781. self.height.SetRange(20, 1e6)
  1782. self.height.SetValue(size.height)
  1783. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1784. size = (125, -1),
  1785. choices = [ "",
  1786. "640x480",
  1787. "800x600",
  1788. "1024x768",
  1789. "1280x960",
  1790. "1600x1200",
  1791. "1920x1440" ])
  1792. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1793. self.btnOK.SetDefault()
  1794. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1795. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1796. self._layout()
  1797. self.SetSize(self.GetBestSize())
  1798. def _layout(self):
  1799. """!Do layout"""
  1800. sizer = wx.BoxSizer(wx.VERTICAL)
  1801. # body
  1802. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1803. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1804. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1805. label = _("Width:")),
  1806. flag = wx.ALIGN_CENTER_VERTICAL)
  1807. fbox.Add(item = self.width)
  1808. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1809. label = _("Height:")),
  1810. flag = wx.ALIGN_CENTER_VERTICAL)
  1811. fbox.Add(item = self.height)
  1812. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1813. label = _("Template:")),
  1814. flag = wx.ALIGN_CENTER_VERTICAL)
  1815. fbox.Add(item = self.template)
  1816. box.Add(item = fbox, proportion = 1,
  1817. flag = wx.EXPAND | wx.ALL, border = 5)
  1818. sizer.Add(item = box, proportion = 1,
  1819. flag=wx.EXPAND | wx.ALL, border = 3)
  1820. # buttons
  1821. btnsizer = wx.StdDialogButtonSizer()
  1822. btnsizer.AddButton(self.btnOK)
  1823. btnsizer.AddButton(self.btnCancel)
  1824. btnsizer.Realize()
  1825. sizer.Add(item = btnsizer, proportion = 0,
  1826. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1827. self.panel.SetSizer(sizer)
  1828. sizer.Fit(self.panel)
  1829. self.Layout()
  1830. def GetValues(self):
  1831. """!Get width/height values"""
  1832. return self.width.GetValue(), self.height.GetValue()
  1833. def OnTemplate(self, event):
  1834. """!Template selected"""
  1835. sel = event.GetString()
  1836. if not sel:
  1837. width, height = self.parent.GetWindow().GetClientSize()
  1838. else:
  1839. width, height = map(int, sel.split('x'))
  1840. self.width.SetValue(width)
  1841. self.height.SetValue(height)
  1842. class SqlQueryFrame(wx.Frame):
  1843. def __init__(self, parent, id = wx.ID_ANY,
  1844. title = _("GRASS GIS SQL Query Utility"),
  1845. *kwargs):
  1846. """!SQL Query Utility window
  1847. """
  1848. self.parent = parent
  1849. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1850. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1851. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1852. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1853. label = _(" SQL statement "))
  1854. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1855. style = wx.TE_MULTILINE)
  1856. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1857. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1858. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1859. self._layout()
  1860. self.SetMinSize(wx.Size(300, 150))
  1861. self.SetSize(wx.Size(500, 200))
  1862. def _layout(self):
  1863. """!Do layout"""
  1864. sizer = wx.BoxSizer(wx.VERTICAL)
  1865. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1866. sqlSizer.Add(item = self.sql, proportion = 1,
  1867. flag = wx.EXPAND)
  1868. btnSizer = wx.StdDialogButtonSizer()
  1869. btnSizer.AddButton(self.btnApply)
  1870. btnSizer.AddButton(self.btnCancel)
  1871. btnSizer.Realize()
  1872. sizer.Add(item = sqlSizer, proportion = 1,
  1873. flag = wx.EXPAND | wx.ALL, border = 5)
  1874. sizer.Add(item = btnSizer, proportion = 0,
  1875. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1876. self.panel.SetSizer(sizer)
  1877. self.Layout()
  1878. def OnCloseWindow(self, event):
  1879. """!Close window
  1880. """
  1881. self.Close()
  1882. class SymbolDialog(wx.Dialog):
  1883. """!Dialog for GRASS symbols selection.
  1884. Dialog is called in gui_core::forms module.
  1885. """
  1886. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  1887. """!Dialog constructor.
  1888. It is assumed that symbolPath contains folders with symbols.
  1889. @param parent dialog parent
  1890. @param symbolPath absolute path to symbols
  1891. @param currentSymbol currently selected symbol (e.g. 'basic/x')
  1892. @param title dialog title
  1893. """
  1894. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  1895. self.symbolPath = symbolPath
  1896. self.currentSymbol = currentSymbol # default basic/x
  1897. self.selected = None
  1898. self.selectedDir = None
  1899. self._layout()
  1900. def _layout(self):
  1901. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  1902. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1903. vSizer = wx.BoxSizer( wx.VERTICAL)
  1904. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  1905. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  1906. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  1907. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  1908. proportion = 0,
  1909. flag = wx.ALIGN_CENTER_VERTICAL)
  1910. fgSizer.Add(item = self.folderChoice, proportion = 0,
  1911. flag = wx.ALIGN_CENTER, border = 0)
  1912. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  1913. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  1914. flag = wx.ALIGN_CENTRE_VERTICAL)
  1915. fgSizer.Add(self.infoLabel, proportion = 0,
  1916. flag = wx.ALIGN_CENTRE_VERTICAL)
  1917. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  1918. self.panels = self._createSymbolPanels(mainPanel)
  1919. for panel in self.panels:
  1920. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  1921. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  1922. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  1923. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  1924. self.btnOK.SetDefault()
  1925. self.btnOK.Enable(False)
  1926. # buttons
  1927. btnSizer = wx.StdDialogButtonSizer()
  1928. btnSizer.AddButton(self.btnCancel)
  1929. btnSizer.AddButton(self.btnOK)
  1930. btnSizer.Realize()
  1931. mainSizer.Add(item = btnSizer, proportion = 0,
  1932. flag = wx.EXPAND | wx.ALL, border = 5)
  1933. # show panel with the largest number of images and fit size
  1934. count = []
  1935. for folder in os.listdir(self.symbolPath):
  1936. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  1937. index = count.index(max(count))
  1938. self.folderChoice.SetSelection(index)
  1939. self.OnFolderSelect(None)
  1940. self.infoLabel.Show()
  1941. mainPanel.SetSizerAndFit(mainSizer)
  1942. self.SetSize(self.GetBestSize())
  1943. # show currently selected symbol
  1944. if self.currentSymbol:
  1945. # set directory
  1946. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  1947. self.folderChoice.SetStringSelection(self.selectedDir)
  1948. # select symbol
  1949. panelIdx = self.folderChoice.GetSelection()
  1950. for panel in self.symbolPanels[panelIdx]:
  1951. if panel.GetName() == self.selected:
  1952. panel.Select()
  1953. else:
  1954. self.folderChoice.SetSelection(0)
  1955. self.OnFolderSelect(None)
  1956. def _createSymbolPanels(self, parent):
  1957. """!Creates multiple panels with symbols.
  1958. Panels are shown/hidden according to selected folder."""
  1959. folders = os.listdir(self.symbolPath)
  1960. panels = []
  1961. self.symbolPanels = []
  1962. for folder in folders:
  1963. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  1964. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  1965. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  1966. symbolPanels = []
  1967. for img in images:
  1968. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  1969. iP.symbolSelectionChanged.connect(self.SelectionChanged)
  1970. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  1971. symbolPanels.append(iP)
  1972. panel.SetSizerAndFit(sizer)
  1973. panel.Hide()
  1974. panels.append(panel)
  1975. self.symbolPanels.append(symbolPanels)
  1976. return panels
  1977. def _getSymbols(self, path):
  1978. # we assume that images are in subfolders (1 level only)
  1979. imageList = []
  1980. for image in os.listdir(path):
  1981. imageList.append(os.path.join(path, image))
  1982. return sorted(imageList)
  1983. def OnFolderSelect(self, event):
  1984. """!Selected folder with symbols changed."""
  1985. idx = self.folderChoice.GetSelection()
  1986. for i in range(len(self.panels)):
  1987. sizer = self.panels[i].GetContainingSizer()
  1988. sizer.Show(self.panels[i], i == idx, recursive = True)
  1989. sizer.Layout()
  1990. if self.selectedDir == self.folderChoice.GetStringSelection():
  1991. self.btnOK.Enable()
  1992. self.infoLabel.SetLabel(self.selected)
  1993. else:
  1994. self.btnOK.Disable()
  1995. self.infoLabel.SetLabel('')
  1996. def SelectionChanged(self, name, doubleClick):
  1997. """!Selected symbol changed."""
  1998. if doubleClick:
  1999. self.EndModal(wx.ID_OK)
  2000. # deselect all
  2001. for i in range(len(self.panels)):
  2002. for panel in self.symbolPanels[i]:
  2003. if panel.GetName() != name:
  2004. panel.Deselect()
  2005. self.btnOK.Enable()
  2006. self.selected = name
  2007. self.selectedDir = self.folderChoice.GetStringSelection()
  2008. self.infoLabel.SetLabel(name)
  2009. def GetSelectedSymbolName(self):
  2010. """!Returns currently selected symbol name (e.g. 'basic/x').
  2011. """
  2012. # separator must be '/' and not dependent on OS
  2013. return self.selectedDir + '/' + self.selected
  2014. def GetSelectedSymbolPath(self):
  2015. """!Returns currently selected symbol full path.
  2016. """
  2017. return os.path.join(self.symbolPath, self.selectedDir, self.selected)
  2018. class TextEntryDialog(wx.Dialog):
  2019. """!Simple dialog with text field.
  2020. It differs from wx.TextEntryDialog because it allows adding validator.
  2021. """
  2022. def __init__(self, parent, message, caption='',
  2023. defaultValue='', pos=wx.DefaultPosition, validator=wx.DefaultValidator,
  2024. style=wx.OK | wx.CANCEL):
  2025. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=caption, pos=pos)
  2026. vbox = wx.BoxSizer(wx.VERTICAL)
  2027. stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
  2028. vbox.Add(item=stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  2029. self._textCtrl = wx.TextCtrl(self, id=wx.ID_ANY, size = (300, -1),
  2030. value=defaultValue, validator=validator)
  2031. vbox.Add(item=self._textCtrl, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  2032. self._textCtrl.SetFocus()
  2033. sizer = self.CreateSeparatedButtonSizer(style)
  2034. vbox.Add(item=sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2035. self.SetSizerAndFit(vbox)
  2036. def GetValue(self):
  2037. return self._textCtrl.GetValue()
  2038. def SetValue(self, value):
  2039. self._textCtrl.SetValue(value)
  2040. class HyperlinkDialog(wx.Dialog):
  2041. """!Dialog for displaying message with hyperlink."""
  2042. def __init__(self, parent, title, message, hyperlink,
  2043. hyperlinkLabel=None, style=wx.OK):
  2044. """!Constructor
  2045. @param parent gui parent
  2046. @param title dialog title
  2047. @param message message
  2048. @param hyperlink url
  2049. @param hyperlinkLabel label shown instead of url
  2050. @param style button style
  2051. """
  2052. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  2053. style=wx.DEFAULT_DIALOG_STYLE)
  2054. sizer = wx.BoxSizer(wx.VERTICAL)
  2055. label = wx.StaticText(self, label=message)
  2056. sizer.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=10)
  2057. hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
  2058. hyperlinkCtrl = wx.HyperlinkCtrl(self, id=wx.ID_ANY,
  2059. label=hyperlinkLabel, url=hyperlink,
  2060. style=wx.HL_ALIGN_LEFT|wx.HL_CONTEXTMENU)
  2061. sizer.Add(item=hyperlinkCtrl, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)
  2062. btnsizer = self.CreateSeparatedButtonSizer(style)
  2063. sizer.Add(item=btnsizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2064. self.SetSizer(sizer)
  2065. sizer.Fit(self)