dialogs.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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 core.utils import _
  28. from gui_core.widgets import SearchModuleWidget, SimpleValidator
  29. from core.gcmd import GError, EncodeString
  30. from gui_core.dialogs import SimpleDialog, MapLayersDialogForModeler
  31. from gui_core.prompt import GPromptSTC
  32. from gui_core.gselect import Select, ElementSelect
  33. from gmodeler.model import *
  34. from lmgr.menudata import LayerManagerMenuData
  35. from gui_core.wrap import Button, StaticText, StaticBox, TextCtrl, \
  36. Menu
  37. from grass.script import task as gtask
  38. class ModelDataDialog(SimpleDialog):
  39. """Data item properties dialog"""
  40. def __init__(self, parent, shape, title=_("Data properties")):
  41. self.parent = parent
  42. self.shape = shape
  43. label, etype = self._getLabel()
  44. self.etype = etype
  45. SimpleDialog.__init__(self, parent, title)
  46. self.element = Select(
  47. parent=self.panel,
  48. type=self.shape.GetPrompt(),
  49. validator=SimpleValidator(
  50. callback=self.ValidatorCallback))
  51. if shape.GetValue():
  52. self.element.SetValue(shape.GetValue())
  53. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  54. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  55. if self.etype:
  56. self.typeSelect = ElementSelect(
  57. parent=self.panel,
  58. elements=[
  59. 'raster',
  60. 'raster_3d',
  61. 'vector'],
  62. size=globalvar.DIALOG_GSELECT_SIZE)
  63. self.typeSelect.Bind(wx.EVT_CHOICE, self.OnType)
  64. self.typeSelect.SetSelection(0)
  65. self.element.SetType('raster')
  66. if shape.GetValue():
  67. self.btnOK.Enable()
  68. self._layout()
  69. self.SetMinSize(self.GetSize())
  70. def _getLabel(self):
  71. etype = False
  72. prompt = self.shape.GetPrompt()
  73. if prompt == 'raster':
  74. label = _('Name of raster map:')
  75. elif prompt == 'vector':
  76. label = _('Name of vector map:')
  77. else:
  78. etype = True
  79. label = _('Name of element:')
  80. return label, etype
  81. def _layout(self):
  82. """Do layout"""
  83. if self.etype:
  84. self.dataSizer.Add(
  85. StaticText(
  86. parent=self.panel,
  87. id=wx.ID_ANY,
  88. label=_("Type of element:")),
  89. proportion=0,
  90. flag=wx.ALL,
  91. border=1)
  92. self.dataSizer.Add(self.typeSelect,
  93. proportion=0, flag=wx.ALL, border=1)
  94. self.dataSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  95. label=_("Name of element:")),
  96. proportion=0, flag=wx.ALL, border=1)
  97. self.dataSizer.Add(self.element, proportion=0,
  98. flag=wx.EXPAND | wx.ALL, border=1)
  99. self.panel.SetSizer(self.sizer)
  100. self.sizer.Fit(self)
  101. def GetType(self):
  102. """Get element type"""
  103. if not self.etype:
  104. return
  105. return self.element.tcp.GetType()
  106. def OnType(self, event):
  107. """Select element type"""
  108. evalue = self.typeSelect.GetValue(event.GetString())
  109. self.element.SetType(evalue)
  110. def OnOK(self, event):
  111. """Ok pressed"""
  112. self.shape.SetValue(self.element.GetValue())
  113. if self.etype:
  114. elem = self.GetType()
  115. if elem == 'raster':
  116. self.shape.SetPrompt('raster')
  117. elif elem == 'vector':
  118. self.shape.SetPrompt('vector')
  119. elif elem == 'raster_3d':
  120. self.shape.SetPrompt('raster_3d')
  121. self.parent.canvas.Refresh()
  122. self.parent.SetStatusText('', 0)
  123. self.shape.SetPropDialog(None)
  124. if self.IsModal():
  125. event.Skip()
  126. else:
  127. self.Destroy()
  128. def OnCancel(self, event):
  129. """Cancel pressed"""
  130. self.shape.SetPropDialog(None)
  131. if self.IsModal():
  132. event.Skip()
  133. else:
  134. self.Destroy()
  135. class ModelSearchDialog(wx.Dialog):
  136. def __init__(self, parent, title=_("Add GRASS command to the model"),
  137. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  138. """Graphical modeler module search window
  139. :param parent: parent window
  140. :param id: window id
  141. :param title: window title
  142. :param kwargs: wx.Dialogs' arguments
  143. """
  144. self.parent = parent
  145. wx.Dialog.__init__(
  146. self,
  147. parent=parent,
  148. id=wx.ID_ANY,
  149. title=title,
  150. **kwargs)
  151. self.SetName("ModelerDialog")
  152. self.SetIcon(
  153. wx.Icon(
  154. os.path.join(
  155. globalvar.ICONDIR,
  156. 'grass.ico'),
  157. wx.BITMAP_TYPE_ICO))
  158. self._command = None
  159. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  160. self.cmdBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  161. label=" %s " % _("Command"))
  162. self.labelBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  163. label=" %s " % _("Label and comment"))
  164. # menu data for search widget and prompt
  165. menuModel = LayerManagerMenuData()
  166. self.cmd_prompt = GPromptSTC(
  167. parent=self, menuModel=menuModel.GetModel())
  168. self.cmd_prompt.promptRunCmd.connect(self.OnCommand)
  169. self.cmd_prompt.commandSelected.connect(
  170. lambda command: self.label.SetValue(command))
  171. self.search = SearchModuleWidget(parent=self.panel,
  172. model=menuModel.GetModel(),
  173. showTip=True)
  174. self.search.moduleSelected.connect(
  175. lambda name: self.cmd_prompt.SetTextAndFocus(name + ' '))
  176. wx.CallAfter(self.cmd_prompt.SetFocus)
  177. self.label = TextCtrl(parent=self.panel, id=wx.ID_ANY)
  178. self.comment = TextCtrl(
  179. parent=self.panel,
  180. id=wx.ID_ANY,
  181. style=wx.TE_MULTILINE)
  182. self.btnCancel = Button(self.panel, wx.ID_CANCEL)
  183. self.btnOk = Button(self.panel, wx.ID_OK)
  184. self.btnOk.SetDefault()
  185. self.Bind(wx.EVT_BUTTON, self.OnOk, self.btnOk)
  186. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  187. self._layout()
  188. self.SetSize((500, -1))
  189. def _layout(self):
  190. cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
  191. cmdSizer.Add(self.cmd_prompt, proportion=1,
  192. flag=wx.EXPAND)
  193. labelSizer = wx.StaticBoxSizer(self.labelBox, wx.VERTICAL)
  194. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  195. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  196. label=_("Label:")),
  197. flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  198. gridSizer.Add(self.label, pos=(0, 1), flag=wx.EXPAND)
  199. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  200. label=_("Comment:")),
  201. flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  202. gridSizer.Add(self.comment, pos=(1, 1), flag=wx.EXPAND)
  203. gridSizer.AddGrowableRow(1)
  204. gridSizer.AddGrowableCol(1)
  205. labelSizer.Add(gridSizer, proportion=1, flag=wx.EXPAND)
  206. btnSizer = wx.StdDialogButtonSizer()
  207. btnSizer.AddButton(self.btnCancel)
  208. btnSizer.AddButton(self.btnOk)
  209. btnSizer.Realize()
  210. mainSizer = wx.BoxSizer(wx.VERTICAL)
  211. mainSizer.Add(self.search, proportion=0,
  212. flag=wx.EXPAND | wx.ALL, border=3)
  213. mainSizer.Add(cmdSizer, proportion=1,
  214. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  215. mainSizer.Add(labelSizer, proportion=1,
  216. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  217. mainSizer.Add(btnSizer, proportion=0,
  218. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  219. self.panel.SetSizer(mainSizer)
  220. mainSizer.Fit(self)
  221. self.Layout()
  222. def GetPanel(self):
  223. """Get dialog panel"""
  224. return self.panel
  225. def _getCmd(self):
  226. line = self.cmd_prompt.GetCurLine()[0].strip()
  227. if len(line) == 0:
  228. cmd = list()
  229. else:
  230. try:
  231. cmd = utils.split(str(line))
  232. except UnicodeError:
  233. cmd = utils.split(EncodeString((line)))
  234. return cmd
  235. def GetCmd(self):
  236. """Get command"""
  237. return self._command
  238. def GetLabel(self):
  239. """Get label and comment"""
  240. return self.label.GetValue(), self.comment.GetValue()
  241. def ValidateCmd(self, cmd):
  242. if len(cmd) < 1:
  243. GError(parent=self,
  244. message=_("Command not defined.\n\n"
  245. "Unable to add new action to the model."))
  246. return False
  247. if cmd[0] not in globalvar.grassCmd:
  248. GError(
  249. parent=self, message=_(
  250. "'%s' is not a GRASS module.\n\n"
  251. "Unable to add new action to the model.") %
  252. cmd[0])
  253. return False
  254. return True
  255. def OnCommand(self, cmd):
  256. """Command in prompt confirmed"""
  257. if self.ValidateCmd(cmd):
  258. self._command = cmd
  259. self.EndModal(wx.ID_OK)
  260. def OnOk(self, event):
  261. """Button 'OK' pressed"""
  262. cmd = self._getCmd()
  263. if self.ValidateCmd(cmd):
  264. self._command = cmd
  265. self.EndModal(wx.ID_OK)
  266. def OnCancel(self, event):
  267. """Cancel pressed, close window"""
  268. self.Hide()
  269. def Reset(self):
  270. """Reset dialog"""
  271. self.search.Reset()
  272. self.label.SetValue('')
  273. self.comment.SetValue('')
  274. self.cmd_prompt.OnCmdErase(None)
  275. self.cmd_prompt.SetFocus()
  276. class ModelRelationDialog(wx.Dialog):
  277. """Relation properties dialog"""
  278. def __init__(self, parent, shape, id=wx.ID_ANY,
  279. title=_("Relation properties"),
  280. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  281. self.parent = parent
  282. self.shape = shape
  283. options = self._getOptions()
  284. if not options:
  285. self.valid = False
  286. return
  287. self.valid = True
  288. wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
  289. self.SetIcon(
  290. wx.Icon(
  291. os.path.join(
  292. globalvar.ICONDIR,
  293. 'grass.ico'),
  294. wx.BITMAP_TYPE_ICO))
  295. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  296. self.fromBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  297. label=" %s " % _("From"))
  298. self.toBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  299. label=" %s " % _("To"))
  300. self.option = wx.ComboBox(parent=self.panel, id=wx.ID_ANY,
  301. style=wx.CB_READONLY,
  302. choices=options)
  303. self.option.Bind(wx.EVT_COMBOBOX, self.OnOption)
  304. self.btnCancel = Button(self.panel, wx.ID_CANCEL)
  305. self.btnOk = Button(self.panel, wx.ID_OK)
  306. self.btnOk.Enable(False)
  307. self._layout()
  308. def _layout(self):
  309. mainSizer = wx.BoxSizer(wx.VERTICAL)
  310. fromSizer = wx.StaticBoxSizer(self.fromBox, wx.VERTICAL)
  311. self._layoutShape(shape=self.shape.GetFrom(), sizer=fromSizer)
  312. toSizer = wx.StaticBoxSizer(self.toBox, wx.VERTICAL)
  313. self._layoutShape(shape=self.shape.GetTo(), sizer=toSizer)
  314. btnSizer = wx.StdDialogButtonSizer()
  315. btnSizer.AddButton(self.btnCancel)
  316. btnSizer.AddButton(self.btnOk)
  317. btnSizer.Realize()
  318. mainSizer.Add(fromSizer, proportion=0,
  319. flag=wx.EXPAND | wx.ALL, border=5)
  320. mainSizer.Add(toSizer, proportion=0, flag=wx.EXPAND |
  321. wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  322. mainSizer.Add(btnSizer, proportion=0,
  323. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  324. self.panel.SetSizer(mainSizer)
  325. mainSizer.Fit(self.panel)
  326. self.Layout()
  327. self.SetSize(self.GetBestSize())
  328. def _layoutShape(self, shape, sizer):
  329. if isinstance(shape, ModelData):
  330. sizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  331. label=_("Data: %s") % shape.GetLog()),
  332. proportion=1, flag=wx.EXPAND | wx.ALL,
  333. border=5)
  334. elif isinstance(shape, ModelAction):
  335. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  336. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  337. label=_("Command:")),
  338. pos=(0, 0))
  339. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  340. label=shape.GetLabel()),
  341. pos=(0, 1))
  342. gridSizer.Add(StaticText(parent=self.panel, id=wx.ID_ANY,
  343. label=_("Option:")),
  344. flag=wx.ALIGN_CENTER_VERTICAL,
  345. pos=(1, 0))
  346. gridSizer.Add(self.option,
  347. pos=(1, 1))
  348. sizer.Add(gridSizer,
  349. proportion=1, flag=wx.EXPAND | wx.ALL,
  350. border=5)
  351. def _getOptions(self):
  352. """Get relevant options"""
  353. items = []
  354. fromShape = self.shape.GetFrom()
  355. if not isinstance(fromShape, ModelData):
  356. GError(parent=self.parent,
  357. message=_("Relation doesn't start with data item.\n"
  358. "Unable to add relation."))
  359. return items
  360. toShape = self.shape.GetTo()
  361. if not isinstance(toShape, ModelAction):
  362. GError(parent=self.parent,
  363. message=_("Relation doesn't point to GRASS command.\n"
  364. "Unable to add relation."))
  365. return items
  366. prompt = fromShape.GetPrompt()
  367. task = toShape.GetTask()
  368. for p in task.get_options()['params']:
  369. if p.get('prompt', '') == prompt and \
  370. 'name' in p:
  371. items.append(p['name'])
  372. if not items:
  373. GError(parent=self.parent,
  374. message=_("No relevant option found.\n"
  375. "Unable to add relation."))
  376. return items
  377. def GetOption(self):
  378. """Get selected option"""
  379. return self.option.GetStringSelection()
  380. def IsValid(self):
  381. """Check if relation is valid"""
  382. return self.valid
  383. def OnOption(self, event):
  384. """Set option"""
  385. if event.GetString():
  386. self.btnOk.Enable()
  387. else:
  388. self.btnOk.Enable(False)
  389. class ModelItemDialog(wx.Dialog):
  390. """Abstract item properties dialog"""
  391. def __init__(self, parent, shape, title, id=wx.ID_ANY,
  392. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  393. self.parent = parent
  394. self.shape = shape
  395. wx.Dialog.__init__(
  396. self,
  397. parent,
  398. id,
  399. title=title,
  400. style=style,
  401. **kwargs)
  402. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  403. self.condBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  404. label=" %s " % _("Condition"))
  405. self.condText = TextCtrl(parent=self.panel, id=wx.ID_ANY,
  406. value=shape.GetLabel())
  407. self.itemList = ItemCheckListCtrl(parent=self.panel,
  408. columns=[_("Label"),
  409. _("Command")],
  410. shape=shape,
  411. frame=parent)
  412. self.itemList.Populate(self.parent.GetModel().GetItems())
  413. self.btnCancel = Button(parent=self.panel, id=wx.ID_CANCEL)
  414. self.btnOk = Button(parent=self.panel, id=wx.ID_OK)
  415. self.btnOk.SetDefault()
  416. def _layout(self):
  417. """Do layout (virtual method)"""
  418. pass
  419. def GetCondition(self):
  420. """Get loop condition"""
  421. return self.condText.GetValue()
  422. class ModelLoopDialog(ModelItemDialog):
  423. """Loop properties dialog"""
  424. def __init__(self, parent, shape, id=wx.ID_ANY, title=_("Loop properties"),
  425. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  426. ModelItemDialog.__init__(self, parent, shape, title,
  427. style=style, **kwargs)
  428. self.listBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  429. label=" %s " % _("List of items in loop"))
  430. self.btnSeries = Button(parent=self.panel, id=wx.ID_ANY,
  431. label=_("Series"))
  432. self.btnSeries.SetToolTip(
  433. _("Define map series as condition for the loop"))
  434. self.btnSeries.Bind(wx.EVT_BUTTON, self.OnSeries)
  435. self._layout()
  436. self.SetMinSize(self.GetSize())
  437. self.SetSize((500, 400))
  438. def _layout(self):
  439. """Do layout"""
  440. sizer = wx.BoxSizer(wx.VERTICAL)
  441. condSizer = wx.StaticBoxSizer(self.condBox, wx.HORIZONTAL)
  442. condSizer.Add(self.condText, proportion=1,
  443. flag=wx.ALL, border=3)
  444. condSizer.Add(self.btnSeries, proportion=0,
  445. flag=wx.EXPAND)
  446. listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
  447. listSizer.Add(self.itemList, proportion=1,
  448. flag=wx.EXPAND | wx.ALL, border=3)
  449. btnSizer = wx.StdDialogButtonSizer()
  450. btnSizer.AddButton(self.btnCancel)
  451. btnSizer.AddButton(self.btnOk)
  452. btnSizer.Realize()
  453. sizer.Add(condSizer, proportion=0,
  454. flag=wx.EXPAND | wx.ALL, border=3)
  455. sizer.Add(listSizer, proportion=1,
  456. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  457. sizer.Add(btnSizer, proportion=0,
  458. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  459. self.panel.SetSizer(sizer)
  460. sizer.Fit(self.panel)
  461. self.Layout()
  462. def GetItems(self):
  463. """Get list of selected actions"""
  464. return self.itemList.GetItems()
  465. def OnSeries(self, event):
  466. """Define map series as condition"""
  467. dialog = MapLayersDialogForModeler(
  468. parent=self, title=_("Define series of maps"))
  469. if dialog.ShowModal() != wx.ID_OK:
  470. dialog.Destroy()
  471. return
  472. cond = dialog.GetDSeries()
  473. if not cond:
  474. cond = 'map in %s' % map(lambda x: str(x), dialog.GetMapLayers())
  475. self.condText.SetValue(cond)
  476. dialog.Destroy()
  477. class ModelConditionDialog(ModelItemDialog):
  478. """Condition properties dialog"""
  479. def __init__(self, parent, shape, id=wx.ID_ANY,
  480. title=_("If-else properties"),
  481. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  482. ModelItemDialog.__init__(self, parent, shape, title,
  483. style=style, **kwargs)
  484. self.listBoxIf = StaticBox(
  485. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  486. _("List of items in 'if' block"))
  487. self.itemListIf = self.itemList
  488. self.itemListIf.SetName('IfBlockList')
  489. self.listBoxElse = StaticBox(
  490. parent=self.panel, id=wx.ID_ANY, label=" %s " %
  491. _("List of items in 'else' block"))
  492. self.itemListElse = ItemCheckListCtrl(parent=self.panel,
  493. columns=[_("Label"),
  494. _("Command")],
  495. shape=shape, frame=parent)
  496. self.itemListElse.SetName('ElseBlockList')
  497. self.itemListElse.Populate(self.parent.GetModel().GetItems())
  498. self._layout()
  499. self.SetMinSize(self.GetSize())
  500. self.SetSize((500, 400))
  501. def _layout(self):
  502. """Do layout"""
  503. sizer = wx.BoxSizer(wx.VERTICAL)
  504. condSizer = wx.StaticBoxSizer(self.condBox, wx.VERTICAL)
  505. condSizer.Add(self.condText, proportion=1,
  506. flag=wx.EXPAND)
  507. listIfSizer = wx.StaticBoxSizer(self.listBoxIf, wx.VERTICAL)
  508. listIfSizer.Add(self.itemListIf, proportion=1,
  509. flag=wx.EXPAND)
  510. listElseSizer = wx.StaticBoxSizer(self.listBoxElse, wx.VERTICAL)
  511. listElseSizer.Add(self.itemListElse, proportion=1,
  512. flag=wx.EXPAND)
  513. btnSizer = wx.StdDialogButtonSizer()
  514. btnSizer.AddButton(self.btnCancel)
  515. btnSizer.AddButton(self.btnOk)
  516. btnSizer.Realize()
  517. sizer.Add(condSizer, proportion=0,
  518. flag=wx.EXPAND | wx.ALL, border=3)
  519. sizer.Add(listIfSizer, proportion=1,
  520. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  521. sizer.Add(listElseSizer, proportion=1,
  522. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  523. sizer.Add(btnSizer, proportion=0,
  524. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  525. self.panel.SetSizer(sizer)
  526. sizer.Fit(self.panel)
  527. self.Layout()
  528. def OnCheckItemIf(self, index, flag):
  529. """Item in if-block checked/unchecked"""
  530. if flag is False:
  531. return
  532. aId = int(self.itemListIf.GetItem(index, 0).GetText())
  533. if aId in self.itemListElse.GetItems()['checked']:
  534. self.itemListElse.CheckItemById(aId, False)
  535. def OnCheckItemElse(self, index, flag):
  536. """Item in else-block checked/unchecked"""
  537. if flag is False:
  538. return
  539. aId = int(self.itemListElse.GetItem(index, 0).GetText())
  540. if aId in self.itemListIf.GetItems()['checked']:
  541. self.itemListIf.CheckItemById(aId, False)
  542. def GetItems(self):
  543. """Get items"""
  544. return {'if': self.itemListIf.GetItems(),
  545. 'else': self.itemListElse.GetItems()}
  546. class ModelListCtrl(wx.ListCtrl,
  547. listmix.ListCtrlAutoWidthMixin,
  548. listmix.TextEditMixin):
  549. def __init__(
  550. self, parent, columns, frame, id=wx.ID_ANY, columnsNotEditable=[],
  551. style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_HRULES | wx.LC_VRULES, **
  552. kwargs):
  553. """List of model variables"""
  554. self.parent = parent
  555. self.columns = columns
  556. self.shape = None
  557. self.frame = frame
  558. self.columnNotEditable = columnsNotEditable
  559. wx.ListCtrl.__init__(self, parent, id=id, style=style, **kwargs)
  560. listmix.ListCtrlAutoWidthMixin.__init__(self)
  561. listmix.TextEditMixin.__init__(self)
  562. i = 0
  563. for col in columns:
  564. self.InsertColumn(i, col)
  565. self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER)
  566. i += 1
  567. self.itemDataMap = {} # requested by sorter
  568. self.itemCount = 0
  569. self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit)
  570. self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit)
  571. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
  572. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp) # wxMSW
  573. self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) # wxGTK
  574. def OnBeginEdit(self, event):
  575. """Editing of item started"""
  576. if self.columnNotEditable and event.m_col in self.columnNotEditable:
  577. event.Veto()
  578. self.SetItemState(
  579. event.m_itemIndex,
  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.InsertStringItem(i, name)
  615. self.SetStringItem(index, 0, name)
  616. self.SetStringItem(index, 1, vtype)
  617. self.SetStringItem(index, 2, value)
  618. self.SetStringItem(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.InsertStringItem(self.GetItemCount(), name)
  631. self.SetStringItem(index, 0, name)
  632. self.SetStringItem(index, 1, vtype)
  633. self.SetStringItem(index, 2, value)
  634. self.SetStringItem(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 = wx.NewId()
  678. self.popupID2 = wx.NewId()
  679. self.popupID3 = wx.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.InsertStringItem(i, str(i))
  767. self.SetStringItem(index, 0, name)
  768. self.SetStringItem(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.InsertStringItem(i, str(i))
  776. self.SetStringItem(index, 0, name)
  777. self.SetStringItem(index, 1, inloop)
  778. self.SetStringItem(index, 2, param)
  779. self.SetStringItem(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'] = wx.NewId()
  820. self.popupID['reload'] = wx.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