gdialogs.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. """!
  2. @package gdialogs.py
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - ElementDialog
  6. - LocationDialog
  7. - MapsetDialog
  8. - NewVectorDialog
  9. - SavedRegion
  10. - DecorationDialog
  11. - TextLayerDialog
  12. - MapLayersDialog
  13. - ImportDialog
  14. - GdalImportDialog
  15. - GdalOutputDialog
  16. - DxfImportDialog
  17. - LayersList (used by MultiImport)
  18. - SetOpacityDialog
  19. - StaticWrapText
  20. - ImageSizeDialog
  21. - SqlQueryFrame
  22. (C) 2008-2011 by the GRASS Development Team
  23. This program is free software under the GNU General Public
  24. License (>=v2). Read the file COPYING that comes with GRASS
  25. for details.
  26. @author Martin Landa <landa.martin gmail.com>
  27. """
  28. import os
  29. import sys
  30. import re
  31. from bisect import bisect
  32. import wx
  33. import wx.lib.filebrowsebutton as filebrowse
  34. import wx.lib.mixins.listctrl as listmix
  35. from grass.script import core as grass
  36. from grass.script import task as gtask
  37. import gcmd
  38. import globalvar
  39. import gselect
  40. import menuform
  41. import utils
  42. from preferences import globalSettings as UserSettings
  43. from debug import Debug
  44. class ElementDialog(wx.Dialog):
  45. def __init__(self, parent, title, label, id = wx.ID_ANY,
  46. etype = False, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  47. **kwargs):
  48. """!General dialog to choose given element (location, mapset, vector map, etc.)
  49. @param parent window
  50. @param title window title
  51. @param label element label
  52. @param etype show also ElementSelect
  53. """
  54. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  55. self.etype = etype
  56. self.label = label
  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.btnOK.Enable(False)
  62. if self.etype:
  63. self.typeSelect = gselect.ElementSelect(parent = self.panel,
  64. size = globalvar.DIALOG_GSELECT_SIZE)
  65. self.typeSelect.Bind(wx.EVT_CHOICE, self.OnType)
  66. self.element = None # must be defined
  67. self.__layout()
  68. def PostInit(self):
  69. self.element.SetFocus()
  70. self.element.Bind(wx.EVT_TEXT, self.OnElement)
  71. def OnType(self, event):
  72. """!Select element type"""
  73. if not self.etype:
  74. return
  75. evalue = self.typeSelect.GetValue(event.GetString())
  76. self.element.SetType(evalue)
  77. def OnElement(self, event):
  78. """!Name for vector map layer given"""
  79. if len(event.GetString()) > 0:
  80. self.btnOK.Enable(True)
  81. else:
  82. self.btnOK.Enable(False)
  83. def __layout(self):
  84. """!Do layout"""
  85. self.sizer = wx.BoxSizer(wx.VERTICAL)
  86. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  87. if self.etype:
  88. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  89. label = _("Type of element:")),
  90. proportion = 0, flag = wx.ALL, border = 1)
  91. self.dataSizer.Add(item = self.typeSelect,
  92. proportion = 0, flag = wx.ALL, border = 1)
  93. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  94. label = self.label),
  95. proportion = 0, flag = wx.ALL, border = 1)
  96. # buttons
  97. btnSizer = wx.StdDialogButtonSizer()
  98. btnSizer.AddButton(self.btnCancel)
  99. btnSizer.AddButton(self.btnOK)
  100. btnSizer.Realize()
  101. self.sizer.Add(item = self.dataSizer, proportion = 1,
  102. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  103. self.sizer.Add(item = btnSizer, proportion = 0,
  104. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  105. def GetElement(self):
  106. """!Return (mapName, overwrite)"""
  107. return self.element.GetValue()
  108. def GetType(self):
  109. """!Get element type"""
  110. return self.element.tcp.GetType()
  111. class LocationDialog(ElementDialog):
  112. """!Dialog used to select location"""
  113. def __init__(self, parent, title = _("Select GRASS location and mapset"), id = wx.ID_ANY):
  114. ElementDialog.__init__(self, parent, title, label = _("Name of GRASS location:"))
  115. self.element = gselect.LocationSelect(parent = self.panel, id = wx.ID_ANY,
  116. size = globalvar.DIALOG_GSELECT_SIZE)
  117. self.element1 = gselect.MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  118. size = globalvar.DIALOG_GSELECT_SIZE,
  119. setItems = False)
  120. self.PostInit()
  121. self.__Layout()
  122. self.SetMinSize(self.GetSize())
  123. def __Layout(self):
  124. """!Do layout"""
  125. self.dataSizer.Add(self.element, proportion = 0,
  126. flag = wx.EXPAND | wx.ALL, border = 1)
  127. self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  128. label = _("Name of mapset:")), proportion = 0,
  129. flag = wx.EXPAND | wx.ALL, border = 1)
  130. self.dataSizer.Add(self.element1, proportion = 0,
  131. flag = wx.EXPAND | wx.ALL, border = 1)
  132. self.panel.SetSizer(self.sizer)
  133. self.sizer.Fit(self)
  134. def OnElement(self, event):
  135. """!Select mapset given location name"""
  136. location = event.GetString()
  137. if location:
  138. dbase = grass.gisenv()['GISDBASE']
  139. self.element1.SetItems(utils.GetListOfMapsets(dbase, location, selectable = True))
  140. self.element1.SetSelection(0)
  141. mapset = self.element1.GetStringSelection()
  142. if location and mapset:
  143. self.btnOK.Enable(True)
  144. else:
  145. self.btnOK.Enable(False)
  146. def GetValues(self):
  147. """!Get location, mapset"""
  148. return (self.GetElement(), self.element1.GetStringSelection())
  149. class MapsetDialog(ElementDialog):
  150. """!Dialog used to select mapset"""
  151. def __init__(self, parent, title = _("Select mapset in GRASS location"),
  152. location = None, id = wx.ID_ANY):
  153. ElementDialog.__init__(self, parent, title, label = _("Name of mapset:"))
  154. if location:
  155. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  156. else:
  157. self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
  158. self.element = gselect.MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  159. size = globalvar.DIALOG_GSELECT_SIZE)
  160. self.PostInit()
  161. self.__Layout()
  162. self.SetMinSize(self.GetSize())
  163. def __Layout(self):
  164. """!Do layout"""
  165. self.dataSizer.Add(self.element, proportion = 0,
  166. flag = wx.EXPAND | wx.ALL, border = 1)
  167. self.panel.SetSizer(self.sizer)
  168. self.sizer.Fit(self)
  169. def GetMapset(self):
  170. return self.GetElement()
  171. class NewVectorDialog(ElementDialog):
  172. def __init__(self, parent, id = wx.ID_ANY, title = _('Create new vector map'),
  173. disableAdd = False, disableTable = False, showType = False,
  174. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  175. """!Dialog for creating new vector map
  176. @param parent parent window
  177. @param id window id
  178. @param title window title
  179. @param disableAdd disable 'add layer' checkbox
  180. @param disableTable disable 'create table' checkbox
  181. @param showType True to show feature type selector (used for creating new empty OGR layers)
  182. @param style window style
  183. @param kwargs other argumentes for ElementDialog
  184. @return dialog instance
  185. """
  186. ElementDialog.__init__(self, parent, title, label = _("Name for new vector map:"))
  187. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  188. type = 'vector', mapsets = [grass.gisenv()['MAPSET'],])
  189. # determine output format
  190. if showType:
  191. self.ftype = gselect.OgrTypeSelect(parent = self, panel = self.panel)
  192. else:
  193. self.ftype = None
  194. self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  195. label = _("Create attribute table"))
  196. self.table.SetValue(True)
  197. if disableTable:
  198. self.table.Enable(False)
  199. self.keycol = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  200. size = globalvar.DIALOG_SPIN_SIZE)
  201. self.keycol.SetValue(UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
  202. if disableTable:
  203. self.keycol.Enable(False)
  204. self.addbox = wx.CheckBox(parent = self.panel,
  205. label = _('Add created map into layer tree'), style = wx.NO_BORDER)
  206. if disableAdd:
  207. self.addbox.SetValue(True)
  208. self.addbox.Enable(False)
  209. else:
  210. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  211. self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
  212. self.PostInit()
  213. self._layout()
  214. self.SetMinSize(self.GetSize())
  215. def OnMapName(self, event):
  216. """!Name for vector map layer given"""
  217. self.OnElement(event)
  218. def OnTable(self, event):
  219. self.keycol.Enable(event.IsChecked())
  220. def _layout(self):
  221. """!Do layout"""
  222. self.dataSizer.Add(item = self.element, proportion = 0,
  223. flag = wx.EXPAND | wx.ALL, border = 1)
  224. if self.ftype:
  225. self.dataSizer.AddSpacer(1)
  226. self.dataSizer.Add(item = self.ftype, proportion = 0,
  227. flag = wx.EXPAND | wx.ALL, border = 1)
  228. self.dataSizer.Add(item = self.table, proportion = 0,
  229. flag = wx.EXPAND | wx.ALL, border = 1)
  230. keySizer = wx.BoxSizer(wx.HORIZONTAL)
  231. keySizer.Add(item = wx.StaticText(parent = self.panel, label = _("Key column:")),
  232. proportion = 0,
  233. flag = wx.ALIGN_CENTER_VERTICAL)
  234. keySizer.AddSpacer(10)
  235. keySizer.Add(item = self.keycol, proportion = 0,
  236. flag = wx.ALIGN_RIGHT)
  237. self.dataSizer.Add(item = keySizer, proportion = 1,
  238. flag = wx.EXPAND | wx.ALL, border = 1)
  239. self.dataSizer.AddSpacer(5)
  240. self.dataSizer.Add(item = self.addbox, proportion = 0,
  241. flag = wx.EXPAND | wx.ALL, border = 1)
  242. self.panel.SetSizer(self.sizer)
  243. self.sizer.Fit(self)
  244. def GetName(self, full = False):
  245. """!Get name of vector map to be created
  246. @param full True to get fully qualified name
  247. """
  248. name = self.GetElement()
  249. if full:
  250. if '@' in name:
  251. return name
  252. else:
  253. return name + '@' + grass.gisenv()['MAPSET']
  254. return name.split('@', 1)[0]
  255. def GetKey(self):
  256. """!Get key column name"""
  257. return self.keycol.GetValue()
  258. def IsChecked(self, key):
  259. """!Get dialog properties
  260. @param key window key ('add', 'table')
  261. @return True/False
  262. @return None on error
  263. """
  264. if key == 'add':
  265. return self.addbox.IsChecked()
  266. elif key == 'table':
  267. return self.table.IsChecked()
  268. return None
  269. def GetFeatureType(self):
  270. """!Get feature type for OGR
  271. @return feature type as string
  272. @return None for native format
  273. """
  274. if self.ftype:
  275. return self.ftype.GetType()
  276. return None
  277. def CreateNewVector(parent, cmd, title = _('Create new vector map'),
  278. exceptMap = None, log = None,
  279. disableAdd = False, disableTable = False):
  280. """!Create new vector map layer
  281. @param cmd (prog, **kwargs)
  282. @param title window title
  283. @param exceptMap list of maps to be excepted
  284. @param log
  285. @param disableAdd disable 'add layer' checkbox
  286. @param disableTable disable 'create table' checkbox
  287. @return dialog instance
  288. @return None on error
  289. """
  290. vExternalOut = grass.parse_command('v.external.out', flags = 'g')
  291. isNative = vExternalOut['format'] == 'native'
  292. if cmd[0] == 'v.edit' and not isNative:
  293. showType = True
  294. else:
  295. showType = False
  296. dlg = NewVectorDialog(parent, title = title,
  297. disableAdd = disableAdd, disableTable = disableTable,
  298. showType = showType)
  299. if dlg.ShowModal() != wx.ID_OK:
  300. dlg.Destroy()
  301. return None
  302. outmap = dlg.GetName()
  303. key = dlg.GetKey()
  304. if outmap == exceptMap:
  305. gcmd.GError(parent = parent,
  306. message = _("Unable to create vector map <%s>.") % outmap)
  307. dlg.Destroy()
  308. return None
  309. if dlg.table.IsEnabled() and not key:
  310. gcmd.GError(parent = parent,
  311. message = _("Invalid or empty key column.\n"
  312. "Unable to create vector map <%s>.") % outmap)
  313. dlg.Destroy()
  314. return
  315. if outmap == '': # should not happen
  316. dlg.Destroy()
  317. return None
  318. # update cmd -> output name defined
  319. cmd[1][cmd[2]] = outmap
  320. if showType:
  321. cmd[1]['type'] = dlg.GetFeatureType()
  322. if isNative:
  323. listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
  324. else:
  325. listOfVectors = gcmd.RunCommand('v.external',
  326. quiet = True,
  327. parent = parent,
  328. read = True,
  329. flags = 'l',
  330. dsn = vExternalOut['dsn'])
  331. overwrite = False
  332. if not UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  333. outmap in listOfVectors:
  334. dlgOw = wx.MessageDialog(parent, message = _("Vector map <%s> already exists "
  335. "in the current mapset. "
  336. "Do you want to overwrite it?") % outmap,
  337. caption = _("Overwrite?"),
  338. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  339. if dlgOw.ShowModal() == wx.ID_YES:
  340. overwrite = True
  341. else:
  342. dlgOw.Destroy()
  343. dlg.Destroy()
  344. return None
  345. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  346. overwrite = True
  347. ret = gcmd.RunCommand(prog = cmd[0],
  348. parent = parent,
  349. overwrite = overwrite,
  350. **cmd[1])
  351. if ret != 0:
  352. dlg.Destroy()
  353. return None
  354. if not isNative:
  355. # create link for OGR layers
  356. gcmd.RunCommand('v.external',
  357. overwrite = overwrite,
  358. parent = parent,
  359. dsn = vExternalOut['dsn'],
  360. layer = outmap)
  361. # create attribute table
  362. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  363. if isNative:
  364. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  365. gcmd.RunCommand('db.connect',
  366. flags = 'c')
  367. Debug.msg(1, "SQL: %s" % sql)
  368. gcmd.RunCommand('db.execute',
  369. quiet = True,
  370. parent = parent,
  371. input = '-',
  372. stdin = sql)
  373. gcmd.RunCommand('v.db.connect',
  374. quiet = True,
  375. parent = parent,
  376. map = outmap,
  377. table = outmap,
  378. key = key,
  379. layer = '1')
  380. # TODO: how to deal with attribute tables for OGR layers?
  381. # return fully qualified map name
  382. if '@' not in outmap:
  383. outmap += '@' + grass.gisenv()['MAPSET']
  384. if log:
  385. log.WriteLog(_("New vector map <%s> created") % outmap)
  386. return dlg
  387. class SavedRegion(wx.Dialog):
  388. def __init__(self, parent, id = wx.ID_ANY, title = "", loadsave = 'load',
  389. **kwargs):
  390. """!Loading and saving of display extents to saved region file
  391. @param loadsave load or save region?
  392. """
  393. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  394. self.loadsave = loadsave
  395. self.wind = ''
  396. sizer = wx.BoxSizer(wx.VERTICAL)
  397. box = wx.BoxSizer(wx.HORIZONTAL)
  398. label = wx.StaticText(parent = self, id = wx.ID_ANY)
  399. box.Add(item = label, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  400. if loadsave == 'load':
  401. label.SetLabel(_("Load region:"))
  402. selection = gselect.Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  403. type = 'windows')
  404. elif loadsave == 'save':
  405. label.SetLabel(_("Save region:"))
  406. selection = gselect.Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  407. type = 'windows', mapsets = [grass.gisenv()['MAPSET']])
  408. box.Add(item = selection, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  409. selection.SetFocus()
  410. selection.Bind(wx.EVT_TEXT, self.OnRegion)
  411. sizer.Add(item = box, proportion = 0, flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL,
  412. border = 5)
  413. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
  414. sizer.Add(item = line, proportion = 0,
  415. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 5)
  416. btnsizer = wx.StdDialogButtonSizer()
  417. btn = wx.Button(parent = self, id = wx.ID_OK)
  418. btn.SetDefault()
  419. btnsizer.AddButton(btn)
  420. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  421. btnsizer.AddButton(btn)
  422. btnsizer.Realize()
  423. sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  424. self.SetSizer(sizer)
  425. sizer.Fit(self)
  426. self.Layout()
  427. def OnRegion(self, event):
  428. self.wind = event.GetString()
  429. class DecorationDialog(wx.Dialog):
  430. """!Controls setting options and displaying/hiding map overlay
  431. decorations
  432. """
  433. def __init__(self, parent, ovlId, title, cmd, name = None,
  434. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE,
  435. checktxt = '', ctrltxt = ''):
  436. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  437. self.ovlId = ovlId # PseudoDC id
  438. self.cmd = cmd
  439. self.name = name # overlay name
  440. self.parent = parent # MapFrame
  441. sizer = wx.BoxSizer(wx.VERTICAL)
  442. box = wx.BoxSizer(wx.HORIZONTAL)
  443. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY, label = checktxt)
  444. if self.parent.Map.GetOverlay(self.ovlId) is None:
  445. self.chkbox.SetValue(True)
  446. else:
  447. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  448. box.Add(item = self.chkbox, proportion = 0,
  449. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  450. sizer.Add(item = box, proportion = 0,
  451. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  452. box = wx.BoxSizer(wx.HORIZONTAL)
  453. optnbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set options"))
  454. box.Add(item = optnbtn, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  455. sizer.Add(item = box, proportion = 0,
  456. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  457. if self.name == 'legend':
  458. box = wx.BoxSizer(wx.HORIZONTAL)
  459. resize = wx.ToggleButton(parent = self, id = wx.ID_ANY, label = _("Set size and position"))
  460. resize.SetToolTipString(_("Click and drag on the map display to set legend"
  461. " size and position and then press OK"))
  462. resize.SetName('resize')
  463. if self.parent.IsPaneShown('3d'):
  464. resize.Disable()
  465. box.Add(item = resize, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  466. sizer.Add(item = box, proportion = 0,
  467. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  468. box = wx.BoxSizer(wx.HORIZONTAL)
  469. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  470. label = _("Drag %s with mouse in pointer mode to position.\n"
  471. "Double-click to change options." % ctrltxt))
  472. if self.name == 'legend':
  473. label.SetLabel(label.GetLabel() + _('\nDefine raster map name for legend in '
  474. 'properties dialog.'))
  475. box.Add(item = label, proportion = 0,
  476. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  477. sizer.Add(item = box, proportion = 0,
  478. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  479. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20,-1), style = wx.LI_HORIZONTAL)
  480. sizer.Add(item = line, proportion = 0,
  481. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  482. # buttons
  483. btnsizer = wx.StdDialogButtonSizer()
  484. self.btnOK = wx.Button(parent = self, id = wx.ID_OK)
  485. self.btnOK.SetDefault()
  486. if self.name == 'legend':
  487. self.btnOK.Enable(False)
  488. btnsizer.AddButton(self.btnOK)
  489. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  490. btnsizer.AddButton(btnCancel)
  491. btnsizer.Realize()
  492. sizer.Add(item = btnsizer, proportion = 0,
  493. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  494. #
  495. # bindings
  496. #
  497. self.Bind(wx.EVT_BUTTON, self.OnOptions, optnbtn)
  498. if self.name == 'legend':
  499. self.Bind(wx.EVT_TOGGLEBUTTON, self.OnResize, resize)
  500. self.Bind(wx.EVT_BUTTON, self.OnCancel, btnCancel)
  501. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  502. self.SetSizer(sizer)
  503. sizer.Fit(self)
  504. # create overlay if doesn't exist
  505. self._createOverlay()
  506. if len(self.parent.MapWindow.overlays[self.ovlId]['cmd']) > 1:
  507. if name == 'legend':
  508. mapName, found = utils.GetLayerNameFromCmd(self.parent.MapWindow.overlays[self.ovlId]['cmd'])
  509. if found:
  510. # enable 'OK' button
  511. self.btnOK.Enable()
  512. # set title
  513. self.SetTitle(_('Legend of raster map <%s>') % \
  514. mapName)
  515. def _createOverlay(self):
  516. """!Creates overlay"""
  517. if not self.parent.GetMap().GetOverlay(self.ovlId):
  518. self.newOverlay = self.parent.Map.AddOverlay(id = self.ovlId, type = self.name,
  519. command = self.cmd,
  520. l_active = False, l_render = False, l_hidden = True)
  521. prop = { 'layer' : self.newOverlay,
  522. 'params' : None,
  523. 'propwin' : None,
  524. 'cmd' : self.cmd,
  525. 'coords': (0, 0),
  526. 'pdcType': 'image' }
  527. self.parent.MapWindow2D.overlays[self.ovlId] = prop
  528. if self.parent.MapWindow3D:
  529. self.parent.MapWindow3D.overlays[self.ovlId] = prop
  530. else:
  531. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] == None:
  532. return
  533. self.parent.MapWindow.overlays[self.ovlId]['propwin'].get_dcmd = self.GetOptData
  534. def OnOptions(self, event):
  535. """!Sets option for decoration map overlays
  536. """
  537. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None:
  538. # build properties dialog
  539. menuform.GUI(parent = self.parent).ParseCommand(cmd = self.cmd,
  540. completed = (self.GetOptData, self.name, ''))
  541. else:
  542. if self.parent.MapWindow.overlays[self.ovlId]['propwin'].IsShown():
  543. self.parent.MapWindow.overlays[self.ovlId]['propwin'].SetFocus()
  544. else:
  545. self.parent.MapWindow.overlays[self.ovlId]['propwin'].Show()
  546. def OnResize(self, event):
  547. if self.FindWindowByName('resize').GetValue():
  548. self.parent.MapWindow.SetCursor(self.parent.cursors["cross"])
  549. self.parent.MapWindow.mouse['use'] = 'legend'
  550. self.parent.MapWindow.mouse['box'] = 'box'
  551. self.parent.MapWindow.pen = wx.Pen(colour = 'Black', width = 2, style = wx.SHORT_DASH)
  552. else:
  553. self.parent.MapWindow.SetCursor(self.parent.cursors["default"])
  554. self.parent.MapWindow.mouse['use'] = 'pointer'
  555. def OnCancel(self, event):
  556. """!Cancel dialog"""
  557. if self.name == 'legend' and self.FindWindowByName('resize').GetValue():
  558. self.FindWindowByName('resize').SetValue(False)
  559. self.OnResize(None)
  560. self.parent.dialogs['barscale'] = None
  561. if event and hasattr(self, 'newOverlay'):
  562. self.parent.Map.DeleteOverlay(self.newOverlay)
  563. self.Destroy()
  564. def OnOK(self, event):
  565. """!Button 'OK' pressed"""
  566. # enable or disable overlay
  567. self.parent.Map.GetOverlay(self.ovlId).SetActive(self.chkbox.IsChecked())
  568. # update map
  569. if self.parent.IsPaneShown('3d'):
  570. self.parent.MapWindow.UpdateOverlays()
  571. self.parent.MapWindow.UpdateMap()
  572. # close dialog
  573. self.OnCancel(None)
  574. def GetOptData(self, dcmd, layer, params, propwin):
  575. """!Process decoration layer data"""
  576. # update layer data
  577. if params:
  578. self.parent.MapWindow.overlays[self.ovlId]['params'] = params
  579. if dcmd:
  580. self.parent.MapWindow.overlays[self.ovlId]['cmd'] = dcmd
  581. self.parent.MapWindow.overlays[self.ovlId]['propwin'] = propwin
  582. # change parameters for item in layers list in render.Map
  583. # "Use mouse..." (-m) flag causes GUI freeze and is pointless here, trac #119
  584. try:
  585. self.parent.MapWindow.overlays[self.ovlId]['cmd'].remove('-m')
  586. except ValueError:
  587. pass
  588. self.parent.Map.ChangeOverlay(id = self.ovlId, type = self.name,
  589. command = self.parent.MapWindow.overlays[self.ovlId]['cmd'],
  590. l_active = self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive(),
  591. l_render = False, l_hidden = True)
  592. if self.name == 'legend':
  593. if params and not self.btnOK.IsEnabled():
  594. self.btnOK.Enable()
  595. class TextLayerDialog(wx.Dialog):
  596. """
  597. Controls setting options and displaying/hiding map overlay decorations
  598. """
  599. def __init__(self, parent, ovlId, title, name = 'text',
  600. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE):
  601. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  602. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  603. self.ovlId = ovlId
  604. self.parent = parent
  605. if self.ovlId in self.parent.MapWindow.textdict.keys():
  606. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  607. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  608. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  609. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  610. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  611. self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
  612. else:
  613. self.currClr = wx.BLACK
  614. self.currText = ''
  615. self.currFont = self.GetFont()
  616. self.currRot = 0.0
  617. self.currCoords = [10, 10]
  618. self.currBB = wx.Rect()
  619. self.sizer = wx.BoxSizer(wx.VERTICAL)
  620. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  621. # show/hide
  622. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY,
  623. label = _('Show text object'))
  624. if self.parent.Map.GetOverlay(self.ovlId) is None:
  625. self.chkbox.SetValue(True)
  626. else:
  627. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  628. box.Add(item = self.chkbox, span = (1,2),
  629. flag = wx.ALIGN_LEFT|wx.ALL, border = 5,
  630. pos = (0, 0))
  631. # text entry
  632. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Enter text:"))
  633. box.Add(item = label,
  634. flag = wx.ALIGN_CENTER_VERTICAL,
  635. pos = (1, 0))
  636. self.textentry = ExpandoTextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (300,-1))
  637. self.textentry.SetFont(self.currFont)
  638. self.textentry.SetForegroundColour(self.currClr)
  639. self.textentry.SetValue(self.currText)
  640. # get rid of unneeded scrollbar when text box first opened
  641. self.textentry.SetClientSize((300,-1))
  642. box.Add(item = self.textentry,
  643. pos = (1, 1))
  644. # rotation
  645. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Rotation:"))
  646. box.Add(item = label,
  647. flag = wx.ALIGN_CENTER_VERTICAL,
  648. pos = (2, 0))
  649. self.rotation = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
  650. size = (75,-1), style = wx.SP_ARROW_KEYS)
  651. self.rotation.SetRange(-360, 360)
  652. self.rotation.SetValue(int(self.currRot))
  653. box.Add(item = self.rotation,
  654. flag = wx.ALIGN_RIGHT,
  655. pos = (2, 1))
  656. # font
  657. fontbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set font"))
  658. box.Add(item = fontbtn,
  659. flag = wx.ALIGN_RIGHT,
  660. pos = (3, 1))
  661. self.sizer.Add(item = box, proportion = 1,
  662. flag = wx.ALL, border = 10)
  663. # note
  664. box = wx.BoxSizer(wx.HORIZONTAL)
  665. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  666. label = _("Drag text with mouse in pointer mode "
  667. "to position.\nDouble-click to change options"))
  668. box.Add(item = label, proportion = 0,
  669. flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  670. self.sizer.Add(item = box, proportion = 0,
  671. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border = 5)
  672. line = wx.StaticLine(parent = self, id = wx.ID_ANY,
  673. size = (20,-1), style = wx.LI_HORIZONTAL)
  674. self.sizer.Add(item = line, proportion = 0,
  675. flag = wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border = 5)
  676. btnsizer = wx.StdDialogButtonSizer()
  677. btn = wx.Button(parent = self, id = wx.ID_OK)
  678. btn.SetDefault()
  679. btnsizer.AddButton(btn)
  680. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  681. btnsizer.AddButton(btn)
  682. btnsizer.Realize()
  683. self.sizer.Add(item = btnsizer, proportion = 0,
  684. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  685. self.SetSizer(self.sizer)
  686. self.sizer.Fit(self)
  687. # bindings
  688. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  689. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  690. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  691. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  692. def OnRefit(self, event):
  693. """!Resize text entry to match text"""
  694. self.sizer.Fit(self)
  695. def OnText(self, event):
  696. """!Change text string"""
  697. self.currText = event.GetString()
  698. def OnRotation(self, event):
  699. """!Change rotation"""
  700. self.currRot = event.GetInt()
  701. event.Skip()
  702. def OnSelectFont(self, event):
  703. """!Change font"""
  704. data = wx.FontData()
  705. data.EnableEffects(True)
  706. data.SetColour(self.currClr) # set colour
  707. data.SetInitialFont(self.currFont)
  708. dlg = wx.FontDialog(self, data)
  709. if dlg.ShowModal() == wx.ID_OK:
  710. data = dlg.GetFontData()
  711. self.currFont = data.GetChosenFont()
  712. self.currClr = data.GetColour()
  713. self.textentry.SetFont(self.currFont)
  714. self.textentry.SetForegroundColour(self.currClr)
  715. self.Layout()
  716. dlg.Destroy()
  717. def GetValues(self):
  718. """!Get text properties"""
  719. return { 'text' : self.currText,
  720. 'font' : self.currFont,
  721. 'color' : self.currClr,
  722. 'rotation' : self.currRot,
  723. 'coords' : self.currCoords,
  724. 'active' : self.chkbox.IsChecked() }
  725. class MapLayersDialog(wx.Dialog):
  726. def __init__(self, parent, title, modeler = False,
  727. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  728. """!Dialog for selecting map layers (raster, vector)"""
  729. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  730. style = style, **kwargs)
  731. self.parent = parent # GMFrame or ?
  732. # dialog body
  733. self.bodySizer = self._createDialogBody()
  734. # update list of layer to be loaded
  735. self.map_layers = [] # list of map layers (full list type/mapset)
  736. self.LoadMapLayers(self.GetLayerType(cmd = True),
  737. self.mapset.GetStringSelection())
  738. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  739. label = _("Use fully-qualified map names"))
  740. self.fullyQualified.SetValue(True)
  741. self.dseries = None
  742. if modeler:
  743. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  744. label = _("Dynamic series (%s)") % 'g.mlist')
  745. self.dseries.SetValue(False)
  746. # buttons
  747. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  748. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  749. btnOk.SetDefault()
  750. # sizers & do layout
  751. btnSizer = wx.StdDialogButtonSizer()
  752. btnSizer.AddButton(btnCancel)
  753. btnSizer.AddButton(btnOk)
  754. btnSizer.Realize()
  755. mainSizer = wx.BoxSizer(wx.VERTICAL)
  756. mainSizer.Add(item = self.bodySizer, proportion = 1,
  757. flag = wx.EXPAND | wx.ALL, border = 5)
  758. mainSizer.Add(item = self.fullyQualified, proportion = 0,
  759. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  760. if self.dseries:
  761. mainSizer.Add(item = self.dseries, proportion = 0,
  762. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  763. mainSizer.Add(item = btnSizer, proportion = 0,
  764. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  765. self.SetSizer(mainSizer)
  766. mainSizer.Fit(self)
  767. # set dialog min size
  768. self.SetMinSize(self.GetSize())
  769. def _createDialogBody(self):
  770. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  771. bodySizer.AddGrowableCol(1)
  772. bodySizer.AddGrowableRow(3)
  773. # layer type
  774. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  775. flag = wx.ALIGN_CENTER_VERTICAL,
  776. pos = (0,0))
  777. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  778. choices = [_('raster'), _('3D raster'), _('vector')], size = (100,-1))
  779. self.layerType.SetSelection(0)
  780. bodySizer.Add(item = self.layerType,
  781. pos = (0,1))
  782. # select toggle
  783. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  784. label = _("Select toggle"))
  785. self.toggle.SetValue(True)
  786. bodySizer.Add(item = self.toggle,
  787. flag = wx.ALIGN_CENTER_VERTICAL,
  788. pos = (0,2))
  789. # mapset filter
  790. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  791. flag = wx.ALIGN_CENTER_VERTICAL,
  792. pos = (1,0))
  793. self.mapset = gselect.MapsetSelect(parent = self, searchPath = True)
  794. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  795. bodySizer.Add(item = self.mapset,
  796. pos = (1,1), span = (1, 2))
  797. # map name filter
  798. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  799. flag = wx.ALIGN_CENTER_VERTICAL,
  800. pos = (2,0))
  801. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  802. value = "",
  803. size = (250,-1))
  804. bodySizer.Add(item = self.filter,
  805. flag = wx.EXPAND,
  806. pos = (2,1), span = (1, 2))
  807. # layer list
  808. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  809. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  810. pos = (3,0))
  811. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  812. size = (250, 100),
  813. choices = [])
  814. bodySizer.Add(item = self.layers,
  815. flag = wx.EXPAND,
  816. pos = (3,1), span = (1, 2))
  817. # bindings
  818. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  819. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  820. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  821. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  822. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  823. return bodySizer
  824. def LoadMapLayers(self, type, mapset):
  825. """!Load list of map layers
  826. @param type layer type ('raster' or 'vector')
  827. @param mapset mapset name
  828. """
  829. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  830. self.layers.Set(self.map_layers)
  831. # check all items by default
  832. for item in range(self.layers.GetCount()):
  833. self.layers.Check(item)
  834. def OnChangeParams(self, event):
  835. """!Filter parameters changed by user"""
  836. # update list of layer to be loaded
  837. self.LoadMapLayers(self.GetLayerType(cmd = True),
  838. self.mapset.GetStringSelection())
  839. event.Skip()
  840. def OnMenu(self, event):
  841. """!Table description area, context menu"""
  842. if not hasattr(self, "popupID1"):
  843. self.popupDataID1 = wx.NewId()
  844. self.popupDataID2 = wx.NewId()
  845. self.popupDataID3 = wx.NewId()
  846. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  847. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  848. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  849. # generate popup-menu
  850. menu = wx.Menu()
  851. menu.Append(self.popupDataID1, _("Select all"))
  852. menu.Append(self.popupDataID2, _("Invert selection"))
  853. menu.Append(self.popupDataID3, _("Deselect all"))
  854. self.PopupMenu(menu)
  855. menu.Destroy()
  856. def OnSelectAll(self, event):
  857. """!Select all map layer from list"""
  858. for item in range(self.layers.GetCount()):
  859. self.layers.Check(item, True)
  860. def OnSelectInvert(self, event):
  861. """!Invert current selection"""
  862. for item in range(self.layers.GetCount()):
  863. if self.layers.IsChecked(item):
  864. self.layers.Check(item, False)
  865. else:
  866. self.layers.Check(item, True)
  867. def OnDeselectAll(self, event):
  868. """!Select all map layer from list"""
  869. for item in range(self.layers.GetCount()):
  870. self.layers.Check(item, False)
  871. def OnFilter(self, event):
  872. """!Apply filter for map names"""
  873. if len(event.GetString()) == 0:
  874. self.layers.Set(self.map_layers)
  875. return
  876. list = []
  877. for layer in self.map_layers:
  878. try:
  879. if re.compile('^' + event.GetString()).search(layer):
  880. list.append(layer)
  881. except:
  882. pass
  883. self.layers.Set(list)
  884. self.OnSelectAll(None)
  885. event.Skip()
  886. def OnToggle(self, event):
  887. """!Select toggle (check or uncheck all layers)"""
  888. check = event.Checked()
  889. for item in range(self.layers.GetCount()):
  890. self.layers.Check(item, check)
  891. event.Skip()
  892. def GetMapLayers(self):
  893. """!Return list of checked map layers"""
  894. layerNames = []
  895. for indx in self.layers.GetSelections():
  896. # layers.append(self.layers.GetStringSelec(indx))
  897. pass
  898. fullyQualified = self.fullyQualified.IsChecked()
  899. mapset = self.mapset.GetStringSelection()
  900. for item in range(self.layers.GetCount()):
  901. if not self.layers.IsChecked(item):
  902. continue
  903. if fullyQualified:
  904. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  905. else:
  906. layerNames.append(self.layers.GetString(item))
  907. return layerNames
  908. def GetLayerType(self, cmd = False):
  909. """!Get selected layer type
  910. @param cmd True for g.mlist
  911. """
  912. if not cmd:
  913. return self.layerType.GetStringSelection()
  914. sel = self.layerType.GetSelection()
  915. if sel == 0:
  916. ltype = 'rast'
  917. elif sel == 1:
  918. ltype = 'rast3d'
  919. else:
  920. ltype = 'vect'
  921. return ltype
  922. def GetDSeries(self):
  923. """!Used by modeler only
  924. @return g.mlist command
  925. """
  926. if not self.dseries or not self.dseries.IsChecked():
  927. return ''
  928. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  929. patt = self.filter.GetValue()
  930. if patt:
  931. cond += 'pattern=%s ' % patt
  932. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  933. return cond
  934. class ImportDialog(wx.Dialog):
  935. """!Dialog for bulk import of various data (base class)"""
  936. def __init__(self, parent, itype,
  937. id = wx.ID_ANY, title = _("Multiple import"),
  938. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  939. self.parent = parent # GMFrame
  940. self.importType = itype
  941. self.options = dict() # list of options
  942. self.commandId = -1 # id of running command
  943. wx.Dialog.__init__(self, parent, id, title, style = style,
  944. name = "MultiImportDialog")
  945. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  946. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  947. label = _(" List of %s layers ") % self.importType.upper())
  948. #
  949. # list of layers
  950. #
  951. columns = [_('Layer id'),
  952. _('Layer name'),
  953. _('Name for GRASS map (editable)')]
  954. if itype == 'ogr':
  955. columns.insert(2, _('Feature type'))
  956. self.list = LayersList(parent = self.panel, columns = columns)
  957. self.list.LoadData()
  958. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  959. label = "%s" % _("Options"))
  960. cmd = self._getCommand()
  961. task = gtask.parse_interface(cmd)
  962. for f in task.get_options()['flags']:
  963. name = f.get('name', '')
  964. desc = f.get('label', '')
  965. if not desc:
  966. desc = f.get('description', '')
  967. if not name and not desc:
  968. continue
  969. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  970. continue
  971. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  972. continue
  973. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  974. continue
  975. elif cmd == 'v.external' and name not in ('b'):
  976. continue
  977. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  978. continue
  979. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  980. label = desc)
  981. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  982. label = _("Allow output files to overwrite existing files"))
  983. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  984. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  985. #
  986. # buttons
  987. #
  988. # cancel
  989. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  990. self.btn_cancel.SetToolTipString(_("Close dialog"))
  991. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  992. # run
  993. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  994. self.btn_run.SetToolTipString(_("Import selected layers"))
  995. self.btn_run.SetDefault()
  996. self.btn_run.Enable(False)
  997. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  998. # run command dialog
  999. self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  1000. label = _("Command dialog"))
  1001. self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  1002. def doLayout(self):
  1003. """!Do layout"""
  1004. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1005. # dsn input
  1006. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1007. flag = wx.EXPAND)
  1008. #
  1009. # list of DXF layers
  1010. #
  1011. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1012. layerSizer.Add(item = self.list, proportion = 1,
  1013. flag = wx.ALL | wx.EXPAND, border = 5)
  1014. dialogSizer.Add(item = layerSizer, proportion = 1,
  1015. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1016. # options
  1017. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1018. for key in self.options.keys():
  1019. optionSizer.Add(item = self.options[key], proportion = 0)
  1020. dialogSizer.Add(item = optionSizer, proportion = 0,
  1021. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1022. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1023. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1024. dialogSizer.Add(item = self.add, proportion = 0,
  1025. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1026. #
  1027. # buttons
  1028. #
  1029. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1030. btnsizer.Add(item = self.btn_cmd, proportion = 0,
  1031. flag = wx.ALL | wx.ALIGN_CENTER,
  1032. border = 10)
  1033. btnsizer.Add(item = self.btn_run, proportion = 0,
  1034. flag = wx.ALL | wx.ALIGN_CENTER,
  1035. border = 10)
  1036. btnsizer.Add(item = self.btn_cancel, proportion = 0,
  1037. flag = wx.ALL | wx.ALIGN_CENTER,
  1038. border = 10)
  1039. dialogSizer.Add(item = btnsizer, proportion = 0,
  1040. flag = wx.ALIGN_CENTER)
  1041. # dialogSizer.SetSizeHints(self.panel)
  1042. self.panel.SetAutoLayout(True)
  1043. self.panel.SetSizer(dialogSizer)
  1044. dialogSizer.Fit(self.panel)
  1045. # auto-layout seems not work here - FIXME
  1046. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1047. self.SetMinSize(size)
  1048. self.SetSize((size.width, size.height + 100))
  1049. # width = self.GetSize()[0]
  1050. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1051. self.Layout()
  1052. def _getCommand(self):
  1053. """!Get command"""
  1054. return ''
  1055. def OnCancel(self, event = None):
  1056. """!Close dialog"""
  1057. self.Close()
  1058. def OnRun(self, event):
  1059. """!Import/Link data (each layes as separate vector map)"""
  1060. pass
  1061. def OnCmdDialog(self, event):
  1062. """!Show command dialog"""
  1063. pass
  1064. def AddLayers(self, returncode, cmd = None):
  1065. """!Add imported/linked layers into layer tree"""
  1066. self.commandId += 1
  1067. if not self.add.IsChecked() or returncode != 0:
  1068. return
  1069. maptree = self.parent.curr_page.maptree
  1070. layer, output = self.list.GetLayers()[self.commandId]
  1071. if '@' not in output:
  1072. name = output + '@' + grass.gisenv()['MAPSET']
  1073. else:
  1074. name = output
  1075. # add imported layers into layer tree
  1076. if self.importType == 'gdal':
  1077. cmd = ['d.rast',
  1078. 'map=%s' % name]
  1079. if UserSettings.Get(group = 'cmd', key = 'rasterOverlay', subkey = 'enabled'):
  1080. cmd.append('-o')
  1081. item = maptree.AddLayer(ltype = 'raster',
  1082. lname = name, lchecked = False,
  1083. lcmd = cmd)
  1084. else:
  1085. item = maptree.AddLayer(ltype = 'vector',
  1086. lname = name, lchecked = False,
  1087. lcmd = ['d.vect',
  1088. 'map=%s' % name])
  1089. maptree.mapdisplay.MapWindow.ZoomToMap()
  1090. def OnAbort(self, event):
  1091. """!Abort running import
  1092. @todo not yet implemented
  1093. """
  1094. pass
  1095. class GdalImportDialog(ImportDialog):
  1096. def __init__(self, parent, ogr = False, link = False):
  1097. """!Dialog for bulk import of various raster/vector data
  1098. @param parent parent window
  1099. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1100. @param link True for linking data otherwise importing data
  1101. """
  1102. self.link = link
  1103. self.ogr = ogr
  1104. if ogr:
  1105. ImportDialog.__init__(self, parent, itype = 'ogr')
  1106. if link:
  1107. self.SetTitle(_("Link external vector data"))
  1108. else:
  1109. self.SetTitle(_("Import vector data"))
  1110. else:
  1111. ImportDialog.__init__(self, parent, itype = 'gdal')
  1112. if link:
  1113. self.SetTitle(_("Link external raster data"))
  1114. else:
  1115. self.SetTitle(_("Import raster data"))
  1116. self.dsnInput = gselect.GdalSelect(parent = self, panel = self.panel, ogr = ogr)
  1117. if link:
  1118. self.add.SetLabel(_("Add linked layers into layer tree"))
  1119. else:
  1120. self.add.SetLabel(_("Add imported layers into layer tree"))
  1121. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1122. if link:
  1123. self.btn_run.SetLabel(_("&Link"))
  1124. self.btn_run.SetToolTipString(_("Link selected layers"))
  1125. if ogr:
  1126. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.external')
  1127. else:
  1128. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.external')
  1129. else:
  1130. self.btn_run.SetLabel(_("&Import"))
  1131. self.btn_run.SetToolTipString(_("Import selected layers"))
  1132. if ogr:
  1133. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.in.ogr')
  1134. else:
  1135. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.in.gdal')
  1136. self.doLayout()
  1137. def OnRun(self, event):
  1138. """!Import/Link data (each layes as separate vector map)"""
  1139. data = self.list.GetLayers()
  1140. # hide dialog
  1141. self.Hide()
  1142. dsn = self.dsnInput.GetDsn()
  1143. ext = self.dsnInput.GetFormatExt()
  1144. for layer, output in data:
  1145. if self.importType == 'ogr':
  1146. if ext and layer.rfind(ext) > -1:
  1147. layer = layer.replace('.' + ext, '')
  1148. if self.link:
  1149. cmd = ['v.external',
  1150. 'dsn=%s' % dsn,
  1151. 'output=%s' % output,
  1152. 'layer=%s' % layer]
  1153. else:
  1154. cmd = ['v.in.ogr',
  1155. 'dsn=%s' % dsn,
  1156. 'layer=%s' % layer,
  1157. 'output=%s' % output]
  1158. else: # gdal
  1159. if self.dsnInput.GetType() == 'dir':
  1160. idsn = os.path.join(dsn, layer)
  1161. else:
  1162. idsn = dsn
  1163. if self.link:
  1164. cmd = ['r.external',
  1165. 'input=%s' % idsn,
  1166. 'output=%s' % output]
  1167. else:
  1168. cmd = ['r.in.gdal',
  1169. 'input=%s' % idsn,
  1170. 'output=%s' % output]
  1171. if self.overwrite.IsChecked():
  1172. cmd.append('--overwrite')
  1173. for key in self.options.keys():
  1174. if self.options[key].IsChecked():
  1175. cmd.append('-%s' % key)
  1176. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1177. cmd.append('--overwrite')
  1178. # run in Layer Manager
  1179. self.parent.goutput.RunCmd(cmd, switchPage = True,
  1180. onDone = self.AddLayers)
  1181. self.OnCancel()
  1182. def _getCommand(self):
  1183. """!Get command"""
  1184. if self.link:
  1185. if self.ogr:
  1186. return 'v.external'
  1187. else:
  1188. return 'r.external'
  1189. else:
  1190. if self.ogr:
  1191. return 'v.in.ogr'
  1192. else:
  1193. return 'r.in.gdal'
  1194. return ''
  1195. def OnCmdDialog(self, event):
  1196. """!Show command dialog"""
  1197. name = self._getCommand()
  1198. menuform.GUI(parent = self, modal = True).ParseCommand(cmd = [name])
  1199. class GdalOutputDialog(wx.Dialog):
  1200. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1201. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1202. """!Dialog for setting output format for rasters/vectors
  1203. @param parent parent window
  1204. @param id window id
  1205. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1206. @param style window style
  1207. @param *kwargs other wx.Dialog's arguments
  1208. """
  1209. self.parent = parent # GMFrame
  1210. self.ogr = ogr
  1211. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1212. if self.ogr:
  1213. self.SetTitle(_("Define output format for vector data"))
  1214. else:
  1215. self.SetTitle(_("Define output format for raster data"))
  1216. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1217. # buttons
  1218. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1219. self.btnCancel.SetToolTipString(_("Close dialog"))
  1220. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1221. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1222. self.btnOk.SetDefault()
  1223. self.btnOk.Enable(False)
  1224. self.dsnInput = gselect.GdalSelect(parent = self, panel = self.panel,
  1225. ogr = ogr,
  1226. exclude = ['file', 'protocol'], dest = True)
  1227. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1228. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1229. self._layout()
  1230. def _layout(self):
  1231. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1232. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1233. flag = wx.EXPAND)
  1234. btnSizer = wx.StdDialogButtonSizer()
  1235. btnSizer.AddButton(self.btnOk)
  1236. btnSizer.AddButton(self.btnCancel)
  1237. btnSizer.Realize()
  1238. dialogSizer.Add(item = btnSizer, proportion = 0,
  1239. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  1240. border = 5)
  1241. self.panel.SetAutoLayout(True)
  1242. self.panel.SetSizer(dialogSizer)
  1243. dialogSizer.Fit(self.panel)
  1244. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1245. self.SetMinSize(size)
  1246. self.SetSize((size.width, size.height))
  1247. self.Layout()
  1248. def OnCancel(self, event):
  1249. self.Destroy()
  1250. def OnOK(self, event):
  1251. if self.dsnInput.GetType() == 'native':
  1252. gcmd.RunCommand('v.external.out',
  1253. parent = self,
  1254. flags = 'r')
  1255. else:
  1256. dsn = self.dsnInput.GetDsn()
  1257. frmt = self.dsnInput.GetFormat()
  1258. options = self.dsnInput.GetOptions()
  1259. gcmd.RunCommand('v.external.out',
  1260. parent = self,
  1261. dsn = dsn, format = frmt,
  1262. options = options)
  1263. self.Close()
  1264. class DxfImportDialog(ImportDialog):
  1265. """!Dialog for bulk import of DXF layers"""
  1266. def __init__(self, parent):
  1267. ImportDialog.__init__(self, parent, itype = 'dxf',
  1268. title = _("Import DXF layers"))
  1269. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1270. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1271. dialogTitle = _('Choose DXF file to import'),
  1272. buttonText = _('Browse'),
  1273. startDirectory = os.getcwd(), fileMode = 0,
  1274. changeCallback = self.OnSetDsn,
  1275. fileMask = "DXF File (*.dxf)|*.dxf")
  1276. self.add.SetLabel(_("Add imported layers into layer tree"))
  1277. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1278. self.doLayout()
  1279. def _getCommand(self):
  1280. """!Get command"""
  1281. return 'v.in.dxf'
  1282. def OnRun(self, event):
  1283. """!Import/Link data (each layes as separate vector map)"""
  1284. data = self.list.GetLayers()
  1285. # hide dialog
  1286. self.Hide()
  1287. inputDxf = self.dsnInput.GetValue()
  1288. for layer, output in data:
  1289. cmd = ['v.in.dxf',
  1290. 'input=%s' % inputDxf,
  1291. 'layers=%s' % layer,
  1292. 'output=%s' % output]
  1293. for key in self.options.keys():
  1294. if self.options[key].IsChecked():
  1295. cmd.append('-%s' % key)
  1296. if self.overwrite.IsChecked() or \
  1297. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1298. cmd.append('--overwrite')
  1299. # run in Layer Manager
  1300. self.parent.goutput.RunCmd(cmd, switchPage = True,
  1301. onDone = self.AddLayers)
  1302. self.OnCancel()
  1303. def OnSetDsn(self, event):
  1304. """!Input DXF file defined, update list of layer widget"""
  1305. path = event.GetString()
  1306. if not path:
  1307. return
  1308. data = list()
  1309. ret = gcmd.RunCommand('v.in.dxf',
  1310. quiet = True,
  1311. parent = self,
  1312. read = True,
  1313. flags = 'l',
  1314. input = path)
  1315. if not ret:
  1316. self.list.LoadData()
  1317. self.btn_run.Enable(False)
  1318. return
  1319. for line in ret.splitlines():
  1320. layerId = line.split(':')[0].split(' ')[1]
  1321. layerName = line.split(':')[1].strip()
  1322. grassName = utils.GetValidLayerName(layerName)
  1323. data.append((layerId, layerName.strip(), grassName.strip()))
  1324. self.list.LoadData(data)
  1325. if len(data) > 0:
  1326. self.btn_run.Enable(True)
  1327. else:
  1328. self.btn_run.Enable(False)
  1329. def OnCmdDialog(self, event):
  1330. """!Show command dialog"""
  1331. menuform.GUI(parent = self, modal = True).ParseCommand(cmd = ['v.in.dxf'])
  1332. class LayersList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin,
  1333. listmix.CheckListCtrlMixin, listmix.TextEditMixin):
  1334. """!List of layers to be imported (dxf, shp...)"""
  1335. def __init__(self, parent, columns, log = None):
  1336. self.parent = parent
  1337. wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
  1338. style = wx.LC_REPORT)
  1339. listmix.CheckListCtrlMixin.__init__(self)
  1340. self.log = log
  1341. # setup mixins
  1342. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1343. listmix.TextEditMixin.__init__(self)
  1344. for i in range(len(columns)):
  1345. self.InsertColumn(i, columns[i])
  1346. if len(columns) == 3:
  1347. width = (65, 200)
  1348. else:
  1349. width = (65, 200, 90)
  1350. for i in range(len(width)):
  1351. self.SetColumnWidth(col = i, width = width[i])
  1352. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) #wxMSW
  1353. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) #wxGTK
  1354. def LoadData(self, data = None):
  1355. """!Load data into list"""
  1356. if data is None:
  1357. return
  1358. self.DeleteAllItems()
  1359. for item in data:
  1360. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1361. for i in range(1, len(item)):
  1362. self.SetStringItem(index, i, "%s" % str(item[i]))
  1363. # check by default
  1364. ### self.CheckItem(index, True)
  1365. def OnPopupMenu(self, event):
  1366. """!Show popup menu"""
  1367. if self.GetItemCount() < 1:
  1368. return
  1369. if not hasattr(self, "popupDataID1"):
  1370. self.popupDataID1 = wx.NewId()
  1371. self.popupDataID2 = wx.NewId()
  1372. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1373. self.Bind(wx.EVT_MENU, self.OnSelectNone, id = self.popupDataID2)
  1374. # generate popup-menu
  1375. menu = wx.Menu()
  1376. menu.Append(self.popupDataID1, _("Select all"))
  1377. menu.Append(self.popupDataID2, _("Deselect all"))
  1378. self.PopupMenu(menu)
  1379. menu.Destroy()
  1380. def OnSelectAll(self, event):
  1381. """!Select all items"""
  1382. item = -1
  1383. while True:
  1384. item = self.GetNextItem(item)
  1385. if item == -1:
  1386. break
  1387. self.CheckItem(item, True)
  1388. event.Skip()
  1389. def OnSelectNone(self, event):
  1390. """!Deselect items"""
  1391. item = -1
  1392. while True:
  1393. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  1394. if item == -1:
  1395. break
  1396. self.CheckItem(item, False)
  1397. event.Skip()
  1398. def OnLeftDown(self, event):
  1399. """!Allow editing only output name
  1400. Code taken from TextEditMixin class.
  1401. """
  1402. x, y = event.GetPosition()
  1403. colLocs = [0]
  1404. loc = 0
  1405. for n in range(self.GetColumnCount()):
  1406. loc = loc + self.GetColumnWidth(n)
  1407. colLocs.append(loc)
  1408. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1409. if col == self.GetColumnCount() - 1:
  1410. listmix.TextEditMixin.OnLeftDown(self, event)
  1411. else:
  1412. event.Skip()
  1413. def GetLayers(self):
  1414. """!Get list of layers (layer name, output name)"""
  1415. data = []
  1416. item = -1
  1417. while True:
  1418. item = self.GetNextItem(item)
  1419. if item == -1:
  1420. break
  1421. if not self.IsChecked(item):
  1422. continue
  1423. # layer / output name
  1424. data.append((self.GetItem(item, 1).GetText(),
  1425. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1426. return data
  1427. class SetOpacityDialog(wx.Dialog):
  1428. """!Set opacity of map layers"""
  1429. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1430. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1431. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1432. self.parent = parent # GMFrame
  1433. self.opacity = opacity # current opacity
  1434. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1435. size = size, style = style, title = title)
  1436. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1437. sizer = wx.BoxSizer(wx.VERTICAL)
  1438. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1439. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1440. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1441. wx.SL_TOP | wx.SL_LABELS,
  1442. minValue = 0, maxValue = 100,
  1443. size = (350, -1))
  1444. box.Add(item = self.value,
  1445. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1446. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1447. label = _("transparent")),
  1448. pos = (1, 0))
  1449. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1450. label = _("opaque")),
  1451. flag = wx.ALIGN_RIGHT,
  1452. pos = (1, 1))
  1453. sizer.Add(item = box, proportion = 0,
  1454. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1455. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1456. style = wx.LI_HORIZONTAL)
  1457. sizer.Add(item = line, proportion = 0,
  1458. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1459. # buttons
  1460. btnsizer = wx.StdDialogButtonSizer()
  1461. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1462. btnOK.SetDefault()
  1463. btnsizer.AddButton(btnOK)
  1464. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1465. btnsizer.AddButton(btnCancel)
  1466. btnsizer.Realize()
  1467. sizer.Add(item = btnsizer, proportion = 0,
  1468. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1469. panel.SetSizer(sizer)
  1470. sizer.Fit(panel)
  1471. self.SetSize(self.GetBestSize())
  1472. self.Layout()
  1473. def GetOpacity(self):
  1474. """!Button 'OK' pressed"""
  1475. # return opacity value
  1476. opacity = float(self.value.GetValue()) / 100
  1477. return opacity
  1478. def GetImageHandlers(image):
  1479. """!Get list of supported image handlers"""
  1480. lext = list()
  1481. ltype = list()
  1482. for h in image.GetHandlers():
  1483. lext.append(h.GetExtension())
  1484. filetype = ''
  1485. if 'png' in lext:
  1486. filetype += "PNG file (*.png)|*.png|"
  1487. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1488. 'ext' : 'png' })
  1489. filetype += "BMP file (*.bmp)|*.bmp|"
  1490. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1491. 'ext' : 'bmp' })
  1492. if 'gif' in lext:
  1493. filetype += "GIF file (*.gif)|*.gif|"
  1494. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1495. 'ext' : 'gif' })
  1496. if 'jpg' in lext:
  1497. filetype += "JPG file (*.jpg)|*.jpg|"
  1498. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1499. 'ext' : 'jpg' })
  1500. if 'pcx' in lext:
  1501. filetype += "PCX file (*.pcx)|*.pcx|"
  1502. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1503. 'ext' : 'pcx' })
  1504. if 'pnm' in lext:
  1505. filetype += "PNM file (*.pnm)|*.pnm|"
  1506. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1507. 'ext' : 'pnm' })
  1508. if 'tif' in lext:
  1509. filetype += "TIF file (*.tif)|*.tif|"
  1510. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1511. 'ext' : 'tif' })
  1512. if 'xpm' in lext:
  1513. filetype += "XPM file (*.xpm)|*.xpm"
  1514. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1515. 'ext' : 'xpm' })
  1516. return filetype, ltype
  1517. class StaticWrapText(wx.StaticText):
  1518. """!A Static Text field that wraps its text to fit its width,
  1519. enlarging its height if necessary.
  1520. """
  1521. def __init__(self, parent, id = wx.ID_ANY, label = '', *args, **kwds):
  1522. self.parent = parent
  1523. self.originalLabel = label
  1524. wx.StaticText.__init__(self, parent, id, label = '', *args, **kwds)
  1525. self.SetLabel(label)
  1526. self.Bind(wx.EVT_SIZE, self.OnResize)
  1527. def SetLabel(self, label):
  1528. self.originalLabel = label
  1529. self.wrappedSize = None
  1530. self.OnResize(None)
  1531. def OnResize(self, event):
  1532. if not getattr(self, "resizing", False):
  1533. self.resizing = True
  1534. newSize = wx.Size(self.parent.GetSize().width - 50,
  1535. self.GetSize().height)
  1536. if self.wrappedSize != newSize:
  1537. wx.StaticText.SetLabel(self, self.originalLabel)
  1538. self.Wrap(newSize.width)
  1539. self.wrappedSize = newSize
  1540. self.SetSize(self.wrappedSize)
  1541. del self.resizing
  1542. class ImageSizeDialog(wx.Dialog):
  1543. """!Set size for saved graphic file"""
  1544. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1545. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1546. self.parent = parent
  1547. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1548. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1549. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1550. label = ' % s' % _("Image size"))
  1551. size = self.parent.GetWindow().GetClientSize()
  1552. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1553. style = wx.SP_ARROW_KEYS)
  1554. self.width.SetRange(20, 1e6)
  1555. self.width.SetValue(size.width)
  1556. wx.CallAfter(self.width.SetFocus)
  1557. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1558. style = wx.SP_ARROW_KEYS)
  1559. self.height.SetRange(20, 1e6)
  1560. self.height.SetValue(size.height)
  1561. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1562. size = (125, -1),
  1563. choices = [ "",
  1564. "640x480",
  1565. "800x600",
  1566. "1024x768",
  1567. "1280x960",
  1568. "1600x1200",
  1569. "1920x1440" ])
  1570. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1571. self.btnOK.SetDefault()
  1572. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1573. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1574. self._layout()
  1575. self.SetSize(self.GetBestSize())
  1576. def _layout(self):
  1577. """!Do layout"""
  1578. sizer = wx.BoxSizer(wx.VERTICAL)
  1579. # body
  1580. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1581. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1582. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1583. label = _("Width:")),
  1584. flag = wx.ALIGN_CENTER_VERTICAL)
  1585. fbox.Add(item = self.width)
  1586. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1587. label = _("Height:")),
  1588. flag = wx.ALIGN_CENTER_VERTICAL)
  1589. fbox.Add(item = self.height)
  1590. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1591. label = _("Template:")),
  1592. flag = wx.ALIGN_CENTER_VERTICAL)
  1593. fbox.Add(item = self.template)
  1594. box.Add(item = fbox, proportion = 1,
  1595. flag = wx.EXPAND | wx.ALL, border = 5)
  1596. sizer.Add(item = box, proportion = 1,
  1597. flag=wx.EXPAND | wx.ALL, border = 3)
  1598. # buttons
  1599. btnsizer = wx.StdDialogButtonSizer()
  1600. btnsizer.AddButton(self.btnOK)
  1601. btnsizer.AddButton(self.btnCancel)
  1602. btnsizer.Realize()
  1603. sizer.Add(item = btnsizer, proportion = 0,
  1604. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1605. self.panel.SetSizer(sizer)
  1606. sizer.Fit(self.panel)
  1607. self.Layout()
  1608. def GetValues(self):
  1609. """!Get width/height values"""
  1610. return self.width.GetValue(), self.height.GetValue()
  1611. def OnTemplate(self, event):
  1612. """!Template selected"""
  1613. sel = event.GetString()
  1614. if not sel:
  1615. width, height = self.parent.GetWindow().GetClientSize()
  1616. else:
  1617. width, height = map(int, sel.split('x'))
  1618. self.width.SetValue(width)
  1619. self.height.SetValue(height)
  1620. class SqlQueryFrame(wx.Frame):
  1621. def __init__(self, parent, id = wx.ID_ANY,
  1622. title = _("GRASS GIS SQL Query Utility"),
  1623. *kwargs):
  1624. """!SQL Query Utility window
  1625. """
  1626. self.parent = parent
  1627. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1628. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1629. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1630. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1631. label = _(" SQL statement "))
  1632. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1633. style = wx.TE_MULTILINE)
  1634. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1635. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1636. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1637. self._layout()
  1638. self.SetMinSize(wx.Size(300, 150))
  1639. self.SetSize(wx.Size(500, 200))
  1640. def _layout(self):
  1641. """!Do layout"""
  1642. sizer = wx.BoxSizer(wx.VERTICAL)
  1643. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1644. sqlSizer.Add(item = self.sql, proportion = 1,
  1645. flag = wx.EXPAND)
  1646. btnSizer = wx.StdDialogButtonSizer()
  1647. btnSizer.AddButton(self.btnApply)
  1648. btnSizer.AddButton(self.btnCancel)
  1649. btnSizer.Realize()
  1650. sizer.Add(item = sqlSizer, proportion = 1,
  1651. flag = wx.EXPAND | wx.ALL, border = 5)
  1652. sizer.Add(item = btnSizer, proportion = 0,
  1653. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1654. self.panel.SetSizer(sizer)
  1655. self.Layout()
  1656. def OnCloseWindow(self, event):
  1657. """!Close window
  1658. """
  1659. self.Close()