dialogs.py 36 KB

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