dialogs.py 98 KB

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