dialogs.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. """!
  2. @package animation.dialogs
  3. @brief Dialogs for animation management, changing speed of animation
  4. Classes:
  5. - dialogs::SpeedDialog
  6. - dialogs::InputDialog
  7. - dialogs::EditDialog
  8. - dialogs::ExportDialog
  9. - dialogs::AnimSimpleLayerManager
  10. - dialogs::AddTemporalLayerDialog
  11. (C) 2013 by the GRASS Development Team
  12. This program is free software under the GNU General Public License
  13. (>=v2). Read the file COPYING that comes with GRASS for details.
  14. @author Anna Petrasova <kratochanna gmail.com>
  15. """
  16. import os
  17. import sys
  18. import wx
  19. import copy
  20. import datetime
  21. import wx.lib.filebrowsebutton as filebrowse
  22. if __name__ == '__main__':
  23. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  24. from core.gcmd import GMessage, GError, GException
  25. from core import globalvar
  26. from gui_core.dialogs import MapLayersDialog, GetImageHandlers
  27. from gui_core.forms import GUI
  28. from core.settings import UserSettings
  29. from core.utils import _
  30. from gui_core.gselect import Select
  31. from animation.utils import TemporalMode, getRegisteredMaps
  32. from animation.data import AnimationData, AnimLayer
  33. from animation.toolbars import AnimSimpleLmgrToolbar, SIMPLE_LMGR_STDS
  34. from gui_core.simplelmgr import SimpleLayerManager, \
  35. SIMPLE_LMGR_RASTER, SIMPLE_LMGR_VECTOR, SIMPLE_LMGR_TB_TOP
  36. from grass.pydispatch.signal import Signal
  37. import grass.script.core as gcore
  38. class SpeedDialog(wx.Dialog):
  39. def __init__(self, parent, title=_("Adjust speed of animation"),
  40. temporalMode=None, minimumDuration=20, timeGranularity=None,
  41. initialSpeed=200):
  42. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  43. style=wx.DEFAULT_DIALOG_STYLE)
  44. # signal emitted when speed has changed; has attribute 'ms'
  45. self.speedChanged = Signal('SpeedDialog.speedChanged')
  46. self.minimumDuration = minimumDuration
  47. # self.framesCount = framesCount
  48. self.defaultSpeed = initialSpeed
  49. self.lastAppliedValue = self.defaultSpeed
  50. self.lastAppliedValueTemp = self.defaultSpeed
  51. self._layout()
  52. self.temporalMode = temporalMode
  53. self.timeGranularity = timeGranularity
  54. self._fillUnitChoice(self.choiceUnits)
  55. self.InitTimeSpin(self.defaultSpeed)
  56. def SetTimeGranularity(self, gran):
  57. self._timeGranularity = gran
  58. def GetTimeGranularity(self):
  59. return self._timeGranularity
  60. timeGranularity = property(fset=SetTimeGranularity, fget=GetTimeGranularity)
  61. def SetTemporalMode(self, mode):
  62. self._temporalMode = mode
  63. self._setTemporalMode()
  64. def GetTemporalMode(self):
  65. return self._temporalMode
  66. temporalMode = property(fset=SetTemporalMode, fget=GetTemporalMode)
  67. def _layout(self):
  68. """!Layout window"""
  69. mainSizer = wx.BoxSizer(wx.VERTICAL)
  70. #
  71. # simple mode
  72. #
  73. self.nontemporalBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
  74. label=' %s ' % _("Simple mode"))
  75. box = wx.StaticBoxSizer(self.nontemporalBox, wx.VERTICAL)
  76. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  77. labelDuration = wx.StaticText(self, id=wx.ID_ANY, label=_("Frame duration:"))
  78. labelUnits = wx.StaticText(self, id=wx.ID_ANY, label=_("ms"))
  79. self.spinDuration = wx.SpinCtrl(self, id=wx.ID_ANY, min=self.minimumDuration,
  80. max=10000, initial=self.defaultSpeed)
  81. # TODO total time
  82. gridSizer.Add(item=labelDuration, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  83. gridSizer.Add(item=self.spinDuration, pos=(0, 1), flag = wx.ALIGN_CENTER)
  84. gridSizer.Add(item=labelUnits, pos=(0, 2), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  85. gridSizer.AddGrowableCol(0)
  86. box.Add(item=gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
  87. self.nontemporalSizer = gridSizer
  88. mainSizer.Add(item=box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  89. #
  90. # temporal mode
  91. #
  92. self.temporalBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
  93. label=' %s ' % _("Temporal mode"))
  94. box = wx.StaticBoxSizer(self.temporalBox, wx.VERTICAL)
  95. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  96. labelTimeUnit = wx.StaticText(self, id=wx.ID_ANY, label=_("Time unit:"))
  97. labelDuration = wx.StaticText(self, id=wx.ID_ANY, label=_("Duration of time unit:"))
  98. labelUnits = wx.StaticText(self, id=wx.ID_ANY, label=_("ms"))
  99. self.spinDurationTemp = wx.SpinCtrl(self, id=wx.ID_ANY, min=self.minimumDuration,
  100. max=10000, initial=self.defaultSpeed)
  101. self.choiceUnits = wx.Choice(self, id=wx.ID_ANY)
  102. # TODO total time
  103. gridSizer.Add(item=labelTimeUnit, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  104. gridSizer.Add(item=self.choiceUnits, pos=(0, 1), flag = wx.ALIGN_CENTER | wx.EXPAND)
  105. gridSizer.Add(item=labelDuration, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  106. gridSizer.Add(item=self.spinDurationTemp, pos=(1, 1), flag = wx.ALIGN_CENTER | wx.EXPAND)
  107. gridSizer.Add(item=labelUnits, pos=(1, 2), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  108. gridSizer.AddGrowableCol(1)
  109. self.temporalSizer = gridSizer
  110. box.Add(item=gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
  111. mainSizer.Add(item=box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  112. self.btnOk = wx.Button(self, wx.ID_OK)
  113. self.btnApply = wx.Button(self, wx.ID_APPLY)
  114. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  115. self.btnOk.SetDefault()
  116. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  117. self.btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  118. self.btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  119. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  120. # button sizer
  121. btnStdSizer = wx.StdDialogButtonSizer()
  122. btnStdSizer.AddButton(self.btnOk)
  123. btnStdSizer.AddButton(self.btnApply)
  124. btnStdSizer.AddButton(self.btnCancel)
  125. btnStdSizer.Realize()
  126. mainSizer.Add(item=btnStdSizer, proportion=0,
  127. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  128. self.SetSizer(mainSizer)
  129. mainSizer.Fit(self)
  130. def _setTemporalMode(self):
  131. self.nontemporalBox.Enable(self.temporalMode == TemporalMode.NONTEMPORAL)
  132. self.temporalBox.Enable(self.temporalMode == TemporalMode.TEMPORAL)
  133. for child in self.temporalSizer.GetChildren():
  134. child.GetWindow().Enable(self.temporalMode == TemporalMode.TEMPORAL)
  135. for child in self.nontemporalSizer.GetChildren():
  136. child.GetWindow().Enable(self.temporalMode == TemporalMode.NONTEMPORAL)
  137. self.Layout()
  138. def _fillUnitChoice(self, choiceWidget):
  139. timeUnitsChoice = [_("year"), _("month"), _("day"), _("hour"), _("minute"), _("second")]
  140. timeUnits = ["years", "months", "days", "hours", "minutes", "seconds"]
  141. for item, cdata in zip(timeUnitsChoice, timeUnits):
  142. choiceWidget.Append(item, cdata)
  143. if self.temporalMode == TemporalMode.TEMPORAL:
  144. unit = self.timeGranularity[1]
  145. try:
  146. index = timeUnits.index(unit)
  147. except ValueError:
  148. index = 0
  149. choiceWidget.SetSelection(index)
  150. else:
  151. choiceWidget.SetSelection(0)
  152. def OnOk(self, event):
  153. self._apply()
  154. self.OnCancel(None)
  155. def OnApply(self, event):
  156. self._apply()
  157. def OnCancel(self, event):
  158. self.spinDuration.SetValue(self.lastAppliedValue)
  159. self.spinDurationTemp.SetValue(self.lastAppliedValueTemp)
  160. self.Hide()
  161. def InitTimeSpin(self, timeTick):
  162. if self.temporalMode == TemporalMode.TEMPORAL:
  163. index = self.choiceUnits.GetSelection()
  164. unit = self.choiceUnits.GetClientData(index)
  165. delta = self._timedelta(unit=unit, number=1)
  166. seconds1 = self._total_seconds(delta)
  167. number, unit = self.timeGranularity
  168. number = float(number)
  169. delta = self._timedelta(unit=unit, number=number)
  170. seconds2 = self._total_seconds(delta)
  171. value = timeTick
  172. ms = value * seconds1 / float(seconds2)
  173. self.spinDurationTemp.SetValue(ms)
  174. else:
  175. self.spinDuration.SetValue(timeTick)
  176. def _apply(self):
  177. if self.temporalMode == TemporalMode.NONTEMPORAL:
  178. ms = self.spinDuration.GetValue()
  179. self.lastAppliedValue = self.spinDuration.GetValue()
  180. elif self.temporalMode == TemporalMode.TEMPORAL:
  181. index = self.choiceUnits.GetSelection()
  182. unit = self.choiceUnits.GetClientData(index)
  183. delta = self._timedelta(unit=unit, number=1)
  184. seconds1 = self._total_seconds(delta)
  185. number, unit = self.timeGranularity
  186. number = float(number)
  187. delta = self._timedelta(unit=unit, number=number)
  188. seconds2 = self._total_seconds(delta)
  189. value = self.spinDurationTemp.GetValue()
  190. ms = value * seconds2 / float(seconds1)
  191. if ms < self.minimumDuration:
  192. GMessage(parent=self, message=_("Animation speed is too high."))
  193. return
  194. self.lastAppliedValueTemp = self.spinDurationTemp.GetValue()
  195. else:
  196. return
  197. self.speedChanged.emit(ms=ms)
  198. def _timedelta(self, unit, number):
  199. if unit in "years":
  200. delta = datetime.timedelta(days=365.25 * number)
  201. elif unit in "months":
  202. delta = datetime.timedelta(days=30.4375 * number) # 365.25/12
  203. elif unit in "days":
  204. delta = datetime.timedelta(days=1 * number)
  205. elif unit in "hours":
  206. delta = datetime.timedelta(hours=1 * number)
  207. elif unit in "minutes":
  208. delta = datetime.timedelta(minutes=1 * number)
  209. elif unit in "seconds":
  210. delta = datetime.timedelta(seconds=1 * number)
  211. return delta
  212. def _total_seconds(self, delta):
  213. """!timedelta.total_seconds is new in version 2.7.
  214. """
  215. return delta.seconds + delta.days * 24 * 3600
  216. class InputDialog(wx.Dialog):
  217. def __init__(self, parent, mode, animationData):
  218. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
  219. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
  220. if mode == 'add':
  221. self.SetTitle(_("Add new animation"))
  222. elif mode == 'edit':
  223. self.SetTitle(_("Edit animation"))
  224. self.animationData = animationData
  225. self._tmpLegendCmd = None
  226. self._layout()
  227. self.OnViewMode(event=None)
  228. def _layout(self):
  229. mainSizer = wx.BoxSizer(wx.VERTICAL)
  230. self.windowChoice = wx.Choice(self, id=wx.ID_ANY,
  231. choices=[_("top left"), _("top right"),
  232. _("bottom left"), _("bottom right")])
  233. self.windowChoice.SetSelection(self.animationData.windowIndex)
  234. self.nameCtrl = wx.TextCtrl(self, id=wx.ID_ANY, value=self.animationData.name)
  235. self.nDChoice = wx.Choice(self, id=wx.ID_ANY)
  236. mode = self.animationData.viewMode
  237. index = 0
  238. for i, (viewMode, viewModeName) in enumerate(self.animationData.viewModes):
  239. self.nDChoice.Append(viewModeName, clientData=viewMode)
  240. if mode == viewMode:
  241. index = i
  242. self.nDChoice.SetSelection(index)
  243. self.nDChoice.SetToolTipString(_("Select 2D or 3D view"))
  244. self.nDChoice.Bind(wx.EVT_CHOICE, self.OnViewMode)
  245. gridSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
  246. gridSizer.Add(item=wx.StaticText(self, id=wx.ID_ANY, label=_("Name:")),
  247. flag=wx.ALIGN_CENTER_VERTICAL)
  248. gridSizer.Add(item=self.nameCtrl, proportion=1, flag=wx.EXPAND)
  249. gridSizer.Add(item=wx.StaticText(self, id=wx.ID_ANY, label=_("Window position:")),
  250. flag=wx.ALIGN_CENTER_VERTICAL)
  251. gridSizer.Add(item=self.windowChoice, proportion=1, flag=wx.ALIGN_RIGHT)
  252. gridSizer.Add(item=wx.StaticText(self, id=wx.ID_ANY, label=_("View mode:")),
  253. flag=wx.ALIGN_CENTER_VERTICAL)
  254. gridSizer.Add(item=self.nDChoice, proportion=1, flag=wx.ALIGN_RIGHT)
  255. gridSizer.AddGrowableCol(0, 1)
  256. gridSizer.AddGrowableCol(1, 1)
  257. mainSizer.Add(item=gridSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
  258. label = _("For 3D animation, please select only one space-time dataset\n"
  259. "or one series of map layers.")
  260. self.warning3DLayers = wx.StaticText(self, label=label)
  261. self.warning3DLayers.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
  262. mainSizer.Add(item=self.warning3DLayers, proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
  263. self.dataPanel = self._createDataPanel()
  264. self.threeDPanel = self._create3DPanel()
  265. mainSizer.Add(item=self.dataPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
  266. mainSizer.Add(item=self.threeDPanel, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  267. # buttons
  268. self.btnOk = wx.Button(self, wx.ID_OK)
  269. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  270. self.btnOk.SetDefault()
  271. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  272. # button sizer
  273. btnStdSizer = wx.StdDialogButtonSizer()
  274. btnStdSizer.AddButton(self.btnOk)
  275. btnStdSizer.AddButton(self.btnCancel)
  276. btnStdSizer.Realize()
  277. mainSizer.Add(item=btnStdSizer, proportion=0,
  278. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  279. self.SetSizer(mainSizer)
  280. mainSizer.Fit(self)
  281. def _createDataPanel(self):
  282. panel = wx.Panel(self)
  283. slmgrSizer = wx.BoxSizer(wx.VERTICAL)
  284. self._layerList = copy.deepcopy(self.animationData.layerList)
  285. self.simpleLmgr = AnimSimpleLayerManager(parent=panel,
  286. layerList=self._layerList,
  287. modal=True)
  288. self.simpleLmgr.SetMinSize((globalvar.DIALOG_GSELECT_SIZE[0], 120))
  289. slmgrSizer.Add(self.simpleLmgr, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  290. self.legend = wx.CheckBox(panel, label=_("Show raster legend"))
  291. self.legend.SetValue(bool(self.animationData.legendCmd))
  292. self.legendBtn = wx.Button(panel, label=_("Set options"))
  293. self.legend.Bind(wx.EVT_CHECKBOX, self.OnLegend)
  294. self.legendBtn.Bind(wx.EVT_BUTTON, self.OnLegendProperties)
  295. hbox = wx.BoxSizer(wx.HORIZONTAL)
  296. hbox.Add(item=self.legend, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
  297. hbox.Add(item=self.legendBtn, proportion=0, flag=wx.LEFT, border=5)
  298. slmgrSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  299. panel.SetSizerAndFit(slmgrSizer)
  300. panel.SetAutoLayout(True)
  301. return panel
  302. def _create3DPanel(self):
  303. panel = wx.Panel(self, id=wx.ID_ANY)
  304. dataStBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  305. label=' %s ' % _("3D view parameters"))
  306. dataBoxSizer = wx.StaticBoxSizer(dataStBox, wx.VERTICAL)
  307. # workspace file
  308. self.fileSelector = \
  309. filebrowse.FileBrowseButton(parent=panel, id=wx.ID_ANY,
  310. size=globalvar.DIALOG_GSELECT_SIZE,
  311. labelText=_("Workspace file:"),
  312. dialogTitle=_("Choose workspace file to "
  313. "import 3D view parameters"),
  314. buttonText=_('Browse'),
  315. startDirectory=os.getcwd(), fileMode=0,
  316. fileMask="GRASS Workspace File (*.gxw)|*.gxw")
  317. if self.animationData.workspaceFile:
  318. self.fileSelector.SetValue(self.animationData.workspaceFile)
  319. self.paramLabel = wx.StaticText(panel, wx.ID_ANY, label=_("Parameter for animation:"))
  320. self.paramChoice = wx.Choice(panel, id=wx.ID_ANY, choices=self.animationData.nvizParameters)
  321. self.paramChoice.SetStringSelection(self.animationData.nvizParameter)
  322. hbox = wx.BoxSizer(wx.HORIZONTAL)
  323. hbox.Add(item=self.fileSelector, proportion=1, flag=wx.EXPAND | wx.ALIGN_CENTER)
  324. dataBoxSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  325. hbox = wx.BoxSizer(wx.HORIZONTAL)
  326. hbox.Add(item=self.paramLabel, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
  327. hbox.Add(item=self.paramChoice, proportion=1, flag=wx.EXPAND)
  328. dataBoxSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  329. panel.SetSizerAndFit(dataBoxSizer)
  330. panel.SetAutoLayout(True)
  331. return panel
  332. def OnViewMode(self, event):
  333. mode = self.nDChoice.GetSelection()
  334. self.Freeze()
  335. self.simpleLmgr.Activate3D(mode == 1)
  336. self.warning3DLayers.Show(mode == 1)
  337. sizer = self.threeDPanel.GetContainingSizer()
  338. sizer.Show(self.threeDPanel, mode == 1, True)
  339. sizer.Layout()
  340. self.Layout()
  341. self.Fit()
  342. self.Thaw()
  343. def OnLegend(self, event):
  344. if not self.legend.IsChecked():
  345. return
  346. if self._tmpLegendCmd or self.animationData.legendCmd:
  347. return
  348. cmd = ['d.legend', 'at=5,50,2,5']
  349. GUI(parent=self, modal=True).ParseCommand(cmd=cmd,
  350. completed=(self.GetOptData, '', ''))
  351. def OnLegendProperties(self, event):
  352. """!Set options for legend"""
  353. if self._tmpLegendCmd:
  354. cmd = self._tmpLegendCmd
  355. elif self.animationData.legendCmd:
  356. cmd = self.animationData.legendCmd
  357. else:
  358. cmd = ['d.legend', 'at=5,50,2,5']
  359. mapName = self._getLegendMapHint()
  360. if mapName:
  361. cmd.append("map=%s" % mapName)
  362. GUI(parent=self, modal=True).ParseCommand(cmd=cmd,
  363. completed=(self.GetOptData, '', ''))
  364. def GetOptData(self, dcmd, layer, params, propwin):
  365. """!Process decoration layer data"""
  366. if dcmd:
  367. self._tmpLegendCmd = dcmd
  368. if not self.legend.IsChecked():
  369. self.legend.SetValue(True)
  370. else:
  371. if not self._tmpLegendCmd and not self.animationData.legendCmd:
  372. self.legend.SetValue(False)
  373. def _update(self):
  374. if self.nDChoice.GetSelection() == 1 and len(self._layerList) > 1:
  375. raise GException(_("Only one series or space-time "
  376. "dataset is accepted for 3D mode."))
  377. hasSeries = False
  378. for layer in self._layerList:
  379. if layer.active and hasattr(layer, 'maps'):
  380. hasSeries = True
  381. break
  382. if not hasSeries:
  383. raise GException(_("No map series or space-time dataset added."))
  384. self.animationData.layerList = self._layerList
  385. self.animationData.name = self.nameCtrl.GetValue()
  386. self.animationData.windowIndex = self.windowChoice.GetSelection()
  387. sel = self.nDChoice.GetSelection()
  388. self.animationData.viewMode = self.nDChoice.GetClientData(sel)
  389. self.animationData.legendCmd = None
  390. if self._tmpLegendCmd:
  391. if self.legend.IsChecked():
  392. self.animationData.legendCmd = self._tmpLegendCmd
  393. if self.threeDPanel.IsShown():
  394. self.animationData.workspaceFile = self.fileSelector.GetValue()
  395. if self.threeDPanel.IsShown():
  396. self.animationData.nvizParameter = self.paramChoice.GetStringSelection()
  397. def OnOk(self, event):
  398. try:
  399. self._update()
  400. self.EndModal(wx.ID_OK)
  401. except (GException, ValueError, IOError) as e:
  402. GError(message=str(e), showTraceback=False, caption=_("Invalid input"))
  403. class EditDialog(wx.Dialog):
  404. def __init__(self, parent, evalFunction, animationData, maxAnimations):
  405. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
  406. style=wx.DEFAULT_DIALOG_STYLE)
  407. self.animationData = copy.deepcopy(animationData)
  408. self.eval = evalFunction
  409. self.SetTitle(_("Add, edit or remove animations"))
  410. self._layout()
  411. self.SetSize((300, -1))
  412. self.maxAnimations = maxAnimations
  413. self.result = None
  414. def _layout(self):
  415. mainSizer = wx.BoxSizer(wx.VERTICAL)
  416. box = wx.StaticBox (parent=self, id=wx.ID_ANY, label=" %s " % _("List of animations"))
  417. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  418. gridBagSizer = wx.GridBagSizer (hgap=5, vgap=5)
  419. gridBagSizer.AddGrowableCol(0)
  420. # gridBagSizer.AddGrowableCol(1,1)
  421. self.listbox = wx.ListBox(self, id=wx.ID_ANY, choices=[], style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
  422. self.listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnEdit)
  423. self.addButton = wx.Button(self, id=wx.ID_ANY, label=_("Add"))
  424. self.addButton.Bind(wx.EVT_BUTTON, self.OnAdd)
  425. self.editButton = wx.Button(self, id=wx.ID_ANY, label=_("Edit"))
  426. self.editButton.Bind(wx.EVT_BUTTON, self.OnEdit)
  427. self.removeButton = wx.Button(self, id=wx.ID_ANY, label=_("Remove"))
  428. self.removeButton.Bind(wx.EVT_BUTTON, self.OnRemove)
  429. self._updateListBox()
  430. gridBagSizer.Add(self.listbox, pos=(0, 0), span = (3, 1),
  431. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  432. gridBagSizer.Add(self.addButton, pos=(0, 1),
  433. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  434. gridBagSizer.Add(self.editButton, pos=(1, 1),
  435. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  436. gridBagSizer.Add(self.removeButton, pos=(2, 1),
  437. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  438. sizer.Add(gridBagSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
  439. mainSizer.Add(item=sizer, proportion=0,
  440. flag=wx.EXPAND | wx.ALL, border=5)
  441. # buttons
  442. self.btnOk = wx.Button(self, wx.ID_OK)
  443. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  444. self.btnOk.SetDefault()
  445. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  446. # button sizer
  447. btnStdSizer = wx.StdDialogButtonSizer()
  448. btnStdSizer.AddButton(self.btnOk)
  449. btnStdSizer.AddButton(self.btnCancel)
  450. btnStdSizer.Realize()
  451. mainSizer.Add(item=btnStdSizer, proportion=0,
  452. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  453. self.SetSizer(mainSizer)
  454. mainSizer.Fit(self)
  455. def _updateListBox(self):
  456. self.listbox.Clear()
  457. for anim in self.animationData:
  458. self.listbox.Append(anim.name, clientData=anim)
  459. if self.animationData:
  460. self.listbox.SetSelection(0)
  461. def _getNextIndex(self):
  462. indices = [anim.windowIndex for anim in self.animationData]
  463. for i in range(self.maxAnimations):
  464. if i not in indices:
  465. return i
  466. return None
  467. def OnAdd(self, event):
  468. windowIndex = self._getNextIndex()
  469. if windowIndex is None:
  470. GMessage(self, message=_("Maximum number of animations is %d.") % self.maxAnimations)
  471. return
  472. animData = AnimationData()
  473. # number of active animations
  474. animationIndex = len(self.animationData)
  475. animData.SetDefaultValues(windowIndex, animationIndex)
  476. dlg = InputDialog(parent=self, mode='add', animationData=animData)
  477. dlg.CenterOnParent()
  478. if dlg.ShowModal() == wx.ID_CANCEL:
  479. dlg.Destroy()
  480. return
  481. dlg.Destroy()
  482. self.animationData.append(animData)
  483. self._updateListBox()
  484. def OnEdit(self, event):
  485. index = self.listbox.GetSelection()
  486. if index == wx.NOT_FOUND:
  487. return
  488. animData = self.listbox.GetClientData(index)
  489. dlg = InputDialog(parent=self, mode='edit', animationData=animData)
  490. dlg.CenterOnParent()
  491. if dlg.ShowModal() == wx.ID_CANCEL:
  492. dlg.Destroy()
  493. return
  494. dlg.Destroy()
  495. self._updateListBox()
  496. def OnRemove(self, event):
  497. index = self.listbox.GetSelection()
  498. if index == wx.NOT_FOUND:
  499. return
  500. animData = self.listbox.GetClientData(index)
  501. self.animationData.remove(animData)
  502. self._updateListBox()
  503. def GetResult(self):
  504. return self.result
  505. def OnOk(self, event):
  506. indices = set([anim.windowIndex for anim in self.animationData])
  507. if len(indices) != len(self.animationData):
  508. GError(parent=self, message=_("More animations are using one window."
  509. " Please select different window for each animation."))
  510. return
  511. try:
  512. temporalMode, tempManager = self.eval(self.animationData)
  513. except GException, e:
  514. GError(parent=self, message=e.value, showTraceback=False)
  515. return
  516. self.result = (self.animationData, temporalMode, tempManager)
  517. self.EndModal(wx.ID_OK)
  518. class ExportDialog(wx.Dialog):
  519. def __init__(self, parent, temporal, timeTick):
  520. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=_("Export animation"),
  521. style=wx.DEFAULT_DIALOG_STYLE)
  522. self.decorations = []
  523. self.temporal = temporal
  524. self.timeTick = timeTick
  525. self._layout()
  526. # export animation
  527. self.doExport = Signal('ExportDialog::doExport')
  528. wx.CallAfter(self._hideAll)
  529. def _layout(self):
  530. notebook = wx.Notebook(self, id=wx.ID_ANY)
  531. mainSizer = wx.BoxSizer(wx.VERTICAL)
  532. notebook.AddPage(page=self._createExportFormatPanel(notebook), text=_("Format"))
  533. notebook.AddPage(page=self._createDecorationsPanel(notebook), text=_("Decorations"))
  534. mainSizer.Add(item=notebook, proportion=0,
  535. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  536. self.btnExport = wx.Button(self, wx.ID_OK)
  537. self.btnExport.SetLabel(_("Export"))
  538. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  539. self.btnExport.SetDefault()
  540. self.btnExport.Bind(wx.EVT_BUTTON, self.OnExport)
  541. # button sizer
  542. btnStdSizer = wx.StdDialogButtonSizer()
  543. btnStdSizer.AddButton(self.btnExport)
  544. btnStdSizer.AddButton(self.btnCancel)
  545. btnStdSizer.Realize()
  546. mainSizer.Add(item=btnStdSizer, proportion=0,
  547. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  548. self.SetSizer(mainSizer)
  549. # set the longest option to fit
  550. self.hidevbox.Show(self.fontBox, True)
  551. self.hidevbox.Show(self.imageBox, False)
  552. self.hidevbox.Show(self.textBox, True)
  553. self.hidevbox.Show(self.posBox, True)
  554. self.hidevbox.Show(self.informBox, False)
  555. mainSizer.Fit(self)
  556. def _createDecorationsPanel(self, notebook):
  557. panel = wx.Panel(notebook, id=wx.ID_ANY)
  558. sizer = wx.BoxSizer(wx.VERTICAL)
  559. sizer.Add(self._createDecorationsList(panel), proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
  560. sizer.Add(self._createDecorationsProperties(panel), proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
  561. panel.SetSizer(sizer)
  562. sizer.Fit(panel)
  563. return panel
  564. def _createDecorationsList(self, panel):
  565. gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
  566. gridBagSizer.AddGrowableCol(0)
  567. self.listbox = wx.ListBox(panel, id=wx.ID_ANY, choices=[],
  568. style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
  569. self.listbox.Bind(wx.EVT_LISTBOX, self.OnSelectionChanged)
  570. gridBagSizer.Add(self.listbox, pos=(0, 0), span=(4, 1),
  571. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  572. buttonNames = ['time', 'image', 'text']
  573. buttonLabels = [_("Add time stamp"), _("Add image"), _("Add text")]
  574. i = 0
  575. for buttonName, buttonLabel in zip(buttonNames, buttonLabels):
  576. if buttonName == 'time' and self.temporal == TemporalMode.NONTEMPORAL:
  577. continue
  578. btn = wx.Button(panel, id=wx.ID_ANY, name=buttonName, label=buttonLabel)
  579. btn.Bind(wx.EVT_BUTTON, lambda evt, temp=buttonName: self.OnAddDecoration(evt, temp))
  580. gridBagSizer.Add(btn, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  581. i += 1
  582. removeButton = wx.Button(panel, id=wx.ID_ANY, label=_("Remove"))
  583. removeButton.Bind(wx.EVT_BUTTON, self.OnRemove)
  584. gridBagSizer.Add(removeButton, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
  585. return gridBagSizer
  586. def _createDecorationsProperties(self, panel):
  587. self.hidevbox = wx.BoxSizer(wx.VERTICAL)
  588. # inform label
  589. self.informBox = wx.BoxSizer(wx.HORIZONTAL)
  590. if self.temporal == TemporalMode.TEMPORAL:
  591. label = _("Add time stamp, image or text decoration by one of the buttons above.")
  592. else:
  593. label = _("Add image or text decoration by one of the buttons above.")
  594. label = wx.StaticText(panel, id=wx.ID_ANY, label=label)
  595. label.Wrap(400)
  596. self.informBox.Add(label, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
  597. self.hidevbox.Add(self.informBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
  598. # font
  599. self.fontBox = wx.BoxSizer(wx.HORIZONTAL)
  600. self.fontBox.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Font settings:")),
  601. proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
  602. self.sampleLabel = wx.StaticText(panel, id=wx.ID_ANY, label=_("Sample text"))
  603. self.fontBox.Add(self.sampleLabel, proportion=1,
  604. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT, border=5)
  605. fontButton = wx.Button(panel, id=wx.ID_ANY, label=_("Set font"))
  606. fontButton.Bind(wx.EVT_BUTTON, self.OnFont)
  607. self.fontBox.Add(fontButton, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
  608. self.hidevbox.Add(self.fontBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
  609. # image
  610. self.imageBox = wx.BoxSizer(wx.HORIZONTAL)
  611. filetype, ltype = GetImageHandlers(wx.EmptyImage(10, 10))
  612. self.browse = filebrowse.FileBrowseButton(parent=panel, id=wx.ID_ANY, fileMask=filetype,
  613. labelText=_("Image file:"),
  614. dialogTitle=_('Choose image file'),
  615. buttonText=_('Browse'),
  616. startDirectory=os.getcwd(), fileMode=wx.OPEN,
  617. changeCallback=self.OnSetImage)
  618. self.imageBox.Add(self.browse, proportion=1, flag=wx.EXPAND)
  619. self.hidevbox.Add(self.imageBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
  620. # text
  621. self.textBox = wx.BoxSizer(wx.HORIZONTAL)
  622. self.textBox.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Text:")),
  623. proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
  624. self.textCtrl = wx.TextCtrl(panel, id=wx.ID_ANY)
  625. self.textCtrl.Bind(wx.EVT_TEXT, self.OnText)
  626. self.textBox.Add(self.textCtrl, proportion=1, flag=wx.EXPAND)
  627. self.hidevbox.Add(self.textBox, proportion=0, flag=wx.EXPAND)
  628. self.posBox = self._positionWidget(panel)
  629. self.hidevbox.Add(self.posBox, proportion=0, flag=wx.EXPAND | wx.TOP, border=5)
  630. return self.hidevbox
  631. def _positionWidget(self, panel):
  632. grid = wx.GridBagSizer(vgap=5, hgap=5)
  633. label = wx.StaticText(panel, id=wx.ID_ANY, label=_("Placement as percentage of"
  634. " screen coordinates (X: 0, Y: 0 is top left):"))
  635. label.Wrap(400)
  636. self.spinX = wx.SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
  637. self.spinY = wx.SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
  638. self.spinX.Bind(wx.EVT_SPINCTRL, lambda evt, temp='X': self.OnPosition(evt, temp))
  639. self.spinY.Bind(wx.EVT_SPINCTRL, lambda evt, temp='Y': self.OnPosition(evt, temp))
  640. grid.Add(label, pos=(0, 0), span = (1, 4), flag = wx.EXPAND)
  641. grid.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("X:")), pos=(1, 0),
  642. flag = wx.ALIGN_CENTER_VERTICAL)
  643. grid.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Y:")), pos=(1, 2),
  644. flag = wx.ALIGN_CENTER_VERTICAL)
  645. grid.Add(self.spinX, pos=(1, 1))
  646. grid.Add(self.spinY, pos=(1, 3))
  647. return grid
  648. def _createExportFormatPanel(self, notebook):
  649. panel = wx.Panel(notebook, id=wx.ID_ANY)
  650. borderSizer = wx.BoxSizer(wx.VERTICAL)
  651. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  652. choices = [_("image sequence"), _("animated GIF"), _("SWF"), _("AVI")]
  653. self.formatChoice = wx.Choice(parent=panel, id=wx.ID_ANY,
  654. choices=choices)
  655. self.formatChoice.Bind(wx.EVT_CHOICE, lambda event: self.ChangeFormat(event.GetSelection()))
  656. hSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Export to:")),
  657. proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=2)
  658. hSizer.Add(item=self.formatChoice, proportion=1,
  659. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALL, border=2)
  660. borderSizer.Add(item=hSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  661. helpSizer = wx.BoxSizer(wx.HORIZONTAL)
  662. helpSizer.AddStretchSpacer(1)
  663. self.formatPanelSizer = wx.BoxSizer(wx.VERTICAL)
  664. helpSizer.Add(self.formatPanelSizer, proportion=5, flag=wx.EXPAND)
  665. borderSizer.Add(helpSizer, proportion=1, flag=wx.EXPAND)
  666. self.formatPanels = []
  667. # panel for image sequence
  668. imSeqPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  669. prefixLabel = wx.StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File prefix:"))
  670. self.prefixCtrl = wx.TextCtrl(imSeqPanel, id=wx.ID_ANY, value=_("animation_"))
  671. formatLabel = wx.StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File format:"))
  672. imageTypes = ['PNG', 'JPEG', 'GIF', 'TIFF', 'PPM', 'BMP']
  673. self.imSeqFormatChoice = wx.Choice(imSeqPanel, choices=imageTypes)
  674. self.imSeqFormatChoice.SetSelection(0)
  675. self.dirBrowse = filebrowse.DirBrowseButton(parent=imSeqPanel, id=wx.ID_ANY,
  676. labelText=_("Directory:"),
  677. dialogTitle=_("Choose directory for export"),
  678. buttonText=_("Browse"),
  679. startDirectory=os.getcwd())
  680. dirGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  681. dirGridSizer.AddGrowableCol(1)
  682. dirGridSizer.Add(prefixLabel, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  683. dirGridSizer.Add(self.prefixCtrl, pos=(0, 1), flag = wx.EXPAND)
  684. dirGridSizer.Add(formatLabel, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  685. dirGridSizer.Add(self.imSeqFormatChoice, pos=(1, 1), flag = wx.EXPAND)
  686. dirGridSizer.Add(self.dirBrowse, pos=(2, 0), flag = wx.EXPAND, span = (1, 2))
  687. imSeqPanel.SetSizer(dirGridSizer)
  688. dirGridSizer.Fit(imSeqPanel)
  689. self.formatPanelSizer.Add(item=imSeqPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  690. self.formatPanels.append(imSeqPanel)
  691. # panel for gif
  692. gifPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  693. self.gifBrowse = filebrowse.FileBrowseButton(parent=gifPanel, id=wx.ID_ANY,
  694. fileMask="GIF file (*.gif)|*.gif",
  695. labelText=_("GIF file:"),
  696. dialogTitle=_("Choose file to save animation"),
  697. buttonText=_("Browse"),
  698. startDirectory=os.getcwd(), fileMode=wx.SAVE)
  699. gifGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  700. gifGridSizer.AddGrowableCol(0)
  701. gifGridSizer.Add(self.gifBrowse, pos=(0, 0), flag = wx.EXPAND)
  702. gifPanel.SetSizer(gifGridSizer)
  703. gifGridSizer.Fit(gifPanel)
  704. self.formatPanelSizer.Add(item=gifPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  705. self.formatPanels.append(gifPanel)
  706. # panel for swf
  707. swfPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  708. self.swfBrowse = filebrowse.FileBrowseButton(parent=swfPanel, id=wx.ID_ANY,
  709. fileMask="SWF file (*.swf)|*.swf",
  710. labelText=_("SWF file:"),
  711. dialogTitle=_("Choose file to save animation"),
  712. buttonText=_("Browse"),
  713. startDirectory=os.getcwd(), fileMode=wx.SAVE)
  714. swfGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  715. swfGridSizer.AddGrowableCol(0)
  716. swfGridSizer.Add(self.swfBrowse, pos=(0, 0), flag = wx.EXPAND)
  717. swfPanel.SetSizer(swfGridSizer)
  718. swfGridSizer.Fit(swfPanel)
  719. self.formatPanelSizer.Add(item=swfPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  720. self.formatPanels.append(swfPanel)
  721. # panel for avi
  722. aviPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  723. ffmpeg = gcore.find_program('ffmpeg', '--help')
  724. if not ffmpeg:
  725. warning = _("Program 'ffmpeg' was not found.\nPlease install it first "
  726. "and make sure\nit's in the PATH variable.")
  727. warningLabel = wx.StaticText(parent=aviPanel, label=warning)
  728. warningLabel.SetForegroundColour(wx.RED)
  729. self.aviBrowse = filebrowse.FileBrowseButton(parent=aviPanel, id=wx.ID_ANY,
  730. fileMask="AVI file (*.avi)|*.avi",
  731. labelText=_("AVI file:"),
  732. dialogTitle=_("Choose file to save animation"),
  733. buttonText=_("Browse"),
  734. startDirectory=os.getcwd(), fileMode=wx.SAVE)
  735. encodingLabel = wx.StaticText(parent=aviPanel, id=wx.ID_ANY, label=_("Video codec:"))
  736. self.encodingText = wx.TextCtrl(parent=aviPanel, id=wx.ID_ANY, value='mpeg4')
  737. optionsLabel = wx.StaticText(parent=aviPanel, label=_("Additional options:"))
  738. self.optionsText = wx.TextCtrl(parent=aviPanel)
  739. self.optionsText.SetToolTipString(_("Consider adding '-sameq' or '-qscale 1' "
  740. "if not satisfied with video quality. "
  741. "Options depend on ffmpeg version."))
  742. aviGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  743. aviGridSizer.AddGrowableCol(1)
  744. aviGridSizer.Add(self.aviBrowse, pos=(0, 0), span = (1, 2), flag = wx.EXPAND)
  745. aviGridSizer.Add(encodingLabel, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  746. aviGridSizer.Add(self.encodingText, pos=(1, 1), flag = wx.EXPAND)
  747. aviGridSizer.Add(optionsLabel, pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
  748. aviGridSizer.Add(self.optionsText, pos=(2, 1), flag=wx.EXPAND)
  749. if not ffmpeg:
  750. aviGridSizer.Add(warningLabel, pos=(3, 0), span=(1, 2),
  751. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  752. aviPanel.SetSizer(aviGridSizer)
  753. aviGridSizer.Fit(aviPanel)
  754. self.formatPanelSizer.Add(item=aviPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  755. self.formatPanels.append(aviPanel)
  756. fpsSizer = wx.BoxSizer(wx.HORIZONTAL)
  757. fps = 1000 / self.timeTick
  758. fpsSizer.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Current frame rate: %.2f fps") % fps),
  759. proportion=1, flag=wx.EXPAND)
  760. borderSizer.Add(fpsSizer, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  761. panel.SetSizer(borderSizer)
  762. borderSizer.Fit(panel)
  763. self.ChangeFormat(index=0)
  764. return panel
  765. def ChangeFormat(self, index):
  766. for i, panel in enumerate(self.formatPanels):
  767. self.formatPanelSizer.Show(item=panel, show=(i == index))
  768. self.formatPanelSizer.Layout()
  769. def OnFont(self, event):
  770. index = self.listbox.GetSelection()
  771. # should not happen
  772. if index == wx.NOT_FOUND:
  773. return
  774. cdata = self.listbox.GetClientData(index)
  775. font = cdata['font']
  776. fontdata = wx.FontData()
  777. fontdata.EnableEffects(True)
  778. fontdata.SetColour('black')
  779. fontdata.SetInitialFont(font)
  780. dlg = wx.FontDialog(self, fontdata)
  781. dlg.CenterOnParent()
  782. if dlg.ShowModal() == wx.ID_OK:
  783. newfontdata = dlg.GetFontData()
  784. font = newfontdata.GetChosenFont()
  785. self.sampleLabel.SetFont(font)
  786. cdata['font'] = font
  787. self.Layout()
  788. def OnPosition(self, event, coord):
  789. index = self.listbox.GetSelection()
  790. # should not happen
  791. if index == wx.NOT_FOUND:
  792. return
  793. cdata = self.listbox.GetClientData(index)
  794. cdata['pos'][coord == 'Y'] = event.GetInt()
  795. def OnSetImage(self, event):
  796. index = self.listbox.GetSelection()
  797. # should not happen
  798. if index == wx.NOT_FOUND:
  799. return
  800. cdata = self.listbox.GetClientData(index)
  801. cdata['file'] = event.GetString()
  802. def OnAddDecoration(self, event, name):
  803. if name == 'time':
  804. timeInfo = {'name': name, 'font': self.GetFont(), 'pos': [10, 10]}
  805. self.decorations.append(timeInfo)
  806. elif name == 'image':
  807. imageInfo = {'name': name, 'file': '', 'pos': [10, 10]}
  808. self.decorations.append(imageInfo)
  809. elif name == 'text':
  810. textInfo = {'name': name, 'font': self.GetFont(), 'text': '', 'pos': [10, 10]}
  811. self.decorations.append(textInfo)
  812. self._updateListBox()
  813. self.listbox.SetSelection(self.listbox.GetCount() - 1)
  814. self.OnSelectionChanged(event=None)
  815. def OnSelectionChanged(self, event):
  816. index = self.listbox.GetSelection()
  817. if index == wx.NOT_FOUND:
  818. self._hideAll()
  819. return
  820. cdata = self.listbox.GetClientData(index)
  821. self.hidevbox.Show(self.fontBox, (cdata['name'] in ('time', 'text')))
  822. self.hidevbox.Show(self.imageBox, (cdata['name'] == 'image'))
  823. self.hidevbox.Show(self.textBox, (cdata['name'] == 'text'))
  824. self.hidevbox.Show(self.posBox, True)
  825. self.hidevbox.Show(self.informBox, False)
  826. self.spinX.SetValue(cdata['pos'][0])
  827. self.spinY.SetValue(cdata['pos'][1])
  828. if cdata['name'] == 'image':
  829. self.browse.SetValue(cdata['file'])
  830. elif cdata['name'] in ('time', 'text'):
  831. self.sampleLabel.SetFont(cdata['font'])
  832. if cdata['name'] == 'text':
  833. self.textCtrl.SetValue(cdata['text'])
  834. self.hidevbox.Layout()
  835. # self.Layout()
  836. def OnText(self, event):
  837. index = self.listbox.GetSelection()
  838. # should not happen
  839. if index == wx.NOT_FOUND:
  840. return
  841. cdata = self.listbox.GetClientData(index)
  842. cdata['text'] = event.GetString()
  843. def OnRemove(self, event):
  844. index = self.listbox.GetSelection()
  845. if index == wx.NOT_FOUND:
  846. return
  847. decData = self.listbox.GetClientData(index)
  848. self.decorations.remove(decData)
  849. self._updateListBox()
  850. if self.listbox.GetCount():
  851. self.listbox.SetSelection(0)
  852. self.OnSelectionChanged(event=None)
  853. def OnExport(self, event):
  854. for decor in self.decorations:
  855. if decor['name'] == 'image':
  856. if not os.path.exists(decor['file']):
  857. if decor['file']:
  858. GError(parent=self, message=_("File %s not found.") % decor['file'])
  859. else:
  860. GError(parent=self, message=_("Decoration image file is missing."))
  861. return
  862. if self.formatChoice.GetSelection() == 0:
  863. name = self.dirBrowse.GetValue()
  864. if not os.path.exists(name):
  865. if name:
  866. GError(parent=self, message=_("Directory %s not found.") % name)
  867. else:
  868. GError(parent=self, message=_("Export directory is missing."))
  869. return
  870. elif self.formatChoice.GetSelection() == 1:
  871. if not self.gifBrowse.GetValue():
  872. GError(parent=self, message=_("Export file is missing."))
  873. return
  874. elif self.formatChoice.GetSelection() == 2:
  875. if not self.swfBrowse.GetValue():
  876. GError(parent=self, message=_("Export file is missing."))
  877. return
  878. # hide only to keep previous values
  879. self.Hide()
  880. self.doExport.emit(exportInfo=self.GetExportInformation(),
  881. decorations=self.GetDecorations())
  882. def GetDecorations(self):
  883. return self.decorations
  884. def GetExportInformation(self):
  885. info = {}
  886. if self.formatChoice.GetSelection() == 0:
  887. info['method'] = 'sequence'
  888. info['directory'] = self.dirBrowse.GetValue()
  889. info['prefix'] = self.prefixCtrl.GetValue()
  890. info['format'] = self.imSeqFormatChoice.GetStringSelection()
  891. elif self.formatChoice.GetSelection() == 1:
  892. info['method'] = 'gif'
  893. info['file'] = self.gifBrowse.GetValue()
  894. elif self.formatChoice.GetSelection() == 2:
  895. info['method'] = 'swf'
  896. info['file'] = self.swfBrowse.GetValue()
  897. elif self.formatChoice.GetSelection() == 3:
  898. info['method'] = 'avi'
  899. info['file'] = self.aviBrowse.GetValue()
  900. info['encoding'] = self.encodingText.GetValue()
  901. info['options'] = self.optionsText.GetValue()
  902. return info
  903. def _updateListBox(self):
  904. self.listbox.Clear()
  905. names = {'time': _("Time stamp"), 'image': _("Image"), 'text': _("Text")}
  906. for decor in self.decorations:
  907. self.listbox.Append(names[decor['name']], clientData=decor)
  908. def _hideAll(self):
  909. self.hidevbox.Show(self.fontBox, False)
  910. self.hidevbox.Show(self.imageBox, False)
  911. self.hidevbox.Show(self.textBox, False)
  912. self.hidevbox.Show(self.posBox, False)
  913. self.hidevbox.Show(self.informBox, True)
  914. self.hidevbox.Layout()
  915. class AnimSimpleLayerManager(SimpleLayerManager):
  916. """!Simple layer manager for animation tool.
  917. Allows to add space-time dataset or series of maps.
  918. """
  919. def __init__(self, parent, layerList,
  920. lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_VECTOR |
  921. SIMPLE_LMGR_TB_TOP | SIMPLE_LMGR_STDS,
  922. toolbarCls=AnimSimpleLmgrToolbar, modal=True):
  923. SimpleLayerManager.__init__(self, parent, layerList, lmgrStyle, toolbarCls, modal)
  924. def OnAddStds(self, event):
  925. """!Opens dialog for specifying temporal dataset.
  926. Dummy layer is added first."""
  927. layer = AnimLayer()
  928. layer.hidden = True
  929. self._layerList.AddLayer(layer)
  930. self.SetStdsProperties(layer)
  931. event.Skip()
  932. def SetStdsProperties(self, layer):
  933. dlg = AddTemporalLayerDialog(parent=self, layer=layer)
  934. # first get hidden property, it's altered afterwards
  935. hidden = layer.hidden
  936. dlg.CenterOnParent()
  937. if dlg.ShowModal() == wx.ID_OK:
  938. layer = dlg.GetLayer()
  939. if hidden:
  940. signal = self.layerAdded
  941. else:
  942. signal = self.cmdChanged
  943. signal.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
  944. else:
  945. if hidden:
  946. self._layerList.RemoveLayer(layer)
  947. dlg.Destroy()
  948. self._update()
  949. self.anyChange.emit()
  950. def _layerChangeProperties(self, layer):
  951. """!Opens new module dialog or recycles it."""
  952. if not hasattr(layer, 'maps'):
  953. GUI(parent=self, giface=None,
  954. modal=self._modal).ParseCommand(cmd=layer.cmd,
  955. completed=(self.GetOptData, layer, ''))
  956. else:
  957. self.SetStdsProperties(layer)
  958. def Activate3D(self, activate=True):
  959. """!Activates/deactivates certain tool depending on 2D/3D view."""
  960. self._toolbar.EnableTools(['addRaster', 'addVector',
  961. 'opacity', 'up', 'down'], not activate)
  962. class AddTemporalLayerDialog(wx.Dialog):
  963. """!Dialog for adding space-time dataset/ map series."""
  964. def __init__(self, parent, layer, title=_("Add space-time dataset layer")):
  965. wx.Dialog.__init__(self, parent=parent, title=title)
  966. self.layer = layer
  967. self._mapType = None
  968. self._name = None
  969. self._cmd = None
  970. self.tselect = Select(parent=self, type='strds')
  971. iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
  972. bitmapPath = os.path.join(globalvar.ETCICONDIR, iconTheme, 'layer-open.png')
  973. if os.path.isfile(bitmapPath) and os.path.getsize(bitmapPath):
  974. bitmap = wx.Bitmap(name=bitmapPath)
  975. else:
  976. bitmap = wx.ArtProvider.GetBitmap(id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR)
  977. self.addManyMapsButton = wx.BitmapButton(self, bitmap=bitmap)
  978. self.addManyMapsButton.Bind(wx.EVT_BUTTON, self._onAddMaps)
  979. types = [('rast', _("Multiple raster maps")),
  980. ('vect', _("Multiple vector maps")),
  981. ('strds', _("Space time raster dataset")),
  982. ('stvds', _("Space time vector dataset"))]
  983. self._types = dict(types)
  984. self.tchoice = wx.Choice(parent=self)
  985. for type_, text in types:
  986. self.tchoice.Append(text, clientData=type_)
  987. self.editBtn = wx.Button(parent=self, label='Set properties')
  988. self.okBtn = wx.Button(parent=self, id=wx.ID_OK)
  989. self.cancelBtn = wx.Button(parent=self, id=wx.ID_CANCEL)
  990. self.okBtn.Bind(wx.EVT_BUTTON, self._onOK)
  991. self.editBtn.Bind(wx.EVT_BUTTON, self._onProperties)
  992. self.tchoice.Bind(wx.EVT_CHOICE,
  993. lambda evt: self._setType())
  994. self.tselect.Bind(wx.EVT_TEXT,
  995. lambda evt: self._datasetChanged())
  996. if self.layer.mapType:
  997. self._setType(self.layer.mapType)
  998. else:
  999. self._setType('rast')
  1000. if self.layer.name:
  1001. self.tselect.SetValue(self.layer.name)
  1002. if self.layer.cmd:
  1003. self._cmd = self.layer.cmd
  1004. self._layout()
  1005. self.SetSize(self.GetBestSize())
  1006. def _layout(self):
  1007. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1008. bodySizer = wx.BoxSizer(wx.VERTICAL)
  1009. typeSizer = wx.BoxSizer(wx.HORIZONTAL)
  1010. selectSizer = wx.BoxSizer(wx.HORIZONTAL)
  1011. typeSizer.Add(wx.StaticText(self, label=_("Input data type:")),
  1012. flag=wx.ALIGN_CENTER_VERTICAL)
  1013. typeSizer.AddStretchSpacer()
  1014. typeSizer.Add(self.tchoice)
  1015. bodySizer.Add(typeSizer, flag=wx.EXPAND | wx.BOTTOM, border=5)
  1016. selectSizer.Add(self.tselect, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=5)
  1017. selectSizer.Add(self.addManyMapsButton, flag=wx.EXPAND)
  1018. bodySizer.Add(selectSizer, flag=wx.BOTTOM, border=5)
  1019. bodySizer.Add(self.editBtn, flag=wx.BOTTOM, border=5)
  1020. mainSizer.Add(bodySizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  1021. btnSizer = wx.StdDialogButtonSizer()
  1022. btnSizer.AddButton(self.okBtn)
  1023. btnSizer.AddButton(self.cancelBtn)
  1024. btnSizer.Realize()
  1025. mainSizer.Add(btnSizer, proportion=0,
  1026. flag=wx.EXPAND | wx.ALL, border=10)
  1027. self.SetSizer(mainSizer)
  1028. mainSizer.Fit(self)
  1029. def _datasetChanged(self):
  1030. if self._name != self.tselect.GetValue():
  1031. self._name = self.tselect.GetValue()
  1032. self._cmd = None
  1033. def _setType(self, typeName=None):
  1034. if typeName:
  1035. self.tchoice.SetStringSelection(self._types[typeName])
  1036. self.tselect.SetType(typeName)
  1037. if typeName in ('strds', 'stvds'):
  1038. self.tselect.SetType(typeName, multiple=False)
  1039. self.addManyMapsButton.Disable()
  1040. else:
  1041. self.tselect.SetType(typeName, multiple=True)
  1042. self.addManyMapsButton.Enable()
  1043. self._mapType = typeName
  1044. self.tselect.SetValue('')
  1045. else:
  1046. typeName = self.tchoice.GetClientData(self.tchoice.GetSelection())
  1047. if typeName in ('strds', 'stvds'):
  1048. self.tselect.SetType(typeName, multiple=False)
  1049. self.addManyMapsButton.Disable()
  1050. else:
  1051. self.tselect.SetType(typeName, multiple=True)
  1052. self.addManyMapsButton.Enable()
  1053. if typeName != self._mapType:
  1054. self._cmd = None
  1055. self._mapType = typeName
  1056. self.tselect.SetValue('')
  1057. def _createDefaultCommand(self):
  1058. cmd = []
  1059. if self._mapType in ('rast', 'strds'):
  1060. cmd.append('d.rast')
  1061. elif self._mapType in ('vect', 'stvds'):
  1062. cmd.append('d.vect')
  1063. if self._name:
  1064. if self._mapType in ('rast', 'vect'):
  1065. cmd.append('map={}'.format(self._name.split(',')[0]))
  1066. else:
  1067. try:
  1068. maps = getRegisteredMaps(self._name, etype=self._mapType)
  1069. if maps:
  1070. cmd.append('map={}'.format(maps[0]))
  1071. except gcore.ScriptError, e:
  1072. GError(parent=self, message=str(e), showTraceback=False)
  1073. return None
  1074. return cmd
  1075. def _onAddMaps(self, event):
  1076. dlg = MapLayersDialog(self, title=_("Select raster/vector maps."))
  1077. dlg.applyAddingMapLayers.connect(lambda mapLayers:
  1078. self.tselect.SetValue(','.join(mapLayers)))
  1079. index = 0 if self._mapType == 'rast' else 1
  1080. dlg.layerType.SetSelection(index)
  1081. dlg.LoadMapLayers(dlg.GetLayerType(cmd=True),
  1082. dlg.mapset.GetStringSelection())
  1083. dlg.CenterOnParent()
  1084. if dlg.ShowModal() == wx.ID_OK:
  1085. self.tselect.SetValue(','.join(dlg.GetMapLayers()))
  1086. dlg.Destroy()
  1087. def _onProperties(self, event):
  1088. self._checkInput()
  1089. if self._cmd:
  1090. GUI(parent=self, show=True, modal=True).ParseCommand(cmd=self._cmd,
  1091. completed=(self._getOptData, '', ''))
  1092. def _checkInput(self):
  1093. if not self.tselect.GetValue():
  1094. GMessage(parent=self, message=_("Please select maps or dataset first."))
  1095. return
  1096. if not self._cmd:
  1097. self._cmd = self._createDefaultCommand()
  1098. def _getOptData(self, dcmd, layer, params, propwin):
  1099. if dcmd:
  1100. self._cmd = dcmd
  1101. def _onOK(self, event):
  1102. self._checkInput()
  1103. if self._cmd:
  1104. try:
  1105. self.layer.hidden = False
  1106. self.layer.mapType = self._mapType
  1107. self.layer.name = self._name
  1108. self.layer.cmd = self._cmd
  1109. event.Skip()
  1110. except (GException, gcore.ScriptError), e:
  1111. GError(parent=self, message=str(e))
  1112. def GetLayer(self):
  1113. return self.layer
  1114. def test():
  1115. import wx.lib.inspection
  1116. app = wx.PySimpleApp()
  1117. # testTemporalLayer()
  1118. # testAnimLmgr()
  1119. testAnimInput()
  1120. # wx.lib.inspection.InspectionTool().Show()
  1121. app.MainLoop()
  1122. def testAnimInput():
  1123. anim = AnimationData()
  1124. anim.SetDefaultValues(animationIndex=0, windowIndex=0)
  1125. dlg = InputDialog(parent=None, mode='add', animationData=anim)
  1126. dlg.Show()
  1127. def testAnimEdit():
  1128. anim = AnimationData()
  1129. anim.SetDefaultValues(animationIndex=0, windowIndex=0)
  1130. dlg = EditDialog(parent=None, animationData=[anim])
  1131. dlg.Show()
  1132. def testExport():
  1133. dlg = ExportDialog(parent=None, temporal=TemporalMode.TEMPORAL,
  1134. timeTick=200)
  1135. if dlg.ShowModal() == wx.ID_OK:
  1136. print dlg.GetDecorations()
  1137. print dlg.GetExportInformation()
  1138. dlg.Destroy()
  1139. else:
  1140. dlg.Destroy()
  1141. def testTemporalLayer():
  1142. frame = wx.Frame(None)
  1143. frame.Show()
  1144. layer = AnimLayer()
  1145. dlg = AddTemporalLayerDialog(parent=frame, layer=layer)
  1146. if dlg.ShowModal() == wx.ID_OK:
  1147. layer = dlg.GetLayer()
  1148. print layer.name, layer.cmd, layer.mapType
  1149. dlg.Destroy()
  1150. else:
  1151. dlg.Destroy()
  1152. def testAnimLmgr():
  1153. from core.layerlist import LayerList
  1154. frame = wx.Frame(None)
  1155. mgr = AnimSimpleLayerManager(parent=frame, layerList=LayerList())
  1156. frame.mgr = mgr
  1157. frame.Show()
  1158. if __name__ == '__main__':
  1159. gcore.set_raise_on_error(True)
  1160. test()