colorrules.py 74 KB

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