dialogs.py 98 KB

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