dialogs.py 97 KB

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