dialogs.py 38 KB

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