colorrules.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930
  1. """
  2. @package module.colorrules
  3. @brief Dialog for interactive management of raster/vector color tables
  4. and color rules.
  5. Classes:
  6. - colorrules::RulesPanel
  7. - colorrules::ColorTable
  8. - colorrules::RasterColorTable
  9. - colorrules::VectorColorTable
  10. - colorrules::ThematicVectorTable
  11. - colorrules::BufferedWindow
  12. (C) 2008-2015 by the GRASS Development Team
  13. This program is free software under the GNU General Public License
  14. (>=v2). Read the file COPYING that comes with GRASS for details.
  15. @author Michael Barton (Arizona State University)
  16. @author Martin Landa <landa.martin gmail.com> (various updates, pre-defined color table)
  17. @author Anna Kratochvilova <kratochanna gmail.com> (split to base and derived classes)
  18. """
  19. import os
  20. import shutil
  21. import copy
  22. import tempfile
  23. import wx
  24. import wx.lib.colourselect as csel
  25. import wx.lib.scrolledpanel as scrolled
  26. import wx.lib.filebrowsebutton as filebrowse
  27. import grass.script as grass
  28. from grass.script.task import cmdlist_to_tuple
  29. from core import globalvar
  30. from core import utils
  31. from core.utils import _
  32. from core.gcmd import GMessage, RunCommand, GError
  33. from gui_core.gselect import Select, LayerSelect, ColumnSelect, VectorDBInfo
  34. from core.render import Map
  35. from gui_core.forms import GUI
  36. from core.debug import Debug as Debug
  37. from core.settings import UserSettings
  38. from gui_core.widgets import ColorTablesComboBox
  39. class RulesPanel:
  40. def __init__(self, parent, mapType, attributeType, properties, panelWidth = 180):
  41. """Create rules panel
  42. :param mapType: raster/vector
  43. :param attributeType: color/size for choosing widget type
  44. :param properties: properties of classes derived from ColorTable
  45. :param panelWidth: width of scroll panel"""
  46. self.ruleslines = {}
  47. self.mapType = mapType
  48. self.attributeType = attributeType
  49. self.properties = properties
  50. self.parent = parent
  51. self.panelWidth = panelWidth
  52. self.mainSizer = wx.FlexGridSizer(cols = 3, vgap = 6, hgap = 4)
  53. # put small border at the top of panel
  54. for i in range(3):
  55. self.mainSizer.Add(item = wx.Size(3, 3))
  56. self.mainPanel = scrolled.ScrolledPanel(parent, id = wx.ID_ANY,
  57. size = (self.panelWidth, 300),
  58. style = wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
  59. # (un)check all
  60. self.checkAll = wx.CheckBox(parent, id = wx.ID_ANY, label = _("Check all"))
  61. self.checkAll.SetValue(True)
  62. # clear button
  63. self.clearAll = wx.Button(parent, id = wx.ID_ANY, label = _("Clear all"))
  64. # determines how many rules should be added
  65. self.numRules = wx.SpinCtrl(parent, id = wx.ID_ANY,
  66. min = 1, max = 1e6, initial = 1)
  67. # add rules
  68. self.btnAdd = wx.Button(parent, id = wx.ID_ADD)
  69. self.btnAdd.Bind(wx.EVT_BUTTON, self.OnAddRules)
  70. self.checkAll.Bind(wx.EVT_CHECKBOX, self.OnCheckAll)
  71. self.clearAll.Bind(wx.EVT_BUTTON, self.OnClearAll)
  72. self.mainPanel.SetSizer(self.mainSizer)
  73. self.mainPanel.SetAutoLayout(True)
  74. self.mainPanel.SetupScrolling()
  75. def Clear(self):
  76. """Clear and widgets and delete information"""
  77. self.ruleslines.clear()
  78. self.mainSizer.Clear(deleteWindows=True)
  79. def OnCheckAll(self, event):
  80. """(Un)check all rules"""
  81. check = event.GetInt()
  82. for child in self.mainPanel.GetChildren():
  83. if child.GetName() == 'enable':
  84. child.SetValue(check)
  85. else:
  86. child.Enable(check)
  87. def OnClearAll(self, event):
  88. """Delete all widgets in panel"""
  89. self.Clear()
  90. def OnAddRules(self, event):
  91. """Add rules button pressed"""
  92. nrules = self.numRules.GetValue()
  93. self.AddRules(nrules)
  94. def AddRules(self, nrules, start = False):
  95. """Add rules
  96. :param start: set widgets (not append)
  97. """
  98. snum = len(self.ruleslines.keys())
  99. if start:
  100. snum = 0
  101. for num in range(snum, snum + nrules):
  102. # enable
  103. enable = wx.CheckBox(parent = self.mainPanel, id = num)
  104. enable.SetValue(True)
  105. enable.SetName('enable')
  106. enable.Bind(wx.EVT_CHECKBOX, self.OnRuleEnable)
  107. # value
  108. txt_ctrl = wx.TextCtrl(parent = self.mainPanel, id = 1000 + num,
  109. size = (80, -1),
  110. style = wx.TE_NOHIDESEL)
  111. if self.mapType == 'vector':
  112. txt_ctrl.SetToolTipString(_("Enter vector attribute values"))
  113. txt_ctrl.Bind(wx.EVT_TEXT, self.OnRuleValue)
  114. txt_ctrl.SetName('source')
  115. if self.attributeType == 'color':
  116. # color
  117. columnCtrl = csel.ColourSelect(self.mainPanel, id = 2000 + num,
  118. size = globalvar.DIALOG_COLOR_SIZE)
  119. columnCtrl.Bind(csel.EVT_COLOURSELECT, self.OnRuleColor)
  120. columnCtrl.SetName('target')
  121. if not start:
  122. self.ruleslines[enable.GetId()] = { 'value' : '',
  123. 'color': "0:0:0" }
  124. else:
  125. # size or width
  126. init = 2
  127. if self.attributeType == 'size':
  128. init = 100
  129. columnCtrl = wx.SpinCtrl(self.mainPanel, id = 2000 + num,
  130. size = (50, -1), min = 1, max = 1e4,
  131. initial = init)
  132. columnCtrl.Bind(wx.EVT_SPINCTRL, self.OnRuleSize)
  133. columnCtrl.Bind(wx.EVT_TEXT, self.OnRuleSize)
  134. columnCtrl.SetName('target')
  135. if not start:
  136. self.ruleslines[enable.GetId()] = { 'value' : '',
  137. self.attributeType: init }
  138. self.mainSizer.Add(item = enable, proportion = 0,
  139. flag = wx.ALIGN_CENTER_VERTICAL)
  140. self.mainSizer.Add(item = txt_ctrl, proportion = 0,
  141. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  142. self.mainSizer.Add(item = columnCtrl, proportion = 0,
  143. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 10)
  144. self.mainPanel.Layout()
  145. self.mainPanel.SetupScrolling(scroll_x = False)
  146. def OnRuleEnable(self, event):
  147. """Rule enabled/disabled"""
  148. id = event.GetId()
  149. if event.IsChecked():
  150. self.mainPanel.FindWindowById(id + 1000).Enable()
  151. self.mainPanel.FindWindowById(id + 2000).Enable()
  152. if self.mapType == 'vector' and not self.parent.GetParent().colorTable:
  153. vals = []
  154. vals.append(self.mainPanel.FindWindowById(id + 1000).GetValue())
  155. try:
  156. vals.append(self.mainPanel.FindWindowById(id + 1 + 1000).GetValue())
  157. except AttributeError:
  158. vals.append(None)
  159. value = self.SQLConvert(vals)
  160. else:
  161. value = self.mainPanel.FindWindowById(id + 1000).GetValue()
  162. color = self.mainPanel.FindWindowById(id + 2000).GetValue()
  163. if self.attributeType == 'color':
  164. # color
  165. color_str = str(color[0]) + ':' \
  166. + str(color[1]) + ':' \
  167. + str(color[2])
  168. self.ruleslines[id] = {'value' : value,
  169. 'color' : color_str }
  170. else:
  171. # size or width
  172. self.ruleslines[id] = {'value' : value,
  173. self.attributeType : float(color) }
  174. else:
  175. self.mainPanel.FindWindowById(id + 1000).Disable()
  176. self.mainPanel.FindWindowById(id + 2000).Disable()
  177. del self.ruleslines[id]
  178. def OnRuleColor(self, event):
  179. """Rule color changed"""
  180. num = event.GetId()
  181. rgba_color = event.GetValue()
  182. rgb_string = str(rgba_color[0]) + ':' \
  183. + str(rgba_color[1]) + ':' \
  184. + str(rgba_color[2])
  185. self.ruleslines[num-2000]['color'] = rgb_string
  186. def OnRuleSize(self, event):
  187. """Rule size changed"""
  188. num = event.GetId()
  189. size = event.GetInt()
  190. self.ruleslines[num - 2000][self.attributeType] = size
  191. def OnRuleValue(self, event):
  192. """Rule value changed"""
  193. num = event.GetId()
  194. val = event.GetString().strip()
  195. if val == '':
  196. return
  197. try:
  198. table = self.parent.colorTable
  199. except AttributeError:
  200. # due to panel/scrollpanel in vector dialog
  201. if isinstance(self.parent.GetParent(), RasterColorTable):
  202. table = self.parent.GetParent().colorTable
  203. else:
  204. table = self.parent.GetParent().GetParent().colorTable
  205. if table:
  206. self.SetRasterRule(num, val)
  207. else:
  208. self.SetVectorRule(num, val)
  209. def SetRasterRule(self, num, val):
  210. """Set raster rule"""
  211. self.ruleslines[num - 1000]['value'] = val
  212. def SetVectorRule(self, num, val):
  213. """Set vector rule"""
  214. vals = []
  215. vals.append(val)
  216. try:
  217. vals.append(self.mainPanel.FindWindowById(num + 1).GetValue())
  218. except AttributeError:
  219. vals.append(None)
  220. self.ruleslines[num - 1000]['value'] = self.SQLConvert(vals)
  221. def Enable(self, enable = True):
  222. """Enable/Disable all widgets"""
  223. for child in self.mainPanel.GetChildren():
  224. child.Enable(enable)
  225. sql = True
  226. self.LoadRulesline(sql)# todo
  227. self.btnAdd.Enable(enable)
  228. self.numRules.Enable(enable)
  229. self.checkAll.Enable(enable)
  230. self.clearAll.Enable(enable)
  231. def LoadRules(self):
  232. message = ""
  233. for item in range(len(self.ruleslines)):
  234. try:
  235. self.mainPanel.FindWindowById(item + 1000).SetValue(self.ruleslines[item]['value'])
  236. r, g, b = (0, 0, 0) # default
  237. if not self.ruleslines[item][self.attributeType]:
  238. if self.attributeType == 'color':
  239. self.ruleslines[item][self.attributeType] = '%d:%d:%d' % (r, g, b)
  240. elif self.attributeType == 'size':
  241. self.ruleslines[item][self.attributeType] = 100
  242. elif self.attributeType == 'width':
  243. self.ruleslines[item][self.attributeType] = 2
  244. if self.attributeType == 'color':
  245. try:
  246. r, g, b = map(int, self.ruleslines[item][self.attributeType].split(':'))
  247. except ValueError as e:
  248. message = _("Bad color format. Use color format '0:0:0'")
  249. self.mainPanel.FindWindowById(item + 2000).SetValue((r, g, b))
  250. else:
  251. value = float(self.ruleslines[item][self.attributeType])
  252. self.mainPanel.FindWindowById(item + 2000).SetValue(value)
  253. except:
  254. continue
  255. if message:
  256. GMessage(parent = self.parent, message = message)
  257. return False
  258. return True
  259. def SQLConvert(self, vals):
  260. """Prepare value for SQL query"""
  261. if vals[0].isdigit():
  262. sqlrule = '%s=%s' % (self.properties['sourceColumn'], vals[0])
  263. if vals[1]:
  264. sqlrule += ' AND %s<%s' % (self.properties['sourceColumn'], vals[1])
  265. else:
  266. sqlrule = '%s=%s' % (self.properties['sourceColumn'], vals[0])
  267. return sqlrule
  268. class ColorTable(wx.Frame):
  269. def __init__(self, parent, title, layerTree = None, id = wx.ID_ANY,
  270. style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
  271. **kwargs):
  272. """Dialog for interactively entering rules for map management
  273. commands
  274. :param raster: True to raster otherwise vector
  275. :param nviz: True if ColorTable is called from nviz thematic mapping
  276. """
  277. self.parent = parent # GMFrame ?
  278. self.layerTree = layerTree # LayerTree or None
  279. wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
  280. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  281. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  282. # instance of render.Map to be associated with display
  283. self.Map = Map()
  284. # input map to change
  285. self.inmap = ''
  286. # reference to layer with preview
  287. self.layer = None
  288. # layout
  289. self._doLayout()
  290. # bindings
  291. self.Bind(wx.EVT_BUTTON, self.OnHelp, self.btnHelp)
  292. self.selectionInput.Bind(wx.EVT_TEXT, self.OnSelectionInput)
  293. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  294. self.Bind(wx.EVT_BUTTON, self.OnApply, self.btnApply)
  295. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  296. self.Bind(wx.EVT_BUTTON, self.OnLoadDefaultTable, self.btnDefault)
  297. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  298. self.Bind(wx.EVT_BUTTON, self.OnPreview, self.btnPreview)
  299. def _initLayer(self):
  300. """Set initial layer when opening dialog"""
  301. # set map layer from layer tree, first selected,
  302. # if not the right type, than select another
  303. try:
  304. sel = self.layerTree.layer_selected
  305. if sel and self.layerTree.GetLayerInfo(sel, key = 'type') == self.mapType:
  306. layer = sel
  307. else:
  308. layer = self.layerTree.FindItemByData(key = 'type', value = self.mapType)
  309. except:
  310. layer = None
  311. if layer:
  312. mapLayer = self.layerTree.GetLayerInfo(layer, key = 'maplayer')
  313. name = mapLayer.GetName()
  314. type = mapLayer.GetType()
  315. self.selectionInput.SetValue(name)
  316. self.inmap = name
  317. def _createMapSelection(self, parent):
  318. """Create map selection part of dialog"""
  319. # top controls
  320. if self.mapType == 'raster':
  321. maplabel = _('Select raster map:')
  322. else:
  323. maplabel = _('Select vector map:')
  324. inputBox = wx.StaticBox(parent, id = wx.ID_ANY,
  325. label = " %s " % maplabel)
  326. inputSizer = wx.StaticBoxSizer(inputBox, wx.VERTICAL)
  327. self.selectionInput = Select(parent = parent, id = wx.ID_ANY,
  328. size = globalvar.DIALOG_GSELECT_SIZE,
  329. type = self.mapType)
  330. # layout
  331. inputSizer.Add(item = self.selectionInput,
  332. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border = 5)
  333. return inputSizer
  334. def _createFileSelection(self, parent):
  335. """Create file (open/save rules) selection part of dialog"""
  336. inputBox = wx.StaticBox(parent, id = wx.ID_ANY,
  337. label = " %s " % _("Import or export color table:"))
  338. inputSizer = wx.StaticBoxSizer(inputBox, wx.HORIZONTAL)
  339. self.loadRules = filebrowse.FileBrowseButton(parent = parent, id = wx.ID_ANY, fileMask = '*',
  340. labelText = '',
  341. dialogTitle = _('Choose file to load color table'),
  342. buttonText = _('Load'),
  343. toolTip = _("Type filename or click to choose "
  344. "file and load color table"),
  345. startDirectory = os.getcwd(), fileMode = wx.FD_OPEN,
  346. changeCallback = self.OnLoadRulesFile)
  347. self.saveRules = filebrowse.FileBrowseButton(parent = parent, id = wx.ID_ANY, fileMask = '*',
  348. labelText = '',
  349. dialogTitle = _('Choose file to save color table'),
  350. toolTip = _("Type filename or click to choose "
  351. "file and save color table"),
  352. buttonText = _('Save'),
  353. startDirectory = os.getcwd(), fileMode = wx.FD_SAVE,
  354. changeCallback = self.OnSaveRulesFile)
  355. colorTable = ColorTablesComboBox(parent = parent, size=globalvar.DIALOG_COMBOBOX_SIZE,
  356. choices = utils.GetColorTables(), name="colorTableChoice")
  357. self.btnSet = wx.Button(parent = parent, id = wx.ID_ANY, label = _("&Set"), name = 'btnSet')
  358. self.btnSet.Bind(wx.EVT_BUTTON, self.OnSetTable)
  359. self.btnSet.Enable(False)
  360. # layout
  361. gridSizer = wx.GridBagSizer(hgap = 2, vgap = 2)
  362. gridSizer.Add(item = wx.StaticText(parent, label = _("Load color table:")),
  363. pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  364. gridSizer.Add(item = colorTable, pos = (0, 1))
  365. gridSizer.Add(item = self.btnSet, pos = (0, 2), flag = wx.ALIGN_RIGHT)
  366. gridSizer.Add(item = wx.StaticText(parent, label = _('Load color table from file:')),
  367. pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  368. gridSizer.Add(item = self.loadRules, pos = (1, 1), span = (1, 2), flag = wx.EXPAND)
  369. gridSizer.Add(item = wx.StaticText(parent, label = _('Save color table to file:')),
  370. pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  371. gridSizer.Add(item = self.saveRules, pos = (2, 1), span = (1, 2), flag = wx.EXPAND)
  372. gridSizer.AddGrowableCol(1)
  373. inputSizer.Add(gridSizer, proportion = 1, flag = wx.EXPAND | wx.ALL,
  374. border = 5)
  375. if self.mapType == 'vector':
  376. # parent is collapsible pane
  377. parent.SetSizer(inputSizer)
  378. return inputSizer
  379. def _createPreview(self, parent):
  380. """Create preview"""
  381. # initialize preview display
  382. self.InitDisplay()
  383. self.preview = BufferedWindow(parent, id = wx.ID_ANY, size = (400, 300),
  384. Map = self.Map)
  385. self.preview.EraseMap()
  386. def _createButtons(self, parent):
  387. """Create buttons for leaving dialog"""
  388. self.btnHelp = wx.Button(parent, id = wx.ID_HELP)
  389. self.btnCancel = wx.Button(parent, id = wx.ID_CANCEL)
  390. self.btnApply = wx.Button(parent, id = wx.ID_APPLY)
  391. self.btnOK = wx.Button(parent, id = wx.ID_OK)
  392. self.btnDefault = wx.Button(parent, id = wx.ID_ANY,
  393. label = _("Reload default table"))
  394. self.btnOK.SetDefault()
  395. self.btnOK.Enable(False)
  396. self.btnApply.Enable(False)
  397. self.btnDefault.Enable(False)
  398. # layout
  399. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  400. btnSizer.Add(wx.Size(-1, -1), proportion = 1)
  401. btnSizer.Add(self.btnDefault,
  402. flag = wx.LEFT | wx.RIGHT, border = 5)
  403. btnSizer.Add(self.btnHelp,
  404. flag = wx.LEFT | wx.RIGHT, border = 5)
  405. btnSizer.Add(self.btnCancel,
  406. flag = wx.LEFT | wx.RIGHT, border = 5)
  407. btnSizer.Add(self.btnApply,
  408. flag = wx.LEFT | wx.RIGHT, border = 5)
  409. btnSizer.Add(self.btnOK,
  410. flag = wx.LEFT | wx.RIGHT, border = 5)
  411. return btnSizer
  412. def _createBody(self, parent):
  413. """Create dialog body consisting of rules and preview"""
  414. bodySizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  415. row = 0
  416. # label with range
  417. self.cr_label = wx.StaticText(parent, id = wx.ID_ANY)
  418. bodySizer.Add(item = self.cr_label, pos = (row, 0), span = (1, 3),
  419. flag = wx.ALL, border = 5)
  420. row += 1
  421. # color table
  422. self.rulesPanel = RulesPanel(parent = parent, mapType = self.mapType,
  423. attributeType = self.attributeType, properties = self.properties)
  424. bodySizer.Add(item = self.rulesPanel.mainPanel, pos = (row, 0),
  425. span = (1, 2), flag = wx.EXPAND)
  426. # add two rules as default
  427. self.rulesPanel.AddRules(2)
  428. # preview window
  429. self._createPreview(parent = parent)
  430. bodySizer.Add(item = self.preview, pos = (row, 2),
  431. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER)
  432. row += 1
  433. # add ckeck all and clear all
  434. bodySizer.Add(item = self.rulesPanel.checkAll, flag = wx.ALIGN_CENTER_VERTICAL,
  435. pos = (row, 0))
  436. bodySizer.Add(item = self.rulesPanel.clearAll, pos = (row, 1))
  437. # preview button
  438. self.btnPreview = wx.Button(parent, id = wx.ID_ANY,
  439. label = _("Preview"))
  440. bodySizer.Add(item = self.btnPreview, pos = (row, 2),
  441. flag = wx.ALIGN_RIGHT)
  442. self.btnPreview.Enable(False)
  443. self.btnPreview.SetToolTipString(_("Show preview of map "
  444. "(current Map Display extent is used)."))
  445. row +=1
  446. # add rules button and spin to sizer
  447. bodySizer.Add(item = self.rulesPanel.numRules, pos = (row, 0),
  448. flag = wx.ALIGN_CENTER_VERTICAL)
  449. bodySizer.Add(item = self.rulesPanel.btnAdd, pos = (row, 1))
  450. bodySizer.AddGrowableRow(1)
  451. bodySizer.AddGrowableCol(2)
  452. return bodySizer
  453. def InitDisplay(self):
  454. """Initialize preview display, set dimensions and region
  455. """
  456. self.width = self.Map.width = 400
  457. self.height = self.Map.height = 300
  458. self.Map.geom = self.width, self.height
  459. def OnCloseWindow(self, event):
  460. """Window closed
  461. """
  462. self.OnCancel(event)
  463. def OnApply(self, event):
  464. """Apply selected color table
  465. :return: True on success otherwise False
  466. """
  467. ret = self.CreateColorTable()
  468. if not ret:
  469. GMessage(parent = self, message = _("No valid color rules given."))
  470. else:
  471. # re-render preview and current map window
  472. self.OnPreview(None)
  473. display = self.layerTree.GetMapDisplay()
  474. if display and display.IsAutoRendered():
  475. display.GetWindow().UpdateMap(render = True)
  476. return ret
  477. def OnOK(self, event):
  478. """Apply selected color table and close the dialog"""
  479. if self.OnApply(event):
  480. self.OnCancel(event)
  481. def OnCancel(self, event):
  482. """Do not apply any changes, remove associated
  483. rendered images and close the dialog"""
  484. self.Map.Clean()
  485. self.Destroy()
  486. def OnSetTable(self, event):
  487. """Load pre-defined color table"""
  488. ct = self.FindWindowByName("colorTableChoice").GetValue()
  489. # save original color table
  490. ctOriginal = RunCommand('r.colors.out', read = True, map = self.inmap, rules = '-')
  491. # set new color table
  492. ret, err = RunCommand('r.colors', map = self.inmap, color = ct, getErrorMsg = True)
  493. if ret != 0:
  494. GError(err, parent = self)
  495. return
  496. ctNew = RunCommand('r.colors.out', read = True, map = self.inmap, rules = '-')
  497. # restore original table
  498. RunCommand('r.colors', map = self.inmap, rules = '-', stdin = ctOriginal)
  499. # load color table
  500. self.rulesPanel.Clear()
  501. self.ReadColorTable(ctable = ctNew)
  502. def OnSaveRulesFile(self, event):
  503. """Save color table to file"""
  504. path = event.GetString()
  505. if not path:
  506. return
  507. if os.path.exists(path):
  508. dlgOw = wx.MessageDialog(parent,
  509. message = _("File <%s> already already exists. "
  510. "Do you want to overwrite it?") % path,
  511. caption = _("Overwrite?"),
  512. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  513. if dlgOw.ShowModal() != wx.ID_YES:
  514. return
  515. rulestxt = ''
  516. for rule in self.rulesPanel.ruleslines.itervalues():
  517. if 'value' not in rule:
  518. continue
  519. rulestxt += rule['value'] + ' ' + rule['color'] + '\n'
  520. if not rulestxt:
  521. GMessage(message = _("Nothing to save."),
  522. parent = self)
  523. return
  524. fd = open(path, 'w')
  525. fd.write(rulestxt)
  526. fd.close()
  527. def OnLoadRulesFile(self, event):
  528. """Load color table from file"""
  529. path = event.GetString()
  530. if not os.path.exists(path):
  531. return
  532. self.rulesPanel.Clear()
  533. fd = open(path, 'r')
  534. self.ReadColorTable(ctable = fd.read())
  535. fd.close()
  536. def ReadColorTable(self, ctable):
  537. """Read color table
  538. :param table: color table in format coming from r.colors.out"""
  539. rulesNumber = len(ctable.splitlines())
  540. self.rulesPanel.AddRules(rulesNumber)
  541. minim = maxim = count = 0
  542. for line in ctable.splitlines():
  543. try:
  544. value, color = map(lambda x: x.strip(), line.split(' '))
  545. except ValueError:
  546. GMessage(parent = self, message = _("Invalid color table format"))
  547. self.rulesPanel.Clear()
  548. return
  549. self.rulesPanel.ruleslines[count]['value'] = value
  550. self.rulesPanel.ruleslines[count]['color'] = color
  551. self.rulesPanel.mainPanel.FindWindowById(count + 1000).SetValue(value)
  552. rgb = list()
  553. for c in color.split(':'):
  554. rgb.append(int(c))
  555. self.rulesPanel.mainPanel.FindWindowById(count + 2000).SetColour(rgb)
  556. # range
  557. try:
  558. if float(value) < minim:
  559. minim = float(value)
  560. if float(value) > maxim:
  561. maxim = float(value)
  562. except ValueError: # nv, default
  563. pass
  564. count += 1
  565. if self.mapType == 'vector':
  566. # raster min, max is known from r.info
  567. self.properties['min'], self.properties['max'] = minim, maxim
  568. self.SetRangeLabel()
  569. self.OnPreview(tmp = True)
  570. def OnLoadDefaultTable(self, event):
  571. """Load internal color table"""
  572. self.LoadTable()
  573. def LoadTable(self, mapType = 'raster'):
  574. """Load current color table (using `r(v).colors.out`)
  575. :param mapType: map type (raster or vector)"""
  576. self.rulesPanel.Clear()
  577. if mapType == 'raster':
  578. cmd = ['r.colors.out',
  579. 'read=True',
  580. 'map=%s' % self.inmap,
  581. 'rules=-']
  582. else:
  583. cmd = ['v.colors.out',
  584. 'read=True',
  585. 'map=%s' % self.inmap,
  586. 'rules=-']
  587. if self.properties['sourceColumn'] and self.properties['sourceColumn'] != 'cat':
  588. cmd.append('column=%s' % self.properties['sourceColumn'])
  589. cmd = cmdlist_to_tuple(cmd)
  590. if self.inmap:
  591. ctable = RunCommand(cmd[0], **cmd[1])
  592. else:
  593. self.OnPreview()
  594. return
  595. self.ReadColorTable(ctable = ctable)
  596. def CreateColorTable(self, tmp = False):
  597. """Creates color table
  598. :return: True on success
  599. :return: False on failure
  600. """
  601. rulestxt = ''
  602. for rule in self.rulesPanel.ruleslines.itervalues():
  603. if 'value' not in rule: # skip empty rules
  604. continue
  605. if rule['value'] not in ('nv', 'default') and \
  606. rule['value'][-1] != '%' and \
  607. not self._IsNumber(rule['value']):
  608. GError(_("Invalid rule value '%s'. Unable to apply color table.") % rule['value'],
  609. parent = self)
  610. return False
  611. rulestxt += rule['value'] + ' ' + rule['color'] + '\n'
  612. if not rulestxt:
  613. return False
  614. gtemp = utils.GetTempfile()
  615. output = open(gtemp, "w")
  616. try:
  617. output.write(rulestxt)
  618. finally:
  619. output.close()
  620. cmd = ['%s.colors' % self.mapType[0], #r.colors/v.colors
  621. 'map=%s' % self.inmap,
  622. 'rules=%s' % gtemp]
  623. if self.mapType == 'vector' and self.properties['sourceColumn'] \
  624. and self.properties['sourceColumn'] != 'cat':
  625. cmd.append('column=%s' % self.properties['sourceColumn'])
  626. cmd = cmdlist_to_tuple(cmd)
  627. ret = RunCommand(cmd[0], **cmd[1])
  628. if ret != 0:
  629. return False
  630. return True
  631. def DoPreview(self, ltype, cmdlist):
  632. """Update preview (based on computational region)"""
  633. if not self.layer:
  634. self.layer = self.Map.AddLayer(ltype = ltype, name = 'preview', command = cmdlist,
  635. active = True, hidden = False, opacity = 1.0,
  636. render = False)
  637. else:
  638. self.layer.SetCmd(cmdlist)
  639. # apply new color table and display preview
  640. self.CreateColorTable(tmp = True)
  641. self.preview.UpdatePreview()
  642. def RunHelp(self, cmd):
  643. """Show GRASS manual page"""
  644. RunCommand('g.manual',
  645. quiet = True,
  646. parent = self,
  647. entry = cmd)
  648. def SetMap(self, name):
  649. """Set map name and update dialog"""
  650. self.selectionInput.SetValue(name)
  651. def _IsNumber(self, s):
  652. """Check if 's' is a number"""
  653. try:
  654. float(s)
  655. return True
  656. except ValueError:
  657. return False
  658. class RasterColorTable(ColorTable):
  659. def __init__(self, parent, **kwargs):
  660. """Dialog for interactively entering color rules for raster maps"""
  661. self.mapType = 'raster'
  662. self.attributeType = 'color'
  663. self.colorTable = True
  664. # raster properties
  665. self.properties = {
  666. # min cat in raster map
  667. 'min' : None,
  668. # max cat in raster map
  669. 'max' : None,
  670. }
  671. ColorTable.__init__(self, parent,
  672. title = _('Create new color table for raster map'), **kwargs)
  673. self._initLayer()
  674. self.Map.GetRenderMgr().renderDone.connect(self._restoreColorTable)
  675. # self.SetMinSize(self.GetSize())
  676. self.SetMinSize((650, 700))
  677. def _doLayout(self):
  678. """Do main layout"""
  679. sizer = wx.BoxSizer(wx.VERTICAL)
  680. #
  681. # map selection
  682. #
  683. mapSelection = self._createMapSelection(parent = self.panel)
  684. sizer.Add(item = mapSelection, proportion = 0,
  685. flag = wx.ALL | wx.EXPAND, border = 5)
  686. #
  687. # manage extern tables
  688. #
  689. fileSelection = self._createFileSelection(parent = self.panel)
  690. sizer.Add(item = fileSelection, proportion = 0,
  691. flag = wx.LEFT | wx.RIGHT | wx.EXPAND, border = 5)
  692. #
  693. # body & preview
  694. #
  695. bodySizer = self._createBody(parent = self.panel)
  696. sizer.Add(item = bodySizer, proportion = 1,
  697. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  698. #
  699. # buttons
  700. #
  701. btnSizer = self._createButtons(parent = self.panel)
  702. sizer.Add(item = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
  703. style = wx.LI_HORIZONTAL), proportion = 0,
  704. flag = wx.EXPAND | wx.ALL, border = 5)
  705. sizer.Add(item = btnSizer, proportion = 0,
  706. flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
  707. self.panel.SetSizer(sizer)
  708. sizer.Layout()
  709. sizer.Fit(self.panel)
  710. self.Layout()
  711. def OnSelectionInput(self, event):
  712. """Raster map selected"""
  713. if event:
  714. self.inmap = event.GetString()
  715. self.loadRules.SetValue('')
  716. self.saveRules.SetValue('')
  717. if self.inmap:
  718. if not grass.find_file(name = self.inmap, element = 'cell')['file']:
  719. self.inmap = None
  720. if not self.inmap:
  721. for btn in (self.btnPreview, self.btnOK,
  722. self.btnApply, self.btnDefault, self.btnSet):
  723. btn.Enable(False)
  724. self.LoadTable()
  725. return
  726. info = grass.raster_info(map = self.inmap)
  727. if info:
  728. self.properties['min'] = info['min']
  729. self.properties['max'] = info['max']
  730. self.LoadTable()
  731. else:
  732. self.inmap = ''
  733. self.properties['min'] = self.properties['max'] = None
  734. for btn in (self.btnPreview, self.btnOK,
  735. self.btnApply, self.btnDefault, self.btnSet):
  736. btn.Enable(False)
  737. self.preview.EraseMap()
  738. self.cr_label.SetLabel(_('Enter raster category values or percents'))
  739. return
  740. if info['datatype'] == 'CELL':
  741. mapRange = _('range')
  742. else:
  743. mapRange = _('fp range')
  744. self.cr_label.SetLabel(_('Enter raster category values or percents (%(range)s = %(min)d-%(max)d)') %
  745. { 'range' : mapRange,
  746. 'min' : self.properties['min'],
  747. 'max' : self.properties['max'] })
  748. for btn in (self.btnPreview, self.btnOK,
  749. self.btnApply, self.btnDefault, self.btnSet):
  750. btn.Enable()
  751. def OnPreview(self, tmp = True):
  752. """Update preview (based on computational region)"""
  753. if not self.inmap:
  754. self.preview.EraseMap()
  755. return
  756. cmdlist = ['d.rast',
  757. 'map=%s' % self.inmap]
  758. ltype = 'raster'
  759. # find existing color table and copy to temp file
  760. try:
  761. name, mapset = self.inmap.split('@')
  762. except ValueError:
  763. name = self.inmap
  764. mapset = grass.find_file(self.inmap, element = 'cell')['mapset']
  765. if not mapset:
  766. return
  767. self._tmp = tmp
  768. self._old_colrtable = None
  769. if mapset == grass.gisenv()['MAPSET']:
  770. self._old_colrtable = grass.find_file(name = name, element = 'colr')['file']
  771. else:
  772. self._old_colrtable = grass.find_file(name = name, element = 'colr2/' + mapset)['file']
  773. if self._old_colrtable:
  774. self._colrtemp = utils.GetTempfile()
  775. shutil.copyfile(self._old_colrtable, self._colrtemp)
  776. ColorTable.DoPreview(self, ltype, cmdlist)
  777. def _restoreColorTable(self):
  778. # restore previous color table
  779. if self._tmp:
  780. if self._old_colrtable:
  781. shutil.copyfile(self._colrtemp, self._old_colrtable)
  782. os.remove(self._colrtemp)
  783. del self._colrtemp, self._old_colrtable
  784. else:
  785. RunCommand('r.colors',
  786. parent = self,
  787. flags = 'r',
  788. map = self.inmap)
  789. del self._tmp
  790. def OnHelp(self, event):
  791. """Show GRASS manual page"""
  792. cmd = 'r.colors'
  793. ColorTable.RunHelp(self, cmd = cmd)
  794. class VectorColorTable(ColorTable):
  795. def __init__(self, parent, attributeType, **kwargs):
  796. """Dialog for interactively entering color rules for vector maps"""
  797. # dialog attributes
  798. self.mapType = 'vector'
  799. self.attributeType = attributeType # color, size, width
  800. # in version 7 v.colors used, otherwise color column only
  801. self.version7 = int(grass.version()['version'].split('.')[0]) >= 7
  802. self.colorTable = False
  803. self.updateColumn = True
  804. # vector properties
  805. self.properties = {
  806. # vector layer for attribute table to use for setting color
  807. 'layer' : 1,
  808. # vector attribute table used for setting color
  809. 'table' : '',
  810. # vector attribute column for assigning colors
  811. 'sourceColumn' : '',
  812. # vector attribute column to use for loading colors
  813. 'loadColumn' : '',
  814. # vector attribute column to use for storing colors
  815. 'storeColumn' : '',
  816. # vector attribute column for temporary storing colors
  817. 'tmpColumn' : 'tmp_0',
  818. # min value of attribute column/vector color table
  819. 'min': None,
  820. # max value of attribute column/vector color table
  821. 'max': None
  822. }
  823. self.columnsProp = {'color': {'name': 'GRASSRGB', 'type1': 'varchar(11)', 'type2': ['character']},
  824. 'size' : {'name': 'GRASSSIZE', 'type1': 'integer', 'type2': ['integer']},
  825. 'width': {'name': 'GRASSWIDTH', 'type1': 'integer', 'type2': ['integer']}}
  826. ColorTable.__init__(self, parent = parent,
  827. title = _('Create new color rules for vector map'), **kwargs)
  828. # additional bindings for vector color management
  829. self.Bind(wx.EVT_COMBOBOX, self.OnLayerSelection, self.layerSelect)
  830. self.sourceColumn.Bind(wx.EVT_TEXT, self.OnSourceColumnSelection)
  831. self.fromColumn.Bind(wx.EVT_TEXT, self.OnFromColSelection)
  832. self.toColumn.Bind(wx.EVT_TEXT, self.OnToColSelection)
  833. self.Bind(wx.EVT_BUTTON, self.OnAddColumn, self.addColumn)
  834. self._initLayer()
  835. if self.colorTable:
  836. self.cr_label.SetLabel(_("Enter vector attribute values or percents:"))
  837. else:
  838. self.cr_label.SetLabel(_("Enter vector attribute values:"))
  839. #self.SetMinSize(self.GetSize())
  840. self.SetMinSize((650, 700))
  841. self.CentreOnScreen()
  842. self.Show()
  843. def _createVectorAttrb(self, parent):
  844. """Create part of dialog with layer/column selection"""
  845. inputBox = wx.StaticBox(parent = parent, id = wx.ID_ANY,
  846. label = " %s " % _("Select vector columns"))
  847. cb_vl_label = wx.StaticText(parent, id = wx.ID_ANY,
  848. label = _('Layer:'))
  849. cb_vc_label = wx.StaticText(parent, id = wx.ID_ANY,
  850. label = _('Attribute column:'))
  851. if self.attributeType == 'color':
  852. labels = [_("Load color from column:"), _("Save color to column:")]
  853. elif self.attributeType == 'size':
  854. labels = [_("Load size from column:"), _("Save size to column:")]
  855. elif self.attributeType == 'width':
  856. labels = [_("Load width from column:"), _("Save width to column:")]
  857. if self.version7 and self.attributeType == 'color':
  858. self.useColumn = wx.CheckBox(parent, id = wx.ID_ANY,
  859. label = _("Use color column instead of color table:"))
  860. self.useColumn.Bind(wx.EVT_CHECKBOX, self.OnCheckColumn)
  861. fromColumnLabel = wx.StaticText(parent, id = wx.ID_ANY,
  862. label = labels[0])
  863. toColumnLabel = wx.StaticText(parent, id = wx.ID_ANY,
  864. label = labels[1])
  865. self.rgb_range_label = wx.StaticText(parent, id = wx.ID_ANY)
  866. self.layerSelect = LayerSelect(parent)
  867. self.sourceColumn = ColumnSelect(parent)
  868. self.fromColumn = ColumnSelect(parent)
  869. self.toColumn = ColumnSelect(parent)
  870. self.addColumn = wx.Button(parent, id = wx.ID_ANY,
  871. label = _('Add column'))
  872. self.addColumn.SetToolTipString(_("Add GRASSRGB column to current attribute table."))
  873. # layout
  874. inputSizer = wx.StaticBoxSizer(inputBox, wx.VERTICAL)
  875. vSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  876. row = 0
  877. vSizer.Add(cb_vl_label, pos = (row, 0),
  878. flag = wx.ALIGN_CENTER_VERTICAL)
  879. vSizer.Add(self.layerSelect, pos = (row, 1),
  880. flag = wx.ALIGN_CENTER_VERTICAL)
  881. row += 1
  882. vSizer.Add(cb_vc_label, pos = (row, 0),
  883. flag = wx.ALIGN_CENTER_VERTICAL)
  884. vSizer.Add(self.sourceColumn, pos = (row, 1),
  885. flag = wx.ALIGN_CENTER_VERTICAL)
  886. vSizer.Add(self.rgb_range_label, pos = (row, 2),
  887. flag = wx.ALIGN_CENTER_VERTICAL)
  888. row += 1
  889. if self.version7 and self.attributeType == 'color':
  890. vSizer.Add(self.useColumn, pos = (row, 0), span = (1, 2),
  891. flag = wx.ALIGN_CENTER_VERTICAL)
  892. row += 1
  893. vSizer.Add(fromColumnLabel, pos = (row, 0),
  894. flag = wx.ALIGN_CENTER_VERTICAL)
  895. vSizer.Add(self.fromColumn, pos = (row, 1),
  896. flag = wx.ALIGN_CENTER_VERTICAL)
  897. row += 1
  898. vSizer.Add(toColumnLabel, pos = (row, 0),
  899. flag = wx.ALIGN_CENTER_VERTICAL)
  900. vSizer.Add(self.toColumn, pos = (row, 1),
  901. flag = wx.ALIGN_CENTER_VERTICAL)
  902. vSizer.Add(self.addColumn, pos = (row, 2),
  903. flag = wx.ALIGN_CENTER_VERTICAL)
  904. inputSizer.Add(item = vSizer,
  905. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border = 5)
  906. self.colorColumnSizer = vSizer
  907. return inputSizer
  908. def _doLayout(self):
  909. """Do main layout"""
  910. scrollPanel = scrolled.ScrolledPanel(parent = self.panel, id = wx.ID_ANY,
  911. style = wx.TAB_TRAVERSAL)
  912. scrollPanel.SetupScrolling()
  913. sizer = wx.BoxSizer(wx.VERTICAL)
  914. #
  915. # map selection
  916. #
  917. mapSelection = self._createMapSelection(parent = scrollPanel)
  918. sizer.Add(item = mapSelection, proportion = 0,
  919. flag = wx.ALL | wx.EXPAND, border = 5)
  920. #
  921. # manage extern tables
  922. #
  923. if self.version7 and self.attributeType == 'color':
  924. self.cp = wx.CollapsiblePane(scrollPanel, label = _("Import or export color table"),
  925. winid = wx.ID_ANY,
  926. style = wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)
  927. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged, self.cp)
  928. self._createFileSelection(parent = self.cp.GetPane())
  929. sizer.Add(item = self.cp, proportion = 0,
  930. flag = wx.ALL | wx.EXPAND, border = 5)
  931. #
  932. # set vector attributes
  933. #
  934. vectorAttrb = self._createVectorAttrb(parent = scrollPanel)
  935. sizer.Add(item = vectorAttrb, proportion = 0,
  936. flag = wx.ALL | wx.EXPAND, border = 5)
  937. #
  938. # body & preview
  939. #
  940. bodySizer = self._createBody(parent = scrollPanel)
  941. sizer.Add(item = bodySizer, proportion = 1,
  942. flag = wx.ALL | wx.EXPAND, border = 5)
  943. scrollPanel.SetSizer(sizer)
  944. scrollPanel.Fit()
  945. #
  946. # buttons
  947. #
  948. btnSizer = self._createButtons(self.panel)
  949. mainsizer = wx.BoxSizer(wx.VERTICAL)
  950. mainsizer.Add(scrollPanel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  951. mainsizer.Add(item = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
  952. style = wx.LI_HORIZONTAL), proportion = 0,
  953. flag = wx.EXPAND | wx.ALL, border = 5)
  954. mainsizer.Add(item = btnSizer, proportion = 0,
  955. flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
  956. self.panel.SetSizer(mainsizer)
  957. mainsizer.Layout()
  958. mainsizer.Fit(self.panel)
  959. self.Layout()
  960. def OnPaneChanged(self, event = None):
  961. # redo the layout
  962. self.Layout()
  963. # and also change the labels
  964. if self.cp.IsExpanded():
  965. self.cp.SetLabel('')
  966. else:
  967. self.cp.SetLabel(_("Import or export color table"))
  968. def CheckMapset(self):
  969. """Check if current vector is in current mapset"""
  970. if grass.find_file(name = self.inmap,
  971. element = 'vector')['mapset'] == grass.gisenv()['MAPSET']:
  972. return True
  973. else:
  974. return False
  975. def NoConnection(self, vectorName):
  976. dlg = wx.MessageDialog(parent = self,
  977. message = _("Database connection for vector map <%s> "
  978. "is not defined in DB file. Do you want to create and "
  979. "connect new attribute table?") % vectorName,
  980. caption = _("No database connection defined"),
  981. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  982. if dlg.ShowModal() == wx.ID_YES:
  983. dlg.Destroy()
  984. GUI(parent = self).ParseCommand(['v.db.addtable', 'map=' + self.inmap],
  985. completed = (self.CreateAttrTable, self.inmap, ''))
  986. else:
  987. dlg.Destroy()
  988. def OnCheckColumn(self, event):
  989. """Use color column instead of color table"""
  990. if self.useColumn.GetValue():
  991. self.properties['loadColumn'] = self.fromColumn.GetValue()
  992. self.properties['storeColumn'] = self.toColumn.GetValue()
  993. self.fromColumn.Enable(True)
  994. self.toColumn.Enable(True)
  995. self.colorTable = False
  996. if self.properties['loadColumn']:
  997. self.LoadTable()
  998. else:
  999. self.rulesPanel.Clear()
  1000. else:
  1001. self.properties['loadColumn'] = ''
  1002. self.properties['storeColumn'] = ''
  1003. self.fromColumn.Enable(False)
  1004. self.toColumn.Enable(False)
  1005. self.colorTable = True
  1006. self.LoadTable()
  1007. def EnableVectorAttributes(self, enable):
  1008. """Enable/disable part of dialog connected with db"""
  1009. for child in self.colorColumnSizer.GetChildren():
  1010. child.GetWindow().Enable(enable)
  1011. def DisableClearAll(self):
  1012. """Enable, disable the whole dialog"""
  1013. self.rulesPanel.Clear()
  1014. self.EnableVectorAttributes(False)
  1015. self.btnPreview.Enable(False)
  1016. self.btnOK.Enable(False)
  1017. self.btnApply.Enable(False)
  1018. self.preview.EraseMap()
  1019. def OnSelectionInput(self, event):
  1020. """Vector map selected"""
  1021. if event:
  1022. if self.inmap:
  1023. # switch to another map -> delete temporary column
  1024. self.DeleteTemporaryColumn()
  1025. self.inmap = event.GetString()
  1026. if self.version7 and self.attributeType == 'color':
  1027. self.loadRules.SetValue('')
  1028. self.saveRules.SetValue('')
  1029. if self.inmap:
  1030. if not grass.find_file(name = self.inmap, element = 'vector')['file']:
  1031. self.inmap = None
  1032. self.UpdateDialog()
  1033. def UpdateDialog(self):
  1034. """Update dialog after map selection"""
  1035. if not self.inmap:
  1036. self.DisableClearAll()
  1037. return
  1038. if not self.CheckMapset():
  1039. # v.colors doesn't need the map to be in current mapset
  1040. if not (self.version7 and self.attributeType == 'color'):
  1041. message = _("Selected map <%(map)s> is not in current mapset <%(mapset)s>. "
  1042. "Attribute table cannot be edited.") % \
  1043. { 'map' : self.inmap,
  1044. 'mapset' : grass.gisenv()['MAPSET'] }
  1045. wx.CallAfter(GMessage, parent = self, message = message)
  1046. self.DisableClearAll()
  1047. return
  1048. # check for db connection
  1049. self.dbInfo = VectorDBInfo(self.inmap)
  1050. enable = True
  1051. if not len(self.dbInfo.layers): # no connection
  1052. if not (self.version7 and self.attributeType == 'color'): # otherwise it doesn't matter
  1053. wx.CallAfter(self.NoConnection, self.inmap)
  1054. enable = False
  1055. for combo in (self.layerSelect, self.sourceColumn, self.fromColumn, self.toColumn):
  1056. combo.SetValue("")
  1057. combo.Clear()
  1058. for prop in ('sourceColumn', 'loadColumn', 'storeColumn'):
  1059. self.properties[prop] = ''
  1060. self.EnableVectorAttributes(False)
  1061. else: # db connection exist
  1062. # initialize layer selection combobox
  1063. self.EnableVectorAttributes(True)
  1064. self.layerSelect.InsertLayers(self.inmap)
  1065. # initialize attribute table for layer=1
  1066. self.properties['layer'] = self.layerSelect.GetString(0)
  1067. self.layerSelect.SetStringSelection(self.properties['layer'])
  1068. layer = int(self.properties['layer'])
  1069. self.properties['table'] = self.dbInfo.layers[layer]['table']
  1070. if self.attributeType == 'color':
  1071. self.AddTemporaryColumn(type = 'varchar(11)')
  1072. else:
  1073. self.AddTemporaryColumn(type = 'integer')
  1074. # initialize column selection comboboxes
  1075. self.OnLayerSelection(event = None)
  1076. if self.version7 and self.attributeType == 'color':
  1077. self.useColumn.SetValue(False)
  1078. self.OnCheckColumn(event = None)
  1079. self.useColumn.Enable(self.CheckMapset())
  1080. self.LoadTable()
  1081. self.btnPreview.Enable(enable)
  1082. self.btnOK.Enable(enable)
  1083. self.btnApply.Enable(enable)
  1084. def AddTemporaryColumn(self, type):
  1085. """Add temporary column to not overwrite the original values,
  1086. need to be deleted when closing dialog and unloading map
  1087. :param type: type of column (e.g. vachar(11))"""
  1088. if not self.CheckMapset():
  1089. return
  1090. # because more than one dialog with the same map can be opened we must test column name and
  1091. # create another one
  1092. while self.properties['tmpColumn'] in self.dbInfo.GetTableDesc(self.properties['table']).keys():
  1093. name, idx = self.properties['tmpColumn'].split('_')
  1094. idx = int(idx)
  1095. idx += 1
  1096. self.properties['tmpColumn'] = name + '_' + str(idx)
  1097. if self.version7:
  1098. modul = 'v.db.addcolumn'
  1099. else:
  1100. modul = 'v.db.addcol'
  1101. ret = RunCommand(modul,
  1102. parent = self,
  1103. map = self.inmap,
  1104. layer = self.properties['layer'],
  1105. column = '%s %s' % (self.properties['tmpColumn'], type))
  1106. def DeleteTemporaryColumn(self):
  1107. """Delete temporary column"""
  1108. if not self.CheckMapset():
  1109. return
  1110. if self.inmap:
  1111. if self.version7:
  1112. modul = 'v.db.dropcolumn'
  1113. else:
  1114. modul = 'v.db.dropcol'
  1115. ret = RunCommand(modul,
  1116. map = self.inmap,
  1117. layer = self.properties['layer'],
  1118. column = self.properties['tmpColumn'])
  1119. def OnLayerSelection(self, event):
  1120. # reset choices in column selection comboboxes if layer changes
  1121. vlayer = int(self.layerSelect.GetStringSelection())
  1122. self.sourceColumn.InsertColumns(vector = self.inmap, layer = vlayer,
  1123. type = ['integer', 'double precision'], dbInfo = self.dbInfo,
  1124. excludeCols = ['tmpColumn'])
  1125. self.sourceColumn.SetValue('cat')
  1126. self.properties['sourceColumn'] = self.sourceColumn.GetValue()
  1127. if self.attributeType == 'color':
  1128. type = ['character']
  1129. else:
  1130. type = ['integer']
  1131. self.fromColumn.InsertColumns(vector = self.inmap, layer = vlayer, type = type,
  1132. dbInfo = self.dbInfo, excludeCols = ['tmpColumn'])
  1133. self.toColumn.InsertColumns(vector = self.inmap, layer = vlayer, type = type,
  1134. dbInfo = self.dbInfo, excludeCols = ['tmpColumn'])
  1135. v = self.columnsProp[self.attributeType]['name']
  1136. found = False
  1137. if v in self.fromColumn.GetColumns():
  1138. found = True
  1139. if found != wx.NOT_FOUND:
  1140. self.fromColumn.SetValue(v)
  1141. self.toColumn.SetValue(v)
  1142. self.properties['loadColumn'] = v
  1143. self.properties['storeColumn'] = v
  1144. else:
  1145. self.properties['loadColumn'] = ''
  1146. self.properties['storeColumn'] = ''
  1147. if event:
  1148. self.LoadTable()
  1149. self.Update()
  1150. def OnSourceColumnSelection(self, event):
  1151. self.properties['sourceColumn'] = event.GetString()
  1152. self.LoadTable()
  1153. def OnAddColumn(self, event):
  1154. """Add GRASS(RGB,SIZE,WIDTH) column if it doesn't exist"""
  1155. if self.columnsProp[self.attributeType]['name'] not in self.fromColumn.GetColumns():
  1156. if self.version7:
  1157. modul = 'v.db.addcolumn'
  1158. else:
  1159. modul = 'v.db.addcol'
  1160. ret = RunCommand(modul,
  1161. map = self.inmap,
  1162. layer = self.properties['layer'],
  1163. columns = '%s %s' % (self.columnsProp[self.attributeType]['name'],
  1164. self.columnsProp[self.attributeType]['type1']))
  1165. self.toColumn.InsertColumns(self.inmap, self.properties['layer'],
  1166. type = self.columnsProp[self.attributeType]['type2'])
  1167. self.toColumn.SetValue(self.columnsProp[self.attributeType]['name'])
  1168. self.properties['storeColumn'] = self.toColumn.GetValue()
  1169. self.LoadTable()
  1170. else:
  1171. GMessage(parent = self,
  1172. message = _("%s column already exists.") % \
  1173. self.columnsProp[self.attributeType]['name'])
  1174. def CreateAttrTable(self, dcmd, layer, params, propwin):
  1175. """Create attribute table"""
  1176. if dcmd:
  1177. cmd = cmdlist_to_tuple(dcmd)
  1178. ret = RunCommand(cmd[0], **cmd[1])
  1179. if ret == 0:
  1180. self.OnSelectionInput(None)
  1181. return True
  1182. for combo in (self.layerSelect, self.sourceColumn, self.fromColumn, self.toColumn):
  1183. combo.SetValue("")
  1184. combo.Disable()
  1185. return False
  1186. def LoadTable(self):
  1187. """Load table"""
  1188. if self.colorTable:
  1189. ColorTable.LoadTable(self, mapType = 'vector')
  1190. else:
  1191. self.LoadRulesFromColumn()
  1192. def LoadRulesFromColumn(self):
  1193. """Load current column (GRASSRGB, size column)"""
  1194. self.rulesPanel.Clear()
  1195. if not self.properties['sourceColumn']:
  1196. self.preview.EraseMap()
  1197. return
  1198. busy = wx.BusyInfo(message = _("Please wait, loading data from attribute table..."),
  1199. parent = self)
  1200. wx.Yield()
  1201. columns = self.properties['sourceColumn']
  1202. if self.properties['loadColumn']:
  1203. columns += ',' + self.properties['loadColumn']
  1204. sep = ';'
  1205. if self.inmap:
  1206. outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1207. ret = RunCommand('v.db.select',
  1208. quiet = True,
  1209. flags = 'c',
  1210. map = self.inmap,
  1211. layer = self.properties['layer'],
  1212. columns = columns,
  1213. sep = sep,
  1214. stdout = outFile)
  1215. else:
  1216. self.preview.EraseMap()
  1217. busy.Destroy()
  1218. return
  1219. outFile.seek(0)
  1220. i = 0
  1221. minim = maxim = 0.0
  1222. limit = 1000
  1223. colvallist = []
  1224. readvals = False
  1225. while True:
  1226. # os.linesep doesn't work here (MSYS)
  1227. record = outFile.readline().replace('\n', '')
  1228. if not record:
  1229. break
  1230. self.rulesPanel.ruleslines[i] = {}
  1231. if not self.properties['loadColumn']:
  1232. col1 = record
  1233. col2 = None
  1234. else:
  1235. col1, col2 = record.split(sep)
  1236. if float(col1) < minim:
  1237. minim = float(col1)
  1238. if float(col1) > maxim:
  1239. maxim = float(col1)
  1240. # color rules list should only have unique values of col1, not all records
  1241. if col1 not in colvallist:
  1242. self.rulesPanel.ruleslines[i]['value'] = col1
  1243. self.rulesPanel.ruleslines[i][self.attributeType] = col2
  1244. colvallist.append(col1)
  1245. i += 1
  1246. if i > limit and readvals == False:
  1247. dlg = wx.MessageDialog (parent = self, message = _(
  1248. "Number of loaded records reached %d, "
  1249. "displaying all the records will be time-consuming "
  1250. "and may lead to computer freezing, "
  1251. "do you still want to continue?") % i,
  1252. caption = _("Too many records"),
  1253. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  1254. if dlg.ShowModal() == wx.ID_YES:
  1255. readvals = True
  1256. dlg.Destroy()
  1257. else:
  1258. busy.Destroy()
  1259. dlg.Destroy()
  1260. self.updateColumn = False
  1261. return
  1262. self.rulesPanel.AddRules(i, start = True)
  1263. ret = self.rulesPanel.LoadRules()
  1264. self.properties['min'], self.properties['max'] = minim, maxim
  1265. self.SetRangeLabel()
  1266. if ret:
  1267. self.OnPreview()
  1268. else:
  1269. self.rulesPanel.Clear()
  1270. busy.Destroy()
  1271. def SetRangeLabel(self):
  1272. """Set labels with info about attribute column range"""
  1273. if self.properties['sourceColumn']:
  1274. ctype = self.dbInfo.GetTableDesc(self.properties['table'])[self.properties['sourceColumn']]['ctype']
  1275. else:
  1276. ctype = int
  1277. range = ''
  1278. if self.properties['min'] or self.properties['max']:
  1279. if ctype == float:
  1280. range = "%s: %.1f - %.1f)" % (_("range"),
  1281. self.properties['min'], self.properties['max'])
  1282. elif ctype == int:
  1283. range = "%s: %d - %d)" % (_("range"),
  1284. self.properties['min'], self.properties['max'])
  1285. if range:
  1286. if self.colorTable:
  1287. self.cr_label.SetLabel(_("Enter vector attribute values or percents %s:") % range)
  1288. else:
  1289. self.cr_label.SetLabel(_("Enter vector attribute values %s:") % range)
  1290. else:
  1291. if self.colorTable:
  1292. self.cr_label.SetLabel(_("Enter vector attribute values or percents:"))
  1293. else:
  1294. self.cr_label.SetLabel(_("Enter vector attribute values:"))
  1295. def OnFromColSelection(self, event):
  1296. """Selection in combobox (for loading values) changed"""
  1297. self.properties['loadColumn'] = event.GetString()
  1298. self.LoadTable()
  1299. def OnToColSelection(self, event):
  1300. """Selection in combobox (for storing values) changed"""
  1301. self.properties['storeColumn'] = event.GetString()
  1302. def OnPreview(self, event = None, tmp = True):
  1303. """Update preview (based on computational region)"""
  1304. if self.colorTable:
  1305. self.OnTablePreview(tmp)
  1306. else:
  1307. self.OnColumnPreview()
  1308. def OnTablePreview(self, tmp):
  1309. """Update preview (based on computational region)"""
  1310. if not self.inmap:
  1311. self.preview.EraseMap()
  1312. return
  1313. ltype = 'vector'
  1314. cmdlist = ['d.vect',
  1315. 'map=%s' % self.inmap]
  1316. # find existing color table and copy to temp file
  1317. try:
  1318. name, mapset = self.inmap.split('@')
  1319. except ValueError:
  1320. name = self.inmap
  1321. mapset = grass.find_file(self.inmap, element = 'cell')['mapset']
  1322. if not mapset:
  1323. return
  1324. old_colrtable = None
  1325. if mapset == grass.gisenv()['MAPSET']:
  1326. old_colrtable = grass.find_file(name = 'colr', element = os.path.join('vector', name))['file']
  1327. else:
  1328. old_colrtable = grass.find_file(name = name, element = os.path.join('vcolr2', mapset))['file']
  1329. if old_colrtable:
  1330. colrtemp = utils.GetTempfile()
  1331. shutil.copyfile(old_colrtable, colrtemp)
  1332. ColorTable.DoPreview(self, ltype, cmdlist)
  1333. # restore previous color table
  1334. if tmp:
  1335. if old_colrtable:
  1336. shutil.copyfile(colrtemp, old_colrtable)
  1337. os.remove(colrtemp)
  1338. else:
  1339. RunCommand('v.colors',
  1340. parent = self,
  1341. flags = 'r',
  1342. map = self.inmap)
  1343. def OnColumnPreview(self):
  1344. """Update preview (based on computational region)"""
  1345. if not self.inmap or not self.properties['tmpColumn']:
  1346. self.preview.EraseMap()
  1347. return
  1348. cmdlist = ['d.vect',
  1349. 'map=%s' % self.inmap,
  1350. 'type=point,line,boundary,area']
  1351. if self.attributeType == 'color':
  1352. cmdlist.append('rgb_column=%s' % self.properties['tmpColumn'])
  1353. elif self.attributeType == 'size':
  1354. cmdlist.append('size_column=%s' % self.properties['tmpColumn'])
  1355. elif self.attributeType == 'width':
  1356. cmdlist.append('width_column=%s' % self.properties['tmpColumn'])
  1357. ltype = 'vector'
  1358. ColorTable.DoPreview(self, ltype, cmdlist)
  1359. def OnHelp(self, event):
  1360. """Show GRASS manual page"""
  1361. cmd = 'v.colors'
  1362. ColorTable.RunHelp(self, cmd = cmd)
  1363. def UseAttrColumn(self, useAttrColumn):
  1364. """Find layers and apply the changes in d.vect command"""
  1365. layers = self.layerTree.FindItemByData(key = 'name', value = self.inmap)
  1366. if not layers:
  1367. return
  1368. for layer in layers:
  1369. if self.layerTree.GetLayerInfo(layer, key = 'type') != 'vector':
  1370. continue
  1371. cmdlist = self.layerTree.GetLayerInfo(layer, key = 'maplayer').GetCmd()
  1372. if self.attributeType == 'color':
  1373. if useAttrColumn:
  1374. cmdlist[1].update({'rgb_column': self.properties['storeColumn']})
  1375. else:
  1376. cmdlist[1].pop('rgb_column', None)
  1377. elif self.attributeType == 'size':
  1378. cmdlist[1].update({'size_column': self.properties['storeColumn']})
  1379. elif self.attributeType == 'width':
  1380. cmdlist[1].update({'width_column' :self.properties['storeColumn']})
  1381. self.layerTree.SetLayerInfo(layer, key = 'cmd', value = cmdlist)
  1382. def CreateColorTable(self, tmp = False):
  1383. """Create color rules (color table or color column)"""
  1384. if self.colorTable:
  1385. ret = ColorTable.CreateColorTable(self)
  1386. else:
  1387. if self.updateColumn:
  1388. ret = self.UpdateColorColumn(tmp)
  1389. else:
  1390. ret = True
  1391. return ret
  1392. def UpdateColorColumn(self, tmp):
  1393. """Creates color table
  1394. :return: True on success
  1395. :return: False on failure
  1396. """
  1397. rulestxt = ''
  1398. for rule in self.rulesPanel.ruleslines.itervalues():
  1399. if 'value' not in rule: # skip empty rules
  1400. break
  1401. if tmp:
  1402. rgb_col = self.properties['tmpColumn']
  1403. else:
  1404. rgb_col = self.properties['storeColumn']
  1405. if not self.properties['storeColumn']:
  1406. GMessage(parent = self.parent,
  1407. message = _("Please select column to save values to."))
  1408. rulestxt += "UPDATE %s SET %s='%s' WHERE %s ;\n" % (self.properties['table'],
  1409. rgb_col,
  1410. rule[self.attributeType],
  1411. rule['value'])
  1412. if not rulestxt:
  1413. return False
  1414. gtemp = utils.GetTempfile()
  1415. output = open(gtemp, "w")
  1416. try:
  1417. output.write(rulestxt)
  1418. finally:
  1419. output.close()
  1420. RunCommand('db.execute',
  1421. parent = self,
  1422. input = gtemp)
  1423. return True
  1424. def OnCancel(self, event):
  1425. """Do not apply any changes and close the dialog"""
  1426. self.DeleteTemporaryColumn()
  1427. self.Map.Clean()
  1428. self.Destroy()
  1429. def OnApply(self, event):
  1430. """Apply selected color table
  1431. :return: True on success otherwise False
  1432. """
  1433. if self.colorTable:
  1434. self.UseAttrColumn(False)
  1435. else:
  1436. if not self.properties['storeColumn']:
  1437. GError(_("No color column defined. Operation canceled."),
  1438. parent = self)
  1439. return
  1440. self.UseAttrColumn(True)
  1441. return ColorTable.OnApply(self, event)
  1442. class ThematicVectorTable(VectorColorTable):
  1443. def __init__(self, parent, vectorType, **kwargs):
  1444. """Dialog for interactively entering color/size rules
  1445. for vector maps for thematic mapping in nviz"""
  1446. self.vectorType = vectorType
  1447. VectorColorTable.__init__(self, parent = parent, **kwargs)
  1448. self.SetTitle(_("Thematic mapping for vector map in 3D view"))
  1449. def _initLayer(self):
  1450. """Set initial layer when opening dialog"""
  1451. self.inmap = self.parent.GetLayerData(nvizType = 'vector', nameOnly = True)
  1452. self.selectionInput.SetValue(self.inmap)
  1453. self.selectionInput.Disable()
  1454. def OnApply(self, event):
  1455. """Apply selected color table
  1456. :return: True on success otherwise False
  1457. """
  1458. ret = self.CreateColorTable()
  1459. if not ret:
  1460. GMessage(parent = self, message = _("No valid color rules given."))
  1461. data = self.parent.GetLayerData(nvizType = 'vector')
  1462. data['vector']['points']['thematic']['layer'] = int(self.properties['layer'])
  1463. value = None
  1464. if self.properties['storeColumn']:
  1465. value = self.properties['storeColumn']
  1466. if not self.colorTable:
  1467. if self.attributeType == 'color':
  1468. data['vector'][self.vectorType]['thematic']['rgbcolumn'] = value
  1469. else:
  1470. data['vector'][self.vectorType]['thematic']['sizecolumn'] = value
  1471. else:
  1472. if self.attributeType == 'color':
  1473. data['vector'][self.vectorType]['thematic']['rgbcolumn'] = None
  1474. else:
  1475. data['vector'][self.vectorType]['thematic']['sizecolumn'] = None
  1476. data['vector'][self.vectorType]['thematic']['update'] = None
  1477. from nviz.main import haveNviz
  1478. if haveNviz:
  1479. from nviz.mapwindow import wxUpdateProperties
  1480. event = wxUpdateProperties(data = data)
  1481. wx.PostEvent(self.parent.mapWindow, event)
  1482. self.parent.mapWindow.Refresh(False)
  1483. return ret
  1484. class BufferedWindow(wx.Window):
  1485. """A Buffered window class"""
  1486. def __init__(self, parent, id,
  1487. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  1488. Map = None, **kwargs):
  1489. wx.Window.__init__(self, parent, id, style = style, **kwargs)
  1490. self.parent = parent
  1491. self.Map = Map
  1492. # re-render the map from GRASS or just redraw image
  1493. self.render = True
  1494. # indicates whether or not a resize event has taken place
  1495. self.resize = False
  1496. #
  1497. # event bindings
  1498. #
  1499. self.Bind(wx.EVT_PAINT, self.OnPaint)
  1500. self.Bind(wx.EVT_IDLE, self.OnIdle)
  1501. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  1502. #
  1503. # render output objects
  1504. #
  1505. # image file to be rendered
  1506. self.mapfile = None
  1507. # wx.Image object (self.mapfile)
  1508. self.img = None
  1509. self.pdc = wx.PseudoDC()
  1510. # will store an off screen empty bitmap for saving to file
  1511. self._Buffer = None
  1512. # make sure that extents are updated at init
  1513. self.Map.region = self.Map.GetRegion()
  1514. self.Map.SetRegion()
  1515. self.Map.GetRenderMgr().renderDone.connect(self._updatePreviewFinished)
  1516. def Draw(self, pdc, img = None, pdctype = 'image'):
  1517. """Draws preview or clears window"""
  1518. pdc.BeginDrawing()
  1519. Debug.msg (3, "BufferedWindow.Draw(): pdctype=%s" % (pdctype))
  1520. if pdctype == 'clear': # erase the display
  1521. bg = wx.WHITE_BRUSH
  1522. pdc.SetBackground(bg)
  1523. pdc.Clear()
  1524. self.Refresh()
  1525. pdc.EndDrawing()
  1526. return
  1527. if pdctype == 'image' and img:
  1528. bg = wx.TRANSPARENT_BRUSH
  1529. pdc.SetBackground(bg)
  1530. bitmap = wx.BitmapFromImage(img)
  1531. w, h = bitmap.GetSize()
  1532. pdc.DrawBitmap(bitmap, 0, 0, True) # draw the composite map
  1533. pdc.EndDrawing()
  1534. self.Refresh()
  1535. def OnPaint(self, event):
  1536. """Draw pseudo DC to buffer"""
  1537. self._Buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
  1538. dc = wx.BufferedPaintDC(self, self._Buffer)
  1539. # use PrepareDC to set position correctly
  1540. # probably does nothing, removed from wxPython 2.9
  1541. # self.PrepareDC(dc)
  1542. # we need to clear the dc BEFORE calling PrepareDC
  1543. bg = wx.Brush(self.GetBackgroundColour())
  1544. dc.SetBackground(bg)
  1545. dc.Clear()
  1546. # create a clipping rect from our position and size
  1547. # and the Update Region
  1548. rgn = self.GetUpdateRegion()
  1549. r = rgn.GetBox()
  1550. # draw to the dc using the calculated clipping rect
  1551. self.pdc.DrawToDCClipped(dc, r)
  1552. def OnSize(self, event):
  1553. """Init image size to match window size"""
  1554. # set size of the input image
  1555. self.Map.width, self.Map.height = self.GetClientSize()
  1556. # Make new off screen bitmap: this bitmap will always have the
  1557. # current drawing in it, so it can be used to save the image to
  1558. # a file, or whatever.
  1559. self._Buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
  1560. # get the image to be rendered
  1561. self.img = self.GetImage()
  1562. # update map display
  1563. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  1564. self.img = self.img.Scale(self.Map.width, self.Map.height)
  1565. self.render = False
  1566. self.UpdatePreview()
  1567. # re-render image on idle
  1568. self.resize = True
  1569. def OnIdle(self, event):
  1570. """Only re-render a preview image from GRASS during
  1571. idle time instead of multiple times during resizing.
  1572. """
  1573. if self.resize:
  1574. self.render = True
  1575. self.UpdatePreview()
  1576. event.Skip()
  1577. def GetImage(self):
  1578. """Converts files to wx.Image"""
  1579. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  1580. os.path.getsize(self.Map.mapfile):
  1581. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  1582. else:
  1583. img = None
  1584. return img
  1585. def UpdatePreview(self, img = None):
  1586. """Update canvas if window changes geometry"""
  1587. Debug.msg (2, "BufferedWindow.UpdatePreview(%s): render=%s" % (img, self.render))
  1588. if not self.render:
  1589. return
  1590. # extent is taken from current map display
  1591. try:
  1592. self.Map.region = copy.deepcopy(self.parent.parent.GetLayerTree().GetMap().GetCurrentRegion())
  1593. except AttributeError:
  1594. self.Map.region = self.Map.GetRegion()
  1595. # render new map images
  1596. self.mapfile = self.Map.Render(force = self.render)
  1597. def _updatePreviewFinished(self):
  1598. if not self.render:
  1599. return
  1600. self.img = self.GetImage()
  1601. self.resize = False
  1602. if not self.img:
  1603. return
  1604. # paint images to PseudoDC
  1605. self.pdc.Clear()
  1606. self.pdc.RemoveAll()
  1607. # draw map image background
  1608. self.Draw(self.pdc, self.img, pdctype = 'image')
  1609. self.resize = False
  1610. def EraseMap(self):
  1611. """Erase preview"""
  1612. self.Draw(self.pdc, pdctype = 'clear')