colorrules.py 74 KB

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