dialogs.py 37 KB

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