dialogs.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. """
  2. @package gmodeler.dialogs
  3. @brief wxGUI Graphical Modeler - dialogs
  4. Classes:
  5. - dialogs::ModelDataDialog
  6. - dialogs::ModelSearchDialog
  7. - dialogs::ModelRelationDialog
  8. - dialogs::ModelItemDialog
  9. - dialogs::ModelLoopDialog
  10. - dialogs::ModelConditionDialog
  11. - dialogs::ModelListCtrl
  12. - dialogs::ValiableListCtrl
  13. - dialogs::ItemListCtrl
  14. - dialogs::ItemCheckListCtrl
  15. (C) 2010-2016 by the GRASS Development Team
  16. This program is free software under the GNU General Public License
  17. (>=v2). Read the file COPYING that comes with GRASS for details.
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import six
  23. import wx
  24. import wx.lib.mixins.listctrl as listmix
  25. from core import globalvar
  26. from core import utils
  27. from gui_core.widgets import SearchModuleWidget, SimpleValidator
  28. from core.gcmd import GError, EncodeString
  29. from gui_core.dialogs import SimpleDialog, MapLayersDialogForModeler
  30. from gui_core.prompt import GPromptSTC
  31. from gui_core.gselect import Select, ElementSelect
  32. from gmodeler.model import *
  33. from lmgr.menudata import LayerManagerMenuData
  34. from gui_core.wrap import Button, StaticText, StaticBox, TextCtrl, \
  35. Menu, ListCtrl
  36. from grass.script import task as gtask
  37. class ModelDataDialog(SimpleDialog):
  38. """Data item properties dialog"""
  39. def __init__(self, parent, shape, title=_("Data properties")):
  40. self.parent = parent
  41. self.shape = shape
  42. label, etype = self._getLabel()
  43. self.etype = etype
  44. SimpleDialog.__init__(self, parent, title)
  45. self.element = Select(
  46. parent=self.panel,
  47. type=self.shape.GetPrompt(),
  48. validator=SimpleValidator(
  49. callback=self.ValidatorCallback))
  50. if shape.GetValue():
  51. self.element.SetValue(shape.GetValue())
  52. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  53. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  54. if self.etype:
  55. self.typeSelect = ElementSelect(
  56. parent=self.panel,
  57. elements=[
  58. 'raster',
  59. 'raster_3d',
  60. 'vector'],
  61. size=globalvar.DIALOG_GSELECT_SIZE)
  62. self.typeSelect.Bind(wx.EVT_CHOICE, self.OnType)
  63. self.typeSelect.SetSelection(0)
  64. self.element.SetType('raster')
  65. if shape.GetValue():
  66. self.btnOK.Enable()
  67. self._layout()
  68. self.SetMinSize(self.GetSize())
  69. def _getLabel(self):
  70. etype = False
  71. prompt = self.shape.GetPrompt()
  72. if prompt == 'raster':
  73. label = _('Name of raster map:')
  74. elif prompt == 'vector':
  75. label = _('Name of vector map:')
  76. else:
  77. etype = True
  78. label = _('Name of element:')
  79. return label, etype
  80. def _layout(self):
  81. """Do layout"""
  82. if self.etype:
  83. self.dataSizer.Add(
  84. StaticText(
  85. parent=self.panel,
  86. id=wx.ID_ANY,
  87. label=_("Type of element:")),
  88. proportion=0,
  89. flag=wx.ALL,
  90. border=1)
  91. self.dataSizer.Add(self.typeSelect,
  92. proportion=0, flag=wx.ALL, border=1)
  93. self.dataSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  94. label=_("Name of element:")),
  95. proportion=0, flag=wx.ALL, border=1)
  96. self.dataSizer.Add(self.element, proportion=0,
  97. flag=wx.EXPAND | wx.ALL, border=1)
  98. self.panel.SetSizer(self.sizer)
  99. self.sizer.Fit(self)
  100. def GetType(self):
  101. """Get element type"""
  102. if not self.etype:
  103. return
  104. return self.element.tcp.GetType()
  105. def OnType(self, event):
  106. """Select element type"""
  107. evalue = self.typeSelect.GetValue(event.GetString())
  108. self.element.SetType(evalue)
  109. def OnOK(self, event):
  110. """Ok pressed"""
  111. self.shape.SetValue(self.element.GetValue())
  112. if self.etype:
  113. elem = self.GetType()
  114. if elem == 'raster':
  115. self.shape.SetPrompt('raster')
  116. elif elem == 'vector':
  117. self.shape.SetPrompt('vector')
  118. elif elem == 'raster_3d':
  119. self.shape.SetPrompt('raster_3d')
  120. self.parent.canvas.Refresh()
  121. self.parent.SetStatusText('', 0)
  122. self.shape.SetPropDialog(None)
  123. if self.IsModal():
  124. event.Skip()
  125. else:
  126. self.Destroy()
  127. def OnCancel(self, event):
  128. """Cancel pressed"""
  129. self.shape.SetPropDialog(None)
  130. if self.IsModal():
  131. event.Skip()
  132. else:
  133. self.Destroy()
  134. class ModelSearchDialog(wx.Dialog):
  135. def __init__(self, parent, title=_("Add GRASS command to the model"),
  136. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  137. """Graphical modeler module search window
  138. :param parent: parent window
  139. :param id: window id
  140. :param title: window title
  141. :param kwargs: wx.Dialogs' arguments
  142. """
  143. self.parent = parent
  144. wx.Dialog.__init__(
  145. self,
  146. parent=parent,
  147. id=wx.ID_ANY,
  148. title=title,
  149. **kwargs)
  150. self.SetName("ModelerDialog")
  151. self.SetIcon(
  152. wx.Icon(
  153. os.path.join(
  154. globalvar.ICONDIR,
  155. 'grass.ico'),
  156. wx.BITMAP_TYPE_ICO))
  157. self._command = None
  158. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  159. self.cmdBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  160. label=" %s " % _("Command"))
  161. self.labelBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  162. label=" %s " % _("Label and comment"))
  163. # menu data for search widget and prompt
  164. menuModel = LayerManagerMenuData()
  165. self.cmd_prompt = GPromptSTC(
  166. parent=self, menuModel=menuModel.GetModel())
  167. self.cmd_prompt.promptRunCmd.connect(self.OnCommand)
  168. self.cmd_prompt.commandSelected.connect(
  169. lambda command: self.label.SetValue(command))
  170. self.search = SearchModuleWidget(parent=self.panel,
  171. model=menuModel.GetModel(),
  172. showTip=True)
  173. self.search.moduleSelected.connect(
  174. lambda name: self.cmd_prompt.SetTextAndFocus(name + ' '))
  175. wx.CallAfter(self.cmd_prompt.SetFocus)
  176. self.label = TextCtrl(parent=self.panel, id=wx.ID_ANY)
  177. self.comment = TextCtrl(
  178. parent=self.panel,
  179. id=wx.ID_ANY,
  180. style=wx.TE_MULTILINE)
  181. self.btnCancel = Button(self.panel, wx.ID_CANCEL)
  182. self.btnOk = Button(self.panel, wx.ID_OK)
  183. self.btnOk.SetDefault()
  184. self.Bind(wx.EVT_BUTTON, self.OnOk, self.btnOk)
  185. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  186. self._layout()
  187. self.SetSize((500, -1))
  188. def _layout(self):
  189. cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
  190. cmdSizer.Add(self.cmd_prompt, proportion=1,
  191. flag=wx.EXPAND)
  192. labelSizer = wx.StaticBoxSizer(self.labelBox, wx.VERTICAL)
  193. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  194. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  195. label=_("Label:")),
  196. flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  197. gridSizer.Add(self.label, pos=(0, 1), flag=wx.EXPAND)
  198. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  199. label=_("Comment:")),
  200. flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  201. gridSizer.Add(self.comment, pos=(1, 1), flag=wx.EXPAND)
  202. gridSizer.AddGrowableRow(1)
  203. gridSizer.AddGrowableCol(1)
  204. labelSizer.Add(gridSizer, proportion=1, flag=wx.EXPAND)
  205. btnSizer = wx.StdDialogButtonSizer()
  206. btnSizer.AddButton(self.btnCancel)
  207. btnSizer.AddButton(self.btnOk)
  208. btnSizer.Realize()
  209. mainSizer = wx.BoxSizer(wx.VERTICAL)
  210. mainSizer.Add(self.search, proportion=0,
  211. flag=wx.EXPAND | wx.ALL, border=3)
  212. mainSizer.Add(cmdSizer, proportion=1,
  213. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  214. mainSizer.Add(labelSizer, proportion=1,
  215. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  216. mainSizer.Add(btnSizer, proportion=0,
  217. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  218. self.panel.SetSizer(mainSizer)
  219. mainSizer.Fit(self)
  220. self.Layout()
  221. def GetPanel(self):
  222. """Get dialog panel"""
  223. return self.panel
  224. def _getCmd(self):
  225. line = self.cmd_prompt.GetCurLine()[0].strip()
  226. if len(line) == 0:
  227. cmd = list()
  228. else:
  229. try:
  230. cmd = utils.split(str(line))
  231. except UnicodeError:
  232. cmd = utils.split(EncodeString((line)))
  233. return cmd
  234. def GetCmd(self):
  235. """Get command"""
  236. return self._command
  237. def GetLabel(self):
  238. """Get label and comment"""
  239. return self.label.GetValue(), self.comment.GetValue()
  240. def ValidateCmd(self, cmd):
  241. if len(cmd) < 1:
  242. GError(parent=self,
  243. message=_("Command not defined.\n\n"
  244. "Unable to add new action to the model."))
  245. return False
  246. if cmd[0] not in globalvar.grassCmd:
  247. GError(
  248. parent=self, message=_(
  249. "'%s' is not a GRASS module.\n\n"
  250. "Unable to add new action to the model.") %
  251. cmd[0])
  252. return False
  253. return True
  254. def OnCommand(self, cmd):
  255. """Command in prompt confirmed"""
  256. if self.ValidateCmd(cmd):
  257. self._command = cmd
  258. self.EndModal(wx.ID_OK)
  259. def OnOk(self, event):
  260. """Button 'OK' pressed"""
  261. cmd = self._getCmd()
  262. if self.ValidateCmd(cmd):
  263. self._command = cmd
  264. self.EndModal(wx.ID_OK)
  265. def OnCancel(self, event):
  266. """Cancel pressed, close window"""
  267. self.Hide()
  268. def Reset(self):
  269. """Reset dialog"""
  270. self.search.Reset()
  271. self.label.SetValue('')
  272. self.comment.SetValue('')
  273. self.cmd_prompt.OnCmdErase(None)
  274. self.cmd_prompt.SetFocus()
  275. class ModelRelationDialog(wx.Dialog):
  276. """Relation properties dialog"""
  277. def __init__(self, parent, shape, id=wx.ID_ANY,
  278. title=_("Relation properties"),
  279. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  280. self.parent = parent
  281. self.shape = shape
  282. options = self._getOptions()
  283. if not options:
  284. self.valid = False
  285. return
  286. self.valid = True
  287. wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
  288. self.SetIcon(
  289. wx.Icon(
  290. os.path.join(
  291. globalvar.ICONDIR,
  292. 'grass.ico'),
  293. wx.BITMAP_TYPE_ICO))
  294. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  295. self.fromBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  296. label=" %s " % _("From"))
  297. self.toBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  298. label=" %s " % _("To"))
  299. self.option = wx.ComboBox(parent=self.panel, id=wx.ID_ANY,
  300. style=wx.CB_READONLY,
  301. choices=options)
  302. self.option.Bind(wx.EVT_COMBOBOX, self.OnOption)
  303. self.btnCancel = Button(self.panel, wx.ID_CANCEL)
  304. self.btnOk = Button(self.panel, wx.ID_OK)
  305. self.btnOk.Enable(False)
  306. self._layout()
  307. def _layout(self):
  308. mainSizer = wx.BoxSizer(wx.VERTICAL)
  309. fromSizer = wx.StaticBoxSizer(self.fromBox, wx.VERTICAL)
  310. self._layoutShape(shape=self.shape.GetFrom(), sizer=fromSizer)
  311. toSizer = wx.StaticBoxSizer(self.toBox, wx.VERTICAL)
  312. self._layoutShape(shape=self.shape.GetTo(), sizer=toSizer)
  313. btnSizer = wx.StdDialogButtonSizer()
  314. btnSizer.AddButton(self.btnCancel)
  315. btnSizer.AddButton(self.btnOk)
  316. btnSizer.Realize()
  317. mainSizer.Add(fromSizer, proportion=0,
  318. flag=wx.EXPAND | wx.ALL, border=5)
  319. mainSizer.Add(toSizer, proportion=0, flag=wx.EXPAND |
  320. wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  321. mainSizer.Add(btnSizer, proportion=0,
  322. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  323. self.panel.SetSizer(mainSizer)
  324. mainSizer.Fit(self.panel)
  325. self.Layout()
  326. self.SetSize(self.GetBestSize())
  327. def _layoutShape(self, shape, sizer):
  328. if isinstance(shape, ModelData):
  329. sizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  330. label=_("Data: %s") % shape.GetLog()),
  331. proportion=1, flag=wx.EXPAND | wx.ALL,
  332. border=5)
  333. elif isinstance(shape, ModelAction):
  334. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  335. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  336. label=_("Command:")),
  337. pos=(0, 0))
  338. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  339. label=shape.GetLabel()),
  340. pos=(0, 1))
  341. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  342. label=_("Option:")),
  343. flag=wx.ALIGN_CENTER_VERTICAL,
  344. pos=(1, 0))
  345. gridSizer.Add(self.option,
  346. pos=(1, 1))
  347. sizer.Add(gridSizer,
  348. proportion=1, flag=wx.EXPAND | wx.ALL,
  349. border=5)
  350. def _getOptions(self):
  351. """Get relevant options"""
  352. items = []
  353. fromShape = self.shape.GetFrom()
  354. if not isinstance(fromShape, ModelData):
  355. GError(parent=self.parent,
  356. message=_("Relation doesn't start with data item.\n"
  357. "Unable to add relation."))
  358. return items
  359. toShape = self.shape.GetTo()
  360. if not isinstance(toShape, ModelAction):
  361. GError(parent=self.parent,
  362. message=_("Relation doesn't point to GRASS command.\n"
  363. "Unable to add relation."))
  364. return items
  365. prompt = fromShape.GetPrompt()
  366. task = toShape.GetTask()
  367. for p in task.get_options()['params']:
  368. if p.get('prompt', '') == prompt and \
  369. 'name' in p:
  370. items.append(p['name'])
  371. if not items:
  372. GError(parent=self.parent,
  373. message=_("No relevant option found.\n"
  374. "Unable to add relation."))
  375. return items
  376. def GetOption(self):
  377. """Get selected option"""
  378. return self.option.GetStringSelection()
  379. def IsValid(self):
  380. """Check if relation is valid"""
  381. return self.valid
  382. def OnOption(self, event):
  383. """Set option"""
  384. if event.GetString():
  385. self.btnOk.Enable()
  386. else:
  387. self.btnOk.Enable(False)
  388. class ModelItemDialog(wx.Dialog):
  389. """Abstract item properties dialog"""
  390. def __init__(self, parent, shape, title, id=wx.ID_ANY,
  391. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  392. self.parent = parent
  393. self.shape = shape
  394. wx.Dialog.__init__(
  395. self,
  396. parent,
  397. id,
  398. title=title,
  399. style=style,
  400. **kwargs)
  401. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  402. self.condBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  403. label=" %s " % _("Condition"))
  404. self.condText = TextCtrl(parent=self.panel, id=wx.ID_ANY,
  405. value=shape.GetLabel())
  406. self.itemList = ItemCheckListCtrl(parent=self.panel,
  407. columns=[_("Label"),
  408. _("Command")],
  409. shape=shape,
  410. frame=parent)
  411. self.itemList.Populate(self.parent.GetModel().GetItems())
  412. self.btnCancel = Button(parent=self.panel, id=wx.ID_CANCEL)
  413. self.btnOk = Button(parent=self.panel, id=wx.ID_OK)
  414. self.btnOk.SetDefault()
  415. def _layout(self):
  416. """Do layout (virtual method)"""
  417. pass
  418. def GetCondition(self):
  419. """Get loop condition"""
  420. return self.condText.GetValue()
  421. class ModelLoopDialog(ModelItemDialog):
  422. """Loop properties dialog"""
  423. def __init__(self, parent, shape, id=wx.ID_ANY, title=_("Loop properties"),
  424. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  425. ModelItemDialog.__init__(self, parent, shape, title,
  426. style=style, **kwargs)
  427. self.listBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  428. label=" %s " % _("List of items in loop"))
  429. self.btnSeries = Button(parent=self.panel, id=wx.ID_ANY,
  430. label=_("Series"))
  431. self.btnSeries.SetToolTip(
  432. _("Define map series as condition for the loop"))
  433. self.btnSeries.Bind(wx.EVT_BUTTON, self.OnSeries)
  434. self._layout()
  435. self.SetMinSize(self.GetSize())
  436. self.SetSize((500, 400))
  437. def _layout(self):
  438. """Do layout"""
  439. sizer = wx.BoxSizer(wx.VERTICAL)
  440. condSizer = wx.StaticBoxSizer(self.condBox, wx.HORIZONTAL)
  441. condSizer.Add(self.condText, proportion=1,
  442. flag=wx.ALL, border=3)
  443. condSizer.Add(self.btnSeries, proportion=0,
  444. flag=wx.EXPAND)
  445. listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
  446. listSizer.Add(self.itemList, proportion=1,
  447. flag=wx.EXPAND | wx.ALL, border=3)
  448. btnSizer = wx.StdDialogButtonSizer()
  449. btnSizer.AddButton(self.btnCancel)
  450. btnSizer.AddButton(self.btnOk)
  451. btnSizer.Realize()
  452. sizer.Add(condSizer, proportion=0,
  453. flag=wx.EXPAND | wx.ALL, border=3)
  454. sizer.Add(listSizer, proportion=1,
  455. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  456. sizer.Add(btnSizer, proportion=0,
  457. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  458. self.panel.SetSizer(sizer)
  459. sizer.Fit(self.panel)
  460. self.Layout()
  461. def GetItems(self):
  462. """Get list of selected actions"""
  463. return self.itemList.GetItems()
  464. def OnSeries(self, event):
  465. """Define map series as condition"""
  466. dialog = MapLayersDialogForModeler(
  467. parent=self, title=_("Define series of maps"))
  468. if dialog.ShowModal() != wx.ID_OK:
  469. dialog.Destroy()
  470. return
  471. cond = dialog.GetDSeries()
  472. if not cond:
  473. cond = 'map in {}'.format(list(map(str, dialog.GetMapLayers())))
  474. self.condText.SetValue(cond)
  475. dialog.Destroy()
  476. class ModelConditionDialog(ModelItemDialog):
  477. """Condition properties dialog"""
  478. def __init__(self, parent, shape, id=wx.ID_ANY,
  479. title=_("If-else properties"),
  480. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  481. ModelItemDialog.__init__(self, parent, shape, title,
  482. style=style, **kwargs)
  483. self.listBoxIf = StaticBox(
  484. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  485. _("List of items in 'if' block"))
  486. self.itemListIf = self.itemList
  487. self.itemListIf.SetName('IfBlockList')
  488. self.listBoxElse = StaticBox(
  489. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  490. _("List of items in 'else' block"))
  491. self.itemListElse = ItemCheckListCtrl(parent=self.panel,
  492. columns=[_("Label"),
  493. _("Command")],
  494. shape=shape, frame=parent)
  495. self.itemListElse.SetName('ElseBlockList')
  496. self.itemListElse.Populate(self.parent.GetModel().GetItems())
  497. self._layout()
  498. self.SetMinSize(self.GetSize())
  499. self.SetSize((500, 400))
  500. def _layout(self):
  501. """Do layout"""
  502. sizer = wx.BoxSizer(wx.VERTICAL)
  503. condSizer = wx.StaticBoxSizer(self.condBox, wx.VERTICAL)
  504. condSizer.Add(self.condText, proportion=1,
  505. flag=wx.EXPAND)
  506. listIfSizer = wx.StaticBoxSizer(self.listBoxIf, wx.VERTICAL)
  507. listIfSizer.Add(self.itemListIf, proportion=1,
  508. flag=wx.EXPAND)
  509. listElseSizer = wx.StaticBoxSizer(self.listBoxElse, wx.VERTICAL)
  510. listElseSizer.Add(self.itemListElse, proportion=1,
  511. flag=wx.EXPAND)
  512. btnSizer = wx.StdDialogButtonSizer()
  513. btnSizer.AddButton(self.btnCancel)
  514. btnSizer.AddButton(self.btnOk)
  515. btnSizer.Realize()
  516. sizer.Add(condSizer, proportion=0,
  517. flag=wx.EXPAND | wx.ALL, border=3)
  518. sizer.Add(listIfSizer, proportion=1,
  519. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  520. sizer.Add(listElseSizer, proportion=1,
  521. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  522. sizer.Add(btnSizer, proportion=0,
  523. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  524. self.panel.SetSizer(sizer)
  525. sizer.Fit(self.panel)
  526. self.Layout()
  527. def OnCheckItemIf(self, index, flag):
  528. """Item in if-block checked/unchecked"""
  529. if flag is False:
  530. return
  531. aId = int(self.itemListIf.GetItem(index, 0).GetText())
  532. if aId in self.itemListElse.GetItems()['checked']:
  533. self.itemListElse.CheckItemById(aId, False)
  534. def OnCheckItemElse(self, index, flag):
  535. """Item in else-block checked/unchecked"""
  536. if flag is False:
  537. return
  538. aId = int(self.itemListElse.GetItem(index, 0).GetText())
  539. if aId in self.itemListIf.GetItems()['checked']:
  540. self.itemListIf.CheckItemById(aId, False)
  541. def GetItems(self):
  542. """Get items"""
  543. return {'if': self.itemListIf.GetItems(),
  544. 'else': self.itemListElse.GetItems()}
  545. class ModelListCtrl(ListCtrl,
  546. listmix.ListCtrlAutoWidthMixin,
  547. listmix.TextEditMixin):
  548. def __init__(
  549. self, parent, columns, frame, id=wx.ID_ANY, columnsNotEditable=[],
  550. style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_HRULES | wx.LC_VRULES, **
  551. kwargs):
  552. """List of model variables"""
  553. self.parent = parent
  554. self.columns = columns
  555. self.shape = None
  556. self.frame = frame
  557. self.columnNotEditable = columnsNotEditable
  558. ListCtrl.__init__(self, parent, id=id, style=style, **kwargs)
  559. listmix.ListCtrlAutoWidthMixin.__init__(self)
  560. listmix.TextEditMixin.__init__(self)
  561. i = 0
  562. for col in columns:
  563. self.InsertColumn(i, col)
  564. self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER)
  565. i += 1
  566. self.itemDataMap = {} # requested by sorter
  567. self.itemCount = 0
  568. self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit)
  569. self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit)
  570. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
  571. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp) # wxMSW
  572. self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) # wxGTK
  573. def OnBeginEdit(self, event):
  574. """Editing of item started"""
  575. if self.columnNotEditable and event.m_col in self.columnNotEditable:
  576. event.Veto()
  577. self.SetItemState(
  578. event.m_itemIndex,
  579. wx.LIST_STATE_SELECTED,
  580. wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
  581. else:
  582. event.Allow()
  583. def OnEndEdit(self, event):
  584. """Finish editing of item"""
  585. pass
  586. def GetListCtrl(self):
  587. """Used by ColumnSorterMixin"""
  588. return self
  589. def OnColClick(self, event):
  590. """Click on column header (order by)"""
  591. event.Skip()
  592. class VariableListCtrl(ModelListCtrl):
  593. def __init__(self, parent, columns, **kwargs):
  594. """List of model variables"""
  595. ModelListCtrl.__init__(self, parent, columns, **kwargs)
  596. self.SetColumnWidth(2, 200) # default value
  597. def GetData(self):
  598. """Get list data"""
  599. return self.itemDataMap
  600. def Populate(self, data):
  601. """Populate the list"""
  602. self.itemDataMap = dict()
  603. i = 0
  604. for name, values in six.iteritems(data):
  605. self.itemDataMap[i] = [name, values['type'],
  606. values.get('value', ''),
  607. values.get('description', '')]
  608. i += 1
  609. self.itemCount = len(self.itemDataMap.keys())
  610. self.DeleteAllItems()
  611. i = 0
  612. for name, vtype, value, desc in six.itervalues(self.itemDataMap):
  613. index = self.InsertStringItem(i, name)
  614. self.SetStringItem(index, 0, name)
  615. self.SetStringItem(index, 1, vtype)
  616. self.SetStringItem(index, 2, value)
  617. self.SetStringItem(index, 3, desc)
  618. self.SetItemData(index, i)
  619. i += 1
  620. def Append(self, name, vtype, value, desc):
  621. """Append new item to the list
  622. :return: None on success
  623. :return: error string
  624. """
  625. for iname, ivtype, ivalue, idesc in six.itervalues(self.itemDataMap):
  626. if iname == name:
  627. return _("Variable <%s> already exists in the model. "
  628. "Adding variable failed.") % name
  629. index = self.InsertStringItem(self.GetItemCount(), name)
  630. self.SetStringItem(index, 0, name)
  631. self.SetStringItem(index, 1, vtype)
  632. self.SetStringItem(index, 2, value)
  633. self.SetStringItem(index, 3, desc)
  634. self.SetItemData(index, self.itemCount)
  635. self.itemDataMap[self.itemCount] = [name, vtype, value, desc]
  636. self.itemCount += 1
  637. return None
  638. def OnRemove(self, event):
  639. """Remove selected variable(s) from the model"""
  640. item = self.GetFirstSelected()
  641. while item != -1:
  642. self.DeleteItem(item)
  643. del self.itemDataMap[item]
  644. item = self.GetFirstSelected()
  645. self.parent.UpdateModelVariables()
  646. event.Skip()
  647. def OnRemoveAll(self, event):
  648. """Remove all variable(s) from the model"""
  649. dlg = wx.MessageBox(
  650. parent=self,
  651. message=_(
  652. "Do you want to delete all variables from "
  653. "the model?"),
  654. caption=_("Delete variables"),
  655. style=wx.YES_NO | wx.CENTRE)
  656. if dlg != wx.YES:
  657. return
  658. self.DeleteAllItems()
  659. self.itemDataMap = dict()
  660. self.parent.UpdateModelVariables()
  661. def OnEndEdit(self, event):
  662. """Finish editing of item"""
  663. itemIndex = event.GetIndex()
  664. columnIndex = event.GetColumn()
  665. nameOld = self.GetItem(itemIndex, 0).GetText()
  666. if columnIndex == 0: # TODO
  667. event.Veto()
  668. self.itemDataMap[itemIndex][columnIndex] = event.GetText()
  669. self.parent.UpdateModelVariables()
  670. def OnReload(self, event):
  671. """Reload list of variables"""
  672. self.Populate(self.parent.parent.GetModel().GetVariables())
  673. def OnRightUp(self, event):
  674. """Mouse right button up"""
  675. if not hasattr(self, "popupID1"):
  676. self.popupID1 = wx.NewId()
  677. self.popupID2 = wx.NewId()
  678. self.popupID3 = wx.NewId()
  679. self.Bind(wx.EVT_MENU, self.OnRemove, id=self.popupID1)
  680. self.Bind(wx.EVT_MENU, self.OnRemoveAll, id=self.popupID2)
  681. self.Bind(wx.EVT_MENU, self.OnReload, id=self.popupID3)
  682. # generate popup-menu
  683. menu = Menu()
  684. menu.Append(self.popupID1, _("Delete selected"))
  685. menu.Append(self.popupID2, _("Delete all"))
  686. if self.GetFirstSelected() == -1:
  687. menu.Enable(self.popupID1, False)
  688. menu.Enable(self.popupID2, False)
  689. menu.AppendSeparator()
  690. menu.Append(self.popupID3, _("Reload"))
  691. self.PopupMenu(menu)
  692. menu.Destroy()
  693. class ItemListCtrl(ModelListCtrl):
  694. def __init__(self, parent, columns, frame, disablePopup=False, **kwargs):
  695. """List of model actions"""
  696. self.disablePopup = disablePopup
  697. ModelListCtrl.__init__(self, parent, columns, frame, **kwargs)
  698. self.itemIdMap = list()
  699. self.SetColumnWidth(0, 100)
  700. self.SetColumnWidth(1, 75)
  701. if len(self.columns) >= 3:
  702. self.SetColumnWidth(2, 100)
  703. def GetData(self):
  704. """Get list data"""
  705. return self.itemDataMap
  706. def Populate(self, data):
  707. """Populate the list"""
  708. self.itemDataMap = dict()
  709. self.itemIdMap = list()
  710. if self.shape:
  711. items = self.frame.GetModel().GetItems(objType=ModelAction)
  712. if isinstance(self.shape, ModelCondition):
  713. if self.GetLabel() == 'ElseBlockList':
  714. shapeItems = map(
  715. lambda x: x.GetId(),
  716. self.shape.GetItems(items)['else'])
  717. else:
  718. shapeItems = map(
  719. lambda x: x.GetId(),
  720. self.shape.GetItems(items)['if'])
  721. else:
  722. shapeItems = map(
  723. lambda x: x.GetId(),
  724. self.shape.GetItems(items))
  725. else:
  726. shapeItems = list()
  727. i = 0
  728. if len(self.columns) == 2: # ItemCheckList
  729. checked = list()
  730. for action in data:
  731. if isinstance(action, ModelData) or \
  732. action == self.shape:
  733. continue
  734. self.itemIdMap.append(action.GetId())
  735. if len(self.columns) == 2:
  736. self.itemDataMap[i] = [action.GetLabel(),
  737. action.GetLog()]
  738. aId = action.GetBlockId()
  739. if action.GetId() in shapeItems:
  740. checked.append(aId)
  741. else:
  742. checked.append(None)
  743. else:
  744. bId = action.GetBlockId()
  745. if not bId:
  746. bId = _('No')
  747. else:
  748. bId = _("Yes")
  749. options = action.GetParameterizedParams()
  750. params = []
  751. for f in options['flags']:
  752. params.append('-{0}'.format(f['name']))
  753. for p in options['params']:
  754. params.append(p['name'])
  755. self.itemDataMap[i] = [action.GetLabel(),
  756. bId,
  757. ','.join(params),
  758. action.GetLog()]
  759. i += 1
  760. self.itemCount = len(self.itemDataMap.keys())
  761. self.DeleteAllItems()
  762. i = 0
  763. if len(self.columns) == 2:
  764. for name, desc in six.itervalues(self.itemDataMap):
  765. index = self.InsertStringItem(i, str(i))
  766. self.SetStringItem(index, 0, name)
  767. self.SetStringItem(index, 1, desc)
  768. self.SetItemData(index, i)
  769. if checked[i]:
  770. self.CheckItem(index, True)
  771. i += 1
  772. else:
  773. for name, inloop, param, desc in six.itervalues(self.itemDataMap):
  774. index = self.InsertStringItem(i, str(i))
  775. self.SetStringItem(index, 0, name)
  776. self.SetStringItem(index, 1, inloop)
  777. self.SetStringItem(index, 2, param)
  778. self.SetStringItem(index, 3, desc)
  779. self.SetItemData(index, i)
  780. i += 1
  781. def OnRemove(self, event):
  782. """Remove selected action(s) from the model"""
  783. model = self.frame.GetModel()
  784. canvas = self.frame.GetCanvas()
  785. item = self.GetFirstSelected()
  786. while item != -1:
  787. self.DeleteItem(item)
  788. del self.itemDataMap[item]
  789. action = model.GetItem(item + 1) # action indices starts at 1
  790. if not action:
  791. item = self.GetFirstSelected()
  792. continue
  793. canvas.RemoveShapes([action])
  794. self.frame.ModelChanged()
  795. item = self.GetFirstSelected()
  796. canvas.Refresh()
  797. event.Skip()
  798. def OnEndEdit(self, event):
  799. """Finish editing of item"""
  800. itemIndex = event.GetIndex()
  801. columnIndex = event.GetColumn()
  802. self.itemDataMap[itemIndex][columnIndex] = event.GetText()
  803. action = self.frame.GetModel().GetItem(itemIndex + 1)
  804. if not action:
  805. event.Veto()
  806. return
  807. action.SetLabel(label=event.GetText())
  808. self.frame.ModelChanged()
  809. def OnReload(self, event=None):
  810. """Reload list of actions"""
  811. self.Populate(self.frame.GetModel().GetItems(objType=ModelAction))
  812. def OnRightUp(self, event):
  813. """Mouse right button up"""
  814. if self.disablePopup:
  815. return
  816. if not hasattr(self, "popupId"):
  817. self.popupID = dict()
  818. self.popupID['remove'] = wx.NewId()
  819. self.popupID['reload'] = wx.NewId()
  820. self.Bind(wx.EVT_MENU, self.OnRemove, id=self.popupID['remove'])
  821. self.Bind(wx.EVT_MENU, self.OnReload, id=self.popupID['reload'])
  822. # generate popup-menu
  823. menu = Menu()
  824. menu.Append(self.popupID['remove'], _("Delete selected"))
  825. if self.GetFirstSelected() == -1:
  826. menu.Enable(self.popupID['remove'], False)
  827. menu.AppendSeparator()
  828. menu.Append(self.popupID['reload'], _("Reload"))
  829. self.PopupMenu(menu)
  830. menu.Destroy()
  831. def MoveItems(self, items, up):
  832. """Move items in the list
  833. :param items: list of items to move
  834. :param up: True to move up otherwise down
  835. """
  836. if len(items) < 1:
  837. return
  838. if items[0] == 0 and up:
  839. del items[0]
  840. if len(items) < 1:
  841. return
  842. if items[-1] == len(self.itemDataMap.keys()) - 1 and not up:
  843. del items[-1]
  844. if len(items) < 1:
  845. return
  846. model = self.frame.GetModel()
  847. modelActions = model.GetItems(objType=ModelAction)
  848. idxList = dict()
  849. itemsToSelect = list()
  850. for i in items:
  851. if up:
  852. idx = i - 1
  853. else:
  854. idx = i + 1
  855. itemsToSelect.append(idx)
  856. idxList[
  857. model.GetItemIndex(
  858. modelActions[i])] = model.GetItemIndex(
  859. modelActions[idx])
  860. # reorganize model items
  861. model.ReorderItems(idxList)
  862. model.Normalize()
  863. self.Populate(model.GetItems(objType=ModelAction))
  864. # re-selected originaly selected item
  865. for item in itemsToSelect:
  866. self.SetItemState(
  867. item,
  868. wx.LIST_STATE_SELECTED,
  869. wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
  870. class ItemCheckListCtrl(ItemListCtrl, listmix.CheckListCtrlMixin):
  871. def __init__(self, parent, shape, columns, frame, **kwargs):
  872. self.parent = parent
  873. self.frame = frame
  874. ItemListCtrl.__init__(self, parent, columns, frame,
  875. disablePopup=True, **kwargs)
  876. listmix.CheckListCtrlMixin.__init__(self)
  877. self.SetColumnWidth(0, 100)
  878. self.shape = shape
  879. def OnBeginEdit(self, event):
  880. """Disable editing"""
  881. event.Veto()
  882. def OnCheckItem(self, index, flag):
  883. """Item checked/unchecked"""
  884. name = self.GetLabel()
  885. if name == 'IfBlockList' and self.window:
  886. self.window.OnCheckItemIf(index, flag)
  887. elif name == 'ElseBlockList' and self.window:
  888. self.window.OnCheckItemElse(index, flag)
  889. def GetItems(self):
  890. """Get list of selected actions"""
  891. ids = {'checked': list(),
  892. 'unchecked': list()}
  893. # action ids start at 1
  894. for i in range(self.GetItemCount()):
  895. if self.IsChecked(i):
  896. ids['checked'].append(self.itemIdMap[i])
  897. else:
  898. ids['unchecked'].append(self.itemIdMap[i])
  899. return ids
  900. def CheckItemById(self, aId, flag):
  901. """Check/uncheck given item by id"""
  902. for i in range(self.GetItemCount()):
  903. iId = int(self.GetItem(i, 0).GetText())
  904. if iId == aId:
  905. self.CheckItem(i, flag)
  906. break