dialogs.py 36 KB

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