dialogs.py 38 KB

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