dialogs.py 98 KB

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