dialogs.py 98 KB

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