dialogs.py 97 KB

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