colorrules.py 71 KB

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