dialogs.py 35 KB

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