colorrules.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  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, 2010-2012 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 os.path.exists(path):
  506. return
  507. rulestxt = ''
  508. for rule in self.rulesPanel.ruleslines.itervalues():
  509. if 'value' not in rule:
  510. continue
  511. rulestxt += rule['value'] + ' ' + rule['color'] + '\n'
  512. if not rulestxt:
  513. GMessage(message = _("Nothing to save."),
  514. parent = self)
  515. return
  516. fd = open(path, 'w')
  517. fd.write(rulestxt)
  518. fd.close()
  519. def OnLoadRulesFile(self, event):
  520. """Load color table from file"""
  521. path = event.GetString()
  522. if not os.path.exists(path):
  523. return
  524. self.rulesPanel.Clear()
  525. fd = open(path, 'r')
  526. self.ReadColorTable(ctable = fd.read())
  527. fd.close()
  528. def ReadColorTable(self, ctable):
  529. """Read color table
  530. :param table: color table in format coming from r.colors.out"""
  531. rulesNumber = len(ctable.splitlines())
  532. self.rulesPanel.AddRules(rulesNumber)
  533. minim = maxim = count = 0
  534. for line in ctable.splitlines():
  535. try:
  536. value, color = map(lambda x: x.strip(), line.split(' '))
  537. except ValueError:
  538. GMessage(parent = self, message = _("Invalid color table format"))
  539. self.rulesPanel.Clear()
  540. return
  541. self.rulesPanel.ruleslines[count]['value'] = value
  542. self.rulesPanel.ruleslines[count]['color'] = color
  543. self.rulesPanel.mainPanel.FindWindowById(count + 1000).SetValue(value)
  544. rgb = list()
  545. for c in color.split(':'):
  546. rgb.append(int(c))
  547. self.rulesPanel.mainPanel.FindWindowById(count + 2000).SetColour(rgb)
  548. # range
  549. try:
  550. if float(value) < minim:
  551. minim = float(value)
  552. if float(value) > maxim:
  553. maxim = float(value)
  554. except ValueError: # nv, default
  555. pass
  556. count += 1
  557. if self.mapType == 'vector':
  558. # raster min, max is known from r.info
  559. self.properties['min'], self.properties['max'] = minim, maxim
  560. self.SetRangeLabel()
  561. self.OnPreview(tmp = True)
  562. def OnLoadDefaultTable(self, event):
  563. """Load internal color table"""
  564. self.LoadTable()
  565. def LoadTable(self, mapType = 'raster'):
  566. """Load current color table (using `r(v).colors.out`)
  567. :param mapType: map type (raster or vector)"""
  568. self.rulesPanel.Clear()
  569. if mapType == 'raster':
  570. cmd = ['r.colors.out',
  571. 'read=True',
  572. 'map=%s' % self.inmap,
  573. 'rules=-']
  574. else:
  575. cmd = ['v.colors.out',
  576. 'read=True',
  577. 'map=%s' % self.inmap,
  578. 'rules=-']
  579. if self.properties['sourceColumn'] and self.properties['sourceColumn'] != 'cat':
  580. cmd.append('column=%s' % self.properties['sourceColumn'])
  581. cmd = cmdlist_to_tuple(cmd)
  582. if self.inmap:
  583. ctable = RunCommand(cmd[0], **cmd[1])
  584. else:
  585. self.OnPreview()
  586. return
  587. self.ReadColorTable(ctable = ctable)
  588. def CreateColorTable(self, tmp = False):
  589. """Creates color table
  590. :return: True on success
  591. :return: False on failure
  592. """
  593. rulestxt = ''
  594. for rule in self.rulesPanel.ruleslines.itervalues():
  595. if 'value' not in rule: # skip empty rules
  596. continue
  597. if rule['value'] not in ('nv', 'default') and \
  598. rule['value'][-1] != '%' and \
  599. not self._IsNumber(rule['value']):
  600. GError(_("Invalid rule value '%s'. Unable to apply color table.") % rule['value'],
  601. parent = self)
  602. return False
  603. rulestxt += rule['value'] + ' ' + rule['color'] + '\n'
  604. if not rulestxt:
  605. return False
  606. gtemp = utils.GetTempfile()
  607. output = open(gtemp, "w")
  608. try:
  609. output.write(rulestxt)
  610. finally:
  611. output.close()
  612. cmd = ['%s.colors' % self.mapType[0], #r.colors/v.colors
  613. 'map=%s' % self.inmap,
  614. 'rules=%s' % gtemp]
  615. if self.mapType == 'vector' and self.properties['sourceColumn'] \
  616. and self.properties['sourceColumn'] != 'cat':
  617. cmd.append('column=%s' % self.properties['sourceColumn'])
  618. cmd = cmdlist_to_tuple(cmd)
  619. ret = RunCommand(cmd[0], **cmd[1])
  620. if ret != 0:
  621. return False
  622. return True
  623. def DoPreview(self, ltype, cmdlist):
  624. """Update preview (based on computational region)"""
  625. if not self.layer:
  626. self.layer = self.Map.AddLayer(ltype = ltype, name = 'preview', command = cmdlist,
  627. active = True, hidden = False, opacity = 1.0,
  628. render = False)
  629. else:
  630. self.layer.SetCmd(cmdlist)
  631. # apply new color table and display preview
  632. self.CreateColorTable(tmp = True)
  633. self.preview.UpdatePreview()
  634. def RunHelp(self, cmd):
  635. """Show GRASS manual page"""
  636. RunCommand('g.manual',
  637. quiet = True,
  638. parent = self,
  639. entry = cmd)
  640. def SetMap(self, name):
  641. """Set map name and update dialog"""
  642. self.selectionInput.SetValue(name)
  643. def _IsNumber(self, s):
  644. """Check if 's' is a number"""
  645. try:
  646. float(s)
  647. return True
  648. except ValueError:
  649. return False
  650. class RasterColorTable(ColorTable):
  651. def __init__(self, parent, **kwargs):
  652. """Dialog for interactively entering color rules for raster maps"""
  653. self.mapType = 'raster'
  654. self.attributeType = 'color'
  655. self.colorTable = True
  656. # raster properties
  657. self.properties = {
  658. # min cat in raster map
  659. 'min' : None,
  660. # max cat in raster map
  661. 'max' : None,
  662. }
  663. ColorTable.__init__(self, parent,
  664. title = _('Create new color table for raster map'), **kwargs)
  665. self._initLayer()
  666. # self.SetMinSize(self.GetSize())
  667. self.SetMinSize((650, 700))
  668. def _doLayout(self):
  669. """Do main layout"""
  670. sizer = wx.BoxSizer(wx.VERTICAL)
  671. #
  672. # map selection
  673. #
  674. mapSelection = self._createMapSelection(parent = self.panel)
  675. sizer.Add(item = mapSelection, proportion = 0,
  676. flag = wx.ALL | wx.EXPAND, border = 5)
  677. #
  678. # manage extern tables
  679. #
  680. fileSelection = self._createFileSelection(parent = self.panel)
  681. sizer.Add(item = fileSelection, proportion = 0,
  682. flag = wx.LEFT | wx.RIGHT | wx.EXPAND, border = 5)
  683. #
  684. # body & preview
  685. #
  686. bodySizer = self._createBody(parent = self.panel)
  687. sizer.Add(item = bodySizer, proportion = 1,
  688. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  689. #
  690. # buttons
  691. #
  692. btnSizer = self._createButtons(parent = self.panel)
  693. sizer.Add(item = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
  694. style = wx.LI_HORIZONTAL), proportion = 0,
  695. flag = wx.EXPAND | wx.ALL, border = 5)
  696. sizer.Add(item = btnSizer, proportion = 0,
  697. flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
  698. self.panel.SetSizer(sizer)
  699. sizer.Layout()
  700. sizer.Fit(self.panel)
  701. self.Layout()
  702. def OnSelectionInput(self, event):
  703. """Raster map selected"""
  704. if event:
  705. self.inmap = event.GetString()
  706. self.loadRules.SetValue('')
  707. self.saveRules.SetValue('')
  708. if self.inmap:
  709. if not grass.find_file(name = self.inmap, element = 'cell')['file']:
  710. self.inmap = None
  711. if not self.inmap:
  712. for btn in (self.btnPreview, self.btnOK,
  713. self.btnApply, self.btnDefault, self.btnSet):
  714. btn.Enable(False)
  715. self.LoadTable()
  716. return
  717. info = grass.raster_info(map = self.inmap)
  718. if info:
  719. self.properties['min'] = info['min']
  720. self.properties['max'] = info['max']
  721. self.LoadTable()
  722. else:
  723. self.inmap = ''
  724. self.properties['min'] = self.properties['max'] = None
  725. for btn in (self.btnPreview, self.btnOK,
  726. self.btnApply, self.btnDefault, self.btnSet):
  727. btn.Enable(False)
  728. self.preview.EraseMap()
  729. self.cr_label.SetLabel(_('Enter raster category values or percents'))
  730. return
  731. if info['datatype'] == 'CELL':
  732. mapRange = _('range')
  733. else:
  734. mapRange = _('fp range')
  735. self.cr_label.SetLabel(_('Enter raster category values or percents (%(range)s = %(min)d-%(max)d)') %
  736. { 'range' : mapRange,
  737. 'min' : self.properties['min'],
  738. 'max' : self.properties['max'] })
  739. for btn in (self.btnPreview, self.btnOK,
  740. self.btnApply, self.btnDefault, self.btnSet):
  741. btn.Enable()
  742. def OnPreview(self, tmp = True):
  743. """Update preview (based on computational region)"""
  744. if not self.inmap:
  745. self.preview.EraseMap()
  746. return
  747. cmdlist = ['d.rast',
  748. 'map=%s' % self.inmap]
  749. ltype = 'raster'
  750. # find existing color table and copy to temp file
  751. try:
  752. name, mapset = self.inmap.split('@')
  753. except ValueError:
  754. name = self.inmap
  755. mapset = grass.find_file(self.inmap, element = 'cell')['mapset']
  756. if not mapset:
  757. return
  758. old_colrtable = None
  759. if mapset == grass.gisenv()['MAPSET']:
  760. old_colrtable = grass.find_file(name = name, element = 'colr')['file']
  761. else:
  762. old_colrtable = grass.find_file(name = name, element = 'colr2/' + mapset)['file']
  763. if old_colrtable:
  764. colrtemp = utils.GetTempfile()
  765. shutil.copyfile(old_colrtable, colrtemp)
  766. ColorTable.DoPreview(self, ltype, cmdlist)
  767. # restore previous color table
  768. if tmp:
  769. if old_colrtable:
  770. shutil.copyfile(colrtemp, old_colrtable)
  771. os.remove(colrtemp)
  772. else:
  773. RunCommand('r.colors',
  774. parent = self,
  775. flags = 'r',
  776. map = self.inmap)
  777. def OnHelp(self, event):
  778. """Show GRASS manual page"""
  779. cmd = 'r.colors'
  780. ColorTable.RunHelp(self, cmd = cmd)
  781. class VectorColorTable(ColorTable):
  782. def __init__(self, parent, attributeType, **kwargs):
  783. """Dialog for interactively entering color rules for vector maps"""
  784. # dialog attributes
  785. self.mapType = 'vector'
  786. self.attributeType = attributeType # color, size, width
  787. # in version 7 v.colors used, otherwise color column only
  788. self.version7 = int(grass.version()['version'].split('.')[0]) >= 7
  789. self.colorTable = False
  790. self.updateColumn = True
  791. # vector properties
  792. self.properties = {
  793. # vector layer for attribute table to use for setting color
  794. 'layer' : 1,
  795. # vector attribute table used for setting color
  796. 'table' : '',
  797. # vector attribute column for assigning colors
  798. 'sourceColumn' : '',
  799. # vector attribute column to use for loading colors
  800. 'loadColumn' : '',
  801. # vector attribute column to use for storing colors
  802. 'storeColumn' : '',
  803. # vector attribute column for temporary storing colors
  804. 'tmpColumn' : 'tmp_0',
  805. # min value of attribute column/vector color table
  806. 'min': None,
  807. # max value of attribute column/vector color table
  808. 'max': None
  809. }
  810. self.columnsProp = {'color': {'name': 'GRASSRGB', 'type1': 'varchar(11)', 'type2': ['character']},
  811. 'size' : {'name': 'GRASSSIZE', 'type1': 'integer', 'type2': ['integer']},
  812. 'width': {'name': 'GRASSWIDTH', 'type1': 'integer', 'type2': ['integer']}}
  813. ColorTable.__init__(self, parent = parent,
  814. title = _('Create new color rules for vector map'), **kwargs)
  815. # additional bindings for vector color management
  816. self.Bind(wx.EVT_COMBOBOX, self.OnLayerSelection, self.layerSelect)
  817. self.sourceColumn.Bind(wx.EVT_TEXT, self.OnSourceColumnSelection)
  818. self.fromColumn.Bind(wx.EVT_TEXT, self.OnFromColSelection)
  819. self.toColumn.Bind(wx.EVT_TEXT, self.OnToColSelection)
  820. self.Bind(wx.EVT_BUTTON, self.OnAddColumn, self.addColumn)
  821. self._initLayer()
  822. if self.colorTable:
  823. self.cr_label.SetLabel(_("Enter vector attribute values or percents:"))
  824. else:
  825. self.cr_label.SetLabel(_("Enter vector attribute values:"))
  826. #self.SetMinSize(self.GetSize())
  827. self.SetMinSize((650, 700))
  828. self.CentreOnScreen()
  829. self.Show()
  830. def _createVectorAttrb(self, parent):
  831. """Create part of dialog with layer/column selection"""
  832. inputBox = wx.StaticBox(parent = parent, id = wx.ID_ANY,
  833. label = " %s " % _("Select vector columns"))
  834. cb_vl_label = wx.StaticText(parent, id = wx.ID_ANY,
  835. label = _('Layer:'))
  836. cb_vc_label = wx.StaticText(parent, id = wx.ID_ANY,
  837. label = _('Attribute column:'))
  838. if self.attributeType == 'color':
  839. labels = [_("Load color from column:"), _("Save color to column:")]
  840. elif self.attributeType == 'size':
  841. labels = [_("Load size from column:"), _("Save size to column:")]
  842. elif self.attributeType == 'width':
  843. labels = [_("Load width from column:"), _("Save width to column:")]
  844. if self.version7 and self.attributeType == 'color':
  845. self.useColumn = wx.CheckBox(parent, id = wx.ID_ANY,
  846. label = _("Use color column instead of color table:"))
  847. self.useColumn.Bind(wx.EVT_CHECKBOX, self.OnCheckColumn)
  848. fromColumnLabel = wx.StaticText(parent, id = wx.ID_ANY,
  849. label = labels[0])
  850. toColumnLabel = wx.StaticText(parent, id = wx.ID_ANY,
  851. label = labels[1])
  852. self.rgb_range_label = wx.StaticText(parent, id = wx.ID_ANY)
  853. self.layerSelect = LayerSelect(parent)
  854. self.sourceColumn = ColumnSelect(parent)
  855. self.fromColumn = ColumnSelect(parent)
  856. self.toColumn = ColumnSelect(parent)
  857. self.addColumn = wx.Button(parent, id = wx.ID_ANY,
  858. label = _('Add column'))
  859. self.addColumn.SetToolTipString(_("Add GRASSRGB column to current attribute table."))
  860. # layout
  861. inputSizer = wx.StaticBoxSizer(inputBox, wx.VERTICAL)
  862. vSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  863. row = 0
  864. vSizer.Add(cb_vl_label, pos = (row, 0),
  865. flag = wx.ALIGN_CENTER_VERTICAL)
  866. vSizer.Add(self.layerSelect, pos = (row, 1),
  867. flag = wx.ALIGN_CENTER_VERTICAL)
  868. row += 1
  869. vSizer.Add(cb_vc_label, pos = (row, 0),
  870. flag = wx.ALIGN_CENTER_VERTICAL)
  871. vSizer.Add(self.sourceColumn, pos = (row, 1),
  872. flag = wx.ALIGN_CENTER_VERTICAL)
  873. vSizer.Add(self.rgb_range_label, pos = (row, 2),
  874. flag = wx.ALIGN_CENTER_VERTICAL)
  875. row += 1
  876. if self.version7 and self.attributeType == 'color':
  877. vSizer.Add(self.useColumn, pos = (row, 0), span = (1, 2),
  878. flag = wx.ALIGN_CENTER_VERTICAL)
  879. row += 1
  880. vSizer.Add(fromColumnLabel, pos = (row, 0),
  881. flag = wx.ALIGN_CENTER_VERTICAL)
  882. vSizer.Add(self.fromColumn, pos = (row, 1),
  883. flag = wx.ALIGN_CENTER_VERTICAL)
  884. row += 1
  885. vSizer.Add(toColumnLabel, pos = (row, 0),
  886. flag = wx.ALIGN_CENTER_VERTICAL)
  887. vSizer.Add(self.toColumn, pos = (row, 1),
  888. flag = wx.ALIGN_CENTER_VERTICAL)
  889. vSizer.Add(self.addColumn, pos = (row, 2),
  890. flag = wx.ALIGN_CENTER_VERTICAL)
  891. inputSizer.Add(item = vSizer,
  892. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border = 5)
  893. self.colorColumnSizer = vSizer
  894. return inputSizer
  895. def _doLayout(self):
  896. """Do main layout"""
  897. scrollPanel = scrolled.ScrolledPanel(parent = self.panel, id = wx.ID_ANY,
  898. style = wx.TAB_TRAVERSAL)
  899. scrollPanel.SetupScrolling()
  900. sizer = wx.BoxSizer(wx.VERTICAL)
  901. #
  902. # map selection
  903. #
  904. mapSelection = self._createMapSelection(parent = scrollPanel)
  905. sizer.Add(item = mapSelection, proportion = 0,
  906. flag = wx.ALL | wx.EXPAND, border = 5)
  907. #
  908. # manage extern tables
  909. #
  910. if self.version7 and self.attributeType == 'color':
  911. self.cp = wx.CollapsiblePane(scrollPanel, label = _("Import or export color table"),
  912. winid = wx.ID_ANY,
  913. style = wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)
  914. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged, self.cp)
  915. self._createFileSelection(parent = self.cp.GetPane())
  916. sizer.Add(item = self.cp, proportion = 0,
  917. flag = wx.ALL | wx.EXPAND, border = 5)
  918. #
  919. # set vector attributes
  920. #
  921. vectorAttrb = self._createVectorAttrb(parent = scrollPanel)
  922. sizer.Add(item = vectorAttrb, proportion = 0,
  923. flag = wx.ALL | wx.EXPAND, border = 5)
  924. #
  925. # body & preview
  926. #
  927. bodySizer = self._createBody(parent = scrollPanel)
  928. sizer.Add(item = bodySizer, proportion = 1,
  929. flag = wx.ALL | wx.EXPAND, border = 5)
  930. scrollPanel.SetSizer(sizer)
  931. scrollPanel.Fit()
  932. #
  933. # buttons
  934. #
  935. btnSizer = self._createButtons(self.panel)
  936. mainsizer = wx.BoxSizer(wx.VERTICAL)
  937. mainsizer.Add(scrollPanel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  938. mainsizer.Add(item = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
  939. style = wx.LI_HORIZONTAL), proportion = 0,
  940. flag = wx.EXPAND | wx.ALL, border = 5)
  941. mainsizer.Add(item = btnSizer, proportion = 0,
  942. flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
  943. self.panel.SetSizer(mainsizer)
  944. mainsizer.Layout()
  945. mainsizer.Fit(self.panel)
  946. self.Layout()
  947. def OnPaneChanged(self, event = None):
  948. # redo the layout
  949. self.Layout()
  950. # and also change the labels
  951. if self.cp.IsExpanded():
  952. self.cp.SetLabel('')
  953. else:
  954. self.cp.SetLabel(_("Import or export color table"))
  955. def CheckMapset(self):
  956. """Check if current vector is in current mapset"""
  957. if grass.find_file(name = self.inmap,
  958. element = 'vector')['mapset'] == grass.gisenv()['MAPSET']:
  959. return True
  960. else:
  961. return False
  962. def NoConnection(self, vectorName):
  963. dlg = wx.MessageDialog(parent = self,
  964. message = _("Database connection for vector map <%s> "
  965. "is not defined in DB file. Do you want to create and "
  966. "connect new attribute table?") % vectorName,
  967. caption = _("No database connection defined"),
  968. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  969. if dlg.ShowModal() == wx.ID_YES:
  970. dlg.Destroy()
  971. GUI(parent = self).ParseCommand(['v.db.addtable', 'map=' + self.inmap],
  972. completed = (self.CreateAttrTable, self.inmap, ''))
  973. else:
  974. dlg.Destroy()
  975. def OnCheckColumn(self, event):
  976. """Use color column instead of color table"""
  977. if self.useColumn.GetValue():
  978. self.properties['loadColumn'] = self.fromColumn.GetValue()
  979. self.properties['storeColumn'] = self.toColumn.GetValue()
  980. self.fromColumn.Enable(True)
  981. self.toColumn.Enable(True)
  982. self.colorTable = False
  983. if self.properties['loadColumn']:
  984. self.LoadTable()
  985. else:
  986. self.rulesPanel.Clear()
  987. else:
  988. self.properties['loadColumn'] = ''
  989. self.properties['storeColumn'] = ''
  990. self.fromColumn.Enable(False)
  991. self.toColumn.Enable(False)
  992. self.colorTable = True
  993. self.LoadTable()
  994. def EnableVectorAttributes(self, enable):
  995. """Enable/disable part of dialog connected with db"""
  996. for child in self.colorColumnSizer.GetChildren():
  997. child.GetWindow().Enable(enable)
  998. def DisableClearAll(self):
  999. """Enable, disable the whole dialog"""
  1000. self.rulesPanel.Clear()
  1001. self.EnableVectorAttributes(False)
  1002. self.btnPreview.Enable(False)
  1003. self.btnOK.Enable(False)
  1004. self.btnApply.Enable(False)
  1005. self.preview.EraseMap()
  1006. def OnSelectionInput(self, event):
  1007. """Vector map selected"""
  1008. if event:
  1009. if self.inmap:
  1010. # switch to another map -> delete temporary column
  1011. self.DeleteTemporaryColumn()
  1012. self.inmap = event.GetString()
  1013. if self.version7 and self.attributeType == 'color':
  1014. self.loadRules.SetValue('')
  1015. self.saveRules.SetValue('')
  1016. if self.inmap:
  1017. if not grass.find_file(name = self.inmap, element = 'vector')['file']:
  1018. self.inmap = None
  1019. self.UpdateDialog()
  1020. def UpdateDialog(self):
  1021. """Update dialog after map selection"""
  1022. if not self.inmap:
  1023. self.DisableClearAll()
  1024. return
  1025. if not self.CheckMapset():
  1026. # v.colors doesn't need the map to be in current mapset
  1027. if not (self.version7 and self.attributeType == 'color'):
  1028. message = _("Selected map <%(map)s> is not in current mapset <%(mapset)s>. "
  1029. "Attribute table cannot be edited.") % \
  1030. { 'map' : self.inmap,
  1031. 'mapset' : grass.gisenv()['MAPSET'] }
  1032. wx.CallAfter(GMessage, parent = self, message = message)
  1033. self.DisableClearAll()
  1034. return
  1035. # check for db connection
  1036. self.dbInfo = VectorDBInfo(self.inmap)
  1037. enable = True
  1038. if not len(self.dbInfo.layers): # no connection
  1039. if not (self.version7 and self.attributeType == 'color'): # otherwise it doesn't matter
  1040. wx.CallAfter(self.NoConnection, self.inmap)
  1041. enable = False
  1042. for combo in (self.layerSelect, self.sourceColumn, self.fromColumn, self.toColumn):
  1043. combo.SetValue("")
  1044. combo.Clear()
  1045. for prop in ('sourceColumn', 'loadColumn', 'storeColumn'):
  1046. self.properties[prop] = ''
  1047. self.EnableVectorAttributes(False)
  1048. else: # db connection exist
  1049. # initialize layer selection combobox
  1050. self.EnableVectorAttributes(True)
  1051. self.layerSelect.InsertLayers(self.inmap)
  1052. # initialize attribute table for layer=1
  1053. self.properties['layer'] = self.layerSelect.GetString(0)
  1054. self.layerSelect.SetStringSelection(self.properties['layer'])
  1055. layer = int(self.properties['layer'])
  1056. self.properties['table'] = self.dbInfo.layers[layer]['table']
  1057. if self.attributeType == 'color':
  1058. self.AddTemporaryColumn(type = 'varchar(11)')
  1059. else:
  1060. self.AddTemporaryColumn(type = 'integer')
  1061. # initialize column selection comboboxes
  1062. self.OnLayerSelection(event = None)
  1063. if self.version7 and self.attributeType == 'color':
  1064. self.useColumn.SetValue(False)
  1065. self.OnCheckColumn(event = None)
  1066. self.useColumn.Enable(self.CheckMapset())
  1067. self.LoadTable()
  1068. self.btnPreview.Enable(enable)
  1069. self.btnOK.Enable(enable)
  1070. self.btnApply.Enable(enable)
  1071. def AddTemporaryColumn(self, type):
  1072. """Add temporary column to not overwrite the original values,
  1073. need to be deleted when closing dialog and unloading map
  1074. :param type: type of column (e.g. vachar(11))"""
  1075. if not self.CheckMapset():
  1076. return
  1077. # because more than one dialog with the same map can be opened we must test column name and
  1078. # create another one
  1079. while self.properties['tmpColumn'] in self.dbInfo.GetTableDesc(self.properties['table']).keys():
  1080. name, idx = self.properties['tmpColumn'].split('_')
  1081. idx = int(idx)
  1082. idx += 1
  1083. self.properties['tmpColumn'] = name + '_' + str(idx)
  1084. if self.version7:
  1085. modul = 'v.db.addcolumn'
  1086. else:
  1087. modul = 'v.db.addcol'
  1088. ret = RunCommand(modul,
  1089. parent = self,
  1090. map = self.inmap,
  1091. layer = self.properties['layer'],
  1092. column = '%s %s' % (self.properties['tmpColumn'], type))
  1093. def DeleteTemporaryColumn(self):
  1094. """Delete temporary column"""
  1095. if not self.CheckMapset():
  1096. return
  1097. if self.inmap:
  1098. if self.version7:
  1099. modul = 'v.db.dropcolumn'
  1100. else:
  1101. modul = 'v.db.dropcol'
  1102. ret = RunCommand(modul,
  1103. map = self.inmap,
  1104. layer = self.properties['layer'],
  1105. column = self.properties['tmpColumn'])
  1106. def OnLayerSelection(self, event):
  1107. # reset choices in column selection comboboxes if layer changes
  1108. vlayer = int(self.layerSelect.GetStringSelection())
  1109. self.sourceColumn.InsertColumns(vector = self.inmap, layer = vlayer,
  1110. type = ['integer', 'double precision'], dbInfo = self.dbInfo,
  1111. excludeCols = ['tmpColumn'])
  1112. self.sourceColumn.SetValue('cat')
  1113. self.properties['sourceColumn'] = self.sourceColumn.GetValue()
  1114. if self.attributeType == 'color':
  1115. type = ['character']
  1116. else:
  1117. type = ['integer']
  1118. self.fromColumn.InsertColumns(vector = self.inmap, layer = vlayer, type = type,
  1119. dbInfo = self.dbInfo, excludeCols = ['tmpColumn'])
  1120. self.toColumn.InsertColumns(vector = self.inmap, layer = vlayer, type = type,
  1121. dbInfo = self.dbInfo, excludeCols = ['tmpColumn'])
  1122. v = self.columnsProp[self.attributeType]['name']
  1123. found = False
  1124. if v in self.fromColumn.GetColumns():
  1125. found = True
  1126. if found != wx.NOT_FOUND:
  1127. self.fromColumn.SetValue(v)
  1128. self.toColumn.SetValue(v)
  1129. self.properties['loadColumn'] = v
  1130. self.properties['storeColumn'] = v
  1131. else:
  1132. self.properties['loadColumn'] = ''
  1133. self.properties['storeColumn'] = ''
  1134. if event:
  1135. self.LoadTable()
  1136. self.Update()
  1137. def OnSourceColumnSelection(self, event):
  1138. self.properties['sourceColumn'] = event.GetString()
  1139. self.LoadTable()
  1140. def OnAddColumn(self, event):
  1141. """Add GRASS(RGB,SIZE,WIDTH) column if it doesn't exist"""
  1142. if self.columnsProp[self.attributeType]['name'] not in self.fromColumn.GetColumns():
  1143. if self.version7:
  1144. modul = 'v.db.addcolumn'
  1145. else:
  1146. modul = 'v.db.addcol'
  1147. ret = RunCommand(modul,
  1148. map = self.inmap,
  1149. layer = self.properties['layer'],
  1150. columns = '%s %s' % (self.columnsProp[self.attributeType]['name'],
  1151. self.columnsProp[self.attributeType]['type1']))
  1152. self.toColumn.InsertColumns(self.inmap, self.properties['layer'],
  1153. type = self.columnsProp[self.attributeType]['type2'])
  1154. self.toColumn.SetValue(self.columnsProp[self.attributeType]['name'])
  1155. self.properties['storeColumn'] = self.toColumn.GetValue()
  1156. self.LoadTable()
  1157. else:
  1158. GMessage(parent = self,
  1159. message = _("%s column already exists.") % \
  1160. self.columnsProp[self.attributeType]['name'])
  1161. def CreateAttrTable(self, dcmd, layer, params, propwin):
  1162. """Create attribute table"""
  1163. if dcmd:
  1164. cmd = cmdlist_to_tuple(dcmd)
  1165. ret = RunCommand(cmd[0], **cmd[1])
  1166. if ret == 0:
  1167. self.OnSelectionInput(None)
  1168. return True
  1169. for combo in (self.layerSelect, self.sourceColumn, self.fromColumn, self.toColumn):
  1170. combo.SetValue("")
  1171. combo.Disable()
  1172. return False
  1173. def LoadTable(self):
  1174. """Load table"""
  1175. if self.colorTable:
  1176. ColorTable.LoadTable(self, mapType = 'vector')
  1177. else:
  1178. self.LoadRulesFromColumn()
  1179. def LoadRulesFromColumn(self):
  1180. """Load current column (GRASSRGB, size column)"""
  1181. self.rulesPanel.Clear()
  1182. if not self.properties['sourceColumn']:
  1183. self.preview.EraseMap()
  1184. return
  1185. busy = wx.BusyInfo(message = _("Please wait, loading data from attribute table..."),
  1186. parent = self)
  1187. wx.Yield()
  1188. columns = self.properties['sourceColumn']
  1189. if self.properties['loadColumn']:
  1190. columns += ',' + self.properties['loadColumn']
  1191. sep = ';'
  1192. if self.inmap:
  1193. outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1194. ret = RunCommand('v.db.select',
  1195. quiet = True,
  1196. flags = 'c',
  1197. map = self.inmap,
  1198. layer = self.properties['layer'],
  1199. columns = columns,
  1200. sep = sep,
  1201. stdout = outFile)
  1202. else:
  1203. self.preview.EraseMap()
  1204. busy.Destroy()
  1205. return
  1206. outFile.seek(0)
  1207. i = 0
  1208. minim = maxim = 0.0
  1209. limit = 1000
  1210. colvallist = []
  1211. readvals = False
  1212. while True:
  1213. # os.linesep doesn't work here (MSYS)
  1214. record = outFile.readline().replace('\n', '')
  1215. if not record:
  1216. break
  1217. self.rulesPanel.ruleslines[i] = {}
  1218. if not self.properties['loadColumn']:
  1219. col1 = record
  1220. col2 = None
  1221. else:
  1222. col1, col2 = record.split(sep)
  1223. if float(col1) < minim:
  1224. minim = float(col1)
  1225. if float(col1) > maxim:
  1226. maxim = float(col1)
  1227. # color rules list should only have unique values of col1, not all records
  1228. if col1 not in colvallist:
  1229. self.rulesPanel.ruleslines[i]['value'] = col1
  1230. self.rulesPanel.ruleslines[i][self.attributeType] = col2
  1231. colvallist.append(col1)
  1232. i += 1
  1233. if i > limit and readvals == False:
  1234. dlg = wx.MessageDialog (parent = self, message = _(
  1235. "Number of loaded records reached %d, "
  1236. "displaying all the records will be time-consuming "
  1237. "and may lead to computer freezing, "
  1238. "do you still want to continue?") % i,
  1239. caption = _("Too many records"),
  1240. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  1241. if dlg.ShowModal() == wx.ID_YES:
  1242. readvals = True
  1243. dlg.Destroy()
  1244. else:
  1245. busy.Destroy()
  1246. dlg.Destroy()
  1247. self.updateColumn = False
  1248. return
  1249. self.rulesPanel.AddRules(i, start = True)
  1250. ret = self.rulesPanel.LoadRules()
  1251. self.properties['min'], self.properties['max'] = minim, maxim
  1252. self.SetRangeLabel()
  1253. if ret:
  1254. self.OnPreview()
  1255. else:
  1256. self.rulesPanel.Clear()
  1257. busy.Destroy()
  1258. def SetRangeLabel(self):
  1259. """Set labels with info about attribute column range"""
  1260. if self.properties['sourceColumn']:
  1261. ctype = self.dbInfo.GetTableDesc(self.properties['table'])[self.properties['sourceColumn']]['ctype']
  1262. else:
  1263. ctype = int
  1264. range = ''
  1265. if self.properties['min'] or self.properties['max']:
  1266. if ctype == float:
  1267. range = "%s: %.1f - %.1f)" % (_("range"),
  1268. self.properties['min'], self.properties['max'])
  1269. elif ctype == int:
  1270. range = "%s: %d - %d)" % (_("range"),
  1271. self.properties['min'], self.properties['max'])
  1272. if range:
  1273. if self.colorTable:
  1274. self.cr_label.SetLabel(_("Enter vector attribute values or percents %s:") % range)
  1275. else:
  1276. self.cr_label.SetLabel(_("Enter vector attribute values %s:") % range)
  1277. else:
  1278. if self.colorTable:
  1279. self.cr_label.SetLabel(_("Enter vector attribute values or percents:"))
  1280. else:
  1281. self.cr_label.SetLabel(_("Enter vector attribute values:"))
  1282. def OnFromColSelection(self, event):
  1283. """Selection in combobox (for loading values) changed"""
  1284. self.properties['loadColumn'] = event.GetString()
  1285. self.LoadTable()
  1286. def OnToColSelection(self, event):
  1287. """Selection in combobox (for storing values) changed"""
  1288. self.properties['storeColumn'] = event.GetString()
  1289. def OnPreview(self, event = None, tmp = True):
  1290. """Update preview (based on computational region)"""
  1291. if self.colorTable:
  1292. self.OnTablePreview(tmp)
  1293. else:
  1294. self.OnColumnPreview()
  1295. def OnTablePreview(self, tmp):
  1296. """Update preview (based on computational region)"""
  1297. if not self.inmap:
  1298. self.preview.EraseMap()
  1299. return
  1300. ltype = 'vector'
  1301. cmdlist = ['d.vect',
  1302. 'map=%s' % self.inmap]
  1303. # find existing color table and copy to temp file
  1304. try:
  1305. name, mapset = self.inmap.split('@')
  1306. except ValueError:
  1307. name = self.inmap
  1308. mapset = grass.find_file(self.inmap, element = 'cell')['mapset']
  1309. if not mapset:
  1310. return
  1311. old_colrtable = None
  1312. if mapset == grass.gisenv()['MAPSET']:
  1313. old_colrtable = grass.find_file(name = 'colr', element = os.path.join('vector', name))['file']
  1314. else:
  1315. old_colrtable = grass.find_file(name = name, element = os.path.join('vcolr2', mapset))['file']
  1316. if old_colrtable:
  1317. colrtemp = utils.GetTempfile()
  1318. shutil.copyfile(old_colrtable, colrtemp)
  1319. ColorTable.DoPreview(self, ltype, cmdlist)
  1320. # restore previous color table
  1321. if tmp:
  1322. if old_colrtable:
  1323. shutil.copyfile(colrtemp, old_colrtable)
  1324. os.remove(colrtemp)
  1325. else:
  1326. RunCommand('v.colors',
  1327. parent = self,
  1328. flags = 'r',
  1329. map = self.inmap)
  1330. def OnColumnPreview(self):
  1331. """Update preview (based on computational region)"""
  1332. if not self.inmap or not self.properties['tmpColumn']:
  1333. self.preview.EraseMap()
  1334. return
  1335. cmdlist = ['d.vect',
  1336. 'map=%s' % self.inmap,
  1337. 'type=point,line,boundary,area']
  1338. if self.attributeType == 'color':
  1339. cmdlist.append('rgb_column=%s' % self.properties['tmpColumn'])
  1340. elif self.attributeType == 'size':
  1341. cmdlist.append('size_column=%s' % self.properties['tmpColumn'])
  1342. elif self.attributeType == 'width':
  1343. cmdlist.append('width_column=%s' % self.properties['tmpColumn'])
  1344. ltype = 'vector'
  1345. ColorTable.DoPreview(self, ltype, cmdlist)
  1346. def OnHelp(self, event):
  1347. """Show GRASS manual page"""
  1348. cmd = 'v.colors'
  1349. ColorTable.RunHelp(self, cmd = cmd)
  1350. def UseAttrColumn(self, useAttrColumn):
  1351. """Find layers and apply the changes in d.vect command"""
  1352. layers = self.layerTree.FindItemByData(key = 'name', value = self.inmap)
  1353. if not layers:
  1354. return
  1355. for layer in layers:
  1356. if self.layerTree.GetLayerInfo(layer, key = 'type') != 'vector':
  1357. continue
  1358. cmdlist = self.layerTree.GetLayerInfo(layer, key = 'maplayer').GetCmd()
  1359. if self.attributeType == 'color':
  1360. if useAttrColumn:
  1361. cmdlist[1].update({'rgb_column': self.properties['storeColumn']})
  1362. else:
  1363. cmdlist[1].pop('rgb_column', None)
  1364. elif self.attributeType == 'size':
  1365. cmdlist[1].update({'size_column': self.properties['storeColumn']})
  1366. elif self.attributeType == 'width':
  1367. cmdlist[1].update({'width_column' :self.properties['storeColumn']})
  1368. self.layerTree.SetLayerInfo(layer, key = 'cmd', value = cmdlist)
  1369. def CreateColorTable(self, tmp = False):
  1370. """Create color rules (color table or color column)"""
  1371. if self.colorTable:
  1372. ret = ColorTable.CreateColorTable(self)
  1373. else:
  1374. if self.updateColumn:
  1375. ret = self.UpdateColorColumn(tmp)
  1376. else:
  1377. ret = True
  1378. return ret
  1379. def UpdateColorColumn(self, tmp):
  1380. """Creates color table
  1381. :return: True on success
  1382. :return: False on failure
  1383. """
  1384. rulestxt = ''
  1385. for rule in self.rulesPanel.ruleslines.itervalues():
  1386. if 'value' not in rule: # skip empty rules
  1387. break
  1388. if tmp:
  1389. rgb_col = self.properties['tmpColumn']
  1390. else:
  1391. rgb_col = self.properties['storeColumn']
  1392. if not self.properties['storeColumn']:
  1393. GMessage(parent = self.parent,
  1394. message = _("Please select column to save values to."))
  1395. rulestxt += "UPDATE %s SET %s='%s' WHERE %s ;\n" % (self.properties['table'],
  1396. rgb_col,
  1397. rule[self.attributeType],
  1398. rule['value'])
  1399. if not rulestxt:
  1400. return False
  1401. gtemp = utils.GetTempfile()
  1402. output = open(gtemp, "w")
  1403. try:
  1404. output.write(rulestxt)
  1405. finally:
  1406. output.close()
  1407. RunCommand('db.execute',
  1408. parent = self,
  1409. input = gtemp)
  1410. return True
  1411. def OnCancel(self, event):
  1412. """Do not apply any changes and close the dialog"""
  1413. self.DeleteTemporaryColumn()
  1414. self.Map.Clean()
  1415. self.Destroy()
  1416. def OnApply(self, event):
  1417. """Apply selected color table
  1418. :return: True on success otherwise False
  1419. """
  1420. if self.colorTable:
  1421. self.UseAttrColumn(False)
  1422. else:
  1423. if not self.properties['storeColumn']:
  1424. GError(_("No color column defined. Operation canceled."),
  1425. parent = self)
  1426. return
  1427. self.UseAttrColumn(True)
  1428. return ColorTable.OnApply(self, event)
  1429. class ThematicVectorTable(VectorColorTable):
  1430. def __init__(self, parent, vectorType, **kwargs):
  1431. """Dialog for interactively entering color/size rules
  1432. for vector maps for thematic mapping in nviz"""
  1433. self.vectorType = vectorType
  1434. VectorColorTable.__init__(self, parent = parent, **kwargs)
  1435. self.SetTitle(_("Thematic mapping for vector map in 3D view"))
  1436. def _initLayer(self):
  1437. """Set initial layer when opening dialog"""
  1438. self.inmap = self.parent.GetLayerData(nvizType = 'vector', nameOnly = True)
  1439. self.selectionInput.SetValue(self.inmap)
  1440. self.selectionInput.Disable()
  1441. def OnApply(self, event):
  1442. """Apply selected color table
  1443. :return: True on success otherwise False
  1444. """
  1445. ret = self.CreateColorTable()
  1446. if not ret:
  1447. GMessage(parent = self, message = _("No valid color rules given."))
  1448. data = self.parent.GetLayerData(nvizType = 'vector')
  1449. data['vector']['points']['thematic']['layer'] = int(self.properties['layer'])
  1450. value = None
  1451. if self.properties['storeColumn']:
  1452. value = self.properties['storeColumn']
  1453. if not self.colorTable:
  1454. if self.attributeType == 'color':
  1455. data['vector'][self.vectorType]['thematic']['rgbcolumn'] = value
  1456. else:
  1457. data['vector'][self.vectorType]['thematic']['sizecolumn'] = value
  1458. else:
  1459. if self.attributeType == 'color':
  1460. data['vector'][self.vectorType]['thematic']['rgbcolumn'] = None
  1461. else:
  1462. data['vector'][self.vectorType]['thematic']['sizecolumn'] = None
  1463. data['vector'][self.vectorType]['thematic']['update'] = None
  1464. from nviz.main import haveNviz
  1465. if haveNviz:
  1466. from nviz.mapwindow import wxUpdateProperties
  1467. event = wxUpdateProperties(data = data)
  1468. wx.PostEvent(self.parent.mapWindow, event)
  1469. self.parent.mapWindow.Refresh(False)
  1470. return ret
  1471. class BufferedWindow(wx.Window):
  1472. """A Buffered window class"""
  1473. def __init__(self, parent, id,
  1474. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  1475. Map = None, **kwargs):
  1476. wx.Window.__init__(self, parent, id, style = style, **kwargs)
  1477. self.parent = parent
  1478. self.Map = Map
  1479. # re-render the map from GRASS or just redraw image
  1480. self.render = True
  1481. # indicates whether or not a resize event has taken place
  1482. self.resize = False
  1483. #
  1484. # event bindings
  1485. #
  1486. self.Bind(wx.EVT_PAINT, self.OnPaint)
  1487. self.Bind(wx.EVT_IDLE, self.OnIdle)
  1488. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  1489. #
  1490. # render output objects
  1491. #
  1492. # image file to be rendered
  1493. self.mapfile = None
  1494. # wx.Image object (self.mapfile)
  1495. self.img = None
  1496. self.pdc = wx.PseudoDC()
  1497. # will store an off screen empty bitmap for saving to file
  1498. self._Buffer = None
  1499. # make sure that extents are updated at init
  1500. self.Map.region = self.Map.GetRegion()
  1501. self.Map.SetRegion()
  1502. def Draw(self, pdc, img = None, pdctype = 'image'):
  1503. """Draws preview or clears window"""
  1504. pdc.BeginDrawing()
  1505. Debug.msg (3, "BufferedWindow.Draw(): pdctype=%s" % (pdctype))
  1506. if pdctype == 'clear': # erase the display
  1507. bg = wx.WHITE_BRUSH
  1508. pdc.SetBackground(bg)
  1509. pdc.Clear()
  1510. self.Refresh()
  1511. pdc.EndDrawing()
  1512. return
  1513. if pdctype == 'image' and img:
  1514. bg = wx.TRANSPARENT_BRUSH
  1515. pdc.SetBackground(bg)
  1516. bitmap = wx.BitmapFromImage(img)
  1517. w, h = bitmap.GetSize()
  1518. pdc.DrawBitmap(bitmap, 0, 0, True) # draw the composite map
  1519. pdc.EndDrawing()
  1520. self.Refresh()
  1521. def OnPaint(self, event):
  1522. """Draw pseudo DC to buffer"""
  1523. self._Buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
  1524. dc = wx.BufferedPaintDC(self, self._Buffer)
  1525. # use PrepareDC to set position correctly
  1526. # probably does nothing, removed from wxPython 2.9
  1527. # self.PrepareDC(dc)
  1528. # we need to clear the dc BEFORE calling PrepareDC
  1529. bg = wx.Brush(self.GetBackgroundColour())
  1530. dc.SetBackground(bg)
  1531. dc.Clear()
  1532. # create a clipping rect from our position and size
  1533. # and the Update Region
  1534. rgn = self.GetUpdateRegion()
  1535. r = rgn.GetBox()
  1536. # draw to the dc using the calculated clipping rect
  1537. self.pdc.DrawToDCClipped(dc, r)
  1538. def OnSize(self, event):
  1539. """Init image size to match window size"""
  1540. # set size of the input image
  1541. self.Map.width, self.Map.height = self.GetClientSize()
  1542. # Make new off screen bitmap: this bitmap will always have the
  1543. # current drawing in it, so it can be used to save the image to
  1544. # a file, or whatever.
  1545. self._Buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
  1546. # get the image to be rendered
  1547. self.img = self.GetImage()
  1548. # update map display
  1549. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  1550. self.img = self.img.Scale(self.Map.width, self.Map.height)
  1551. self.render = False
  1552. self.UpdatePreview()
  1553. # re-render image on idle
  1554. self.resize = True
  1555. def OnIdle(self, event):
  1556. """Only re-render a preview image from GRASS during
  1557. idle time instead of multiple times during resizing.
  1558. """
  1559. if self.resize:
  1560. self.render = True
  1561. self.UpdatePreview()
  1562. event.Skip()
  1563. def GetImage(self):
  1564. """Converts files to wx.Image"""
  1565. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  1566. os.path.getsize(self.Map.mapfile):
  1567. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  1568. else:
  1569. img = None
  1570. return img
  1571. def UpdatePreview(self, img = None):
  1572. """Update canvas if window changes geometry"""
  1573. Debug.msg (2, "BufferedWindow.UpdatePreview(%s): render=%s" % (img, self.render))
  1574. oldfont = ""
  1575. oldencoding = ""
  1576. if self.render:
  1577. # extent is taken from current map display
  1578. try:
  1579. self.Map.region = copy.deepcopy(self.parent.parent.GetLayerTree().GetMap().GetCurrentRegion())
  1580. except AttributeError:
  1581. self.Map.region = self.Map.GetRegion()
  1582. # render new map images
  1583. self.mapfile = self.Map.Render(force = self.render)
  1584. self.img = self.GetImage()
  1585. self.resize = False
  1586. if not self.img:
  1587. return
  1588. # paint images to PseudoDC
  1589. self.pdc.Clear()
  1590. self.pdc.RemoveAll()
  1591. # draw map image background
  1592. self.Draw(self.pdc, self.img, pdctype = 'image')
  1593. self.resize = False
  1594. def EraseMap(self):
  1595. """Erase preview"""
  1596. self.Draw(self.pdc, pdctype = 'clear')