dialogs.py 38 KB

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