dialogs.py 37 KB

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