frame.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. """
  2. @package animation.frame
  3. @brief Animation frame and different types of sliders
  4. Classes:
  5. - frame::AnimationFrame
  6. - frame::AnimationsPanel
  7. - frame::AnimationSliderBase
  8. - frame::SimpleAnimationSlider
  9. - frame::TimeAnimationSlider
  10. (C) 2013 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Anna Petrasova <kratochanna gmail.com>
  14. """
  15. import os
  16. import sys
  17. import wx
  18. import wx.aui
  19. import tempfile
  20. import six
  21. import grass.script as gcore
  22. import grass.temporal as tgis
  23. from core import globalvar
  24. from gui_core.widgets import IntegerValidator
  25. from gui_core.wrap import StaticText, TextCtrl
  26. from core.gcmd import RunCommand
  27. from animation.mapwindow import AnimationWindow
  28. from animation.provider import BitmapProvider, BitmapPool, \
  29. MapFilesPool, CleanUp
  30. from animation.controller import AnimationController
  31. from animation.anim import Animation
  32. from animation.toolbars import MainToolbar, AnimationToolbar, MiscToolbar
  33. from animation.dialogs import SpeedDialog, PreferencesDialog
  34. from animation.utils import Orientation, ReplayMode, TemporalType
  35. MAX_COUNT = 4
  36. TMP_DIR = None
  37. gcore.set_raise_on_error(True)
  38. class AnimationFrame(wx.Frame):
  39. def __init__(self, parent, giface, title=_("GRASS GIS Animation tool"),
  40. rasters=None, timeseries=None):
  41. wx.Frame.__init__(self, parent, title=title,
  42. style=wx.DEFAULT_FRAME_STYLE, size=(800, 600))
  43. self._giface = giface
  44. self.SetClientSize(self.GetSize())
  45. self.iconsize = (16, 16)
  46. self.SetIcon(
  47. wx.Icon(
  48. os.path.join(
  49. globalvar.ICONDIR,
  50. 'grass_map.ico'),
  51. wx.BITMAP_TYPE_ICO))
  52. # Make sure the temporal database exists
  53. tgis.init()
  54. # create temporal directory and ensure it's deleted after programs ends
  55. # (stored in MAPSET/.tmp/)
  56. global TMP_DIR
  57. TMP_DIR = gcore.tempdir()
  58. self.animations = [Animation() for i in range(MAX_COUNT)]
  59. self.windows = []
  60. self.animationPanel = AnimationsPanel(
  61. self, self.windows, initialCount=MAX_COUNT)
  62. bitmapPool = BitmapPool()
  63. mapFilesPool = MapFilesPool()
  64. self._progressDlg = None
  65. self._progressDlgMax = None
  66. self.provider = BitmapProvider(
  67. bitmapPool=bitmapPool,
  68. mapFilesPool=mapFilesPool,
  69. tempDir=TMP_DIR)
  70. self.animationSliders = {}
  71. self.animationSliders['nontemporal'] = SimpleAnimationSlider(self)
  72. self.animationSliders['temporal'] = TimeAnimationSlider(self)
  73. self.controller = AnimationController(frame=self,
  74. sliders=self.animationSliders,
  75. animations=self.animations,
  76. mapwindows=self.windows,
  77. provider=self.provider,
  78. bitmapPool=bitmapPool,
  79. mapFilesPool=mapFilesPool)
  80. for win in self.windows:
  81. win.Bind(wx.EVT_SIZE, self.FrameSizeChanged)
  82. self.provider.mapsLoaded.connect(lambda: self.SetStatusText(''))
  83. self.provider.renderingStarted.connect(self._showRenderingProgress)
  84. self.provider.renderingContinues.connect(self._updateProgress)
  85. self.provider.renderingFinished.connect(self._closeProgress)
  86. self.provider.compositionStarted.connect(
  87. self._showRenderingProgress)
  88. self.provider.compositionContinues.connect(self._updateProgress)
  89. self.provider.compositionFinished.connect(self._closeProgress)
  90. self.InitStatusbar()
  91. self._mgr = wx.aui.AuiManager(self)
  92. # toolbars
  93. self.toolbars = {}
  94. tb = ['miscToolbar', 'animationToolbar', 'mainToolbar']
  95. if sys.platform == 'win32':
  96. tb.reverse()
  97. for toolb in tb:
  98. self._addToolbar(toolb)
  99. self._addPanes()
  100. self._mgr.Update()
  101. self.dialogs = dict()
  102. self.dialogs['speed'] = None
  103. self.dialogs['preferences'] = None
  104. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  105. def InitStatusbar(self):
  106. """Init statusbar."""
  107. self.CreateStatusBar(number=1, style=0)
  108. def _addPanes(self):
  109. self._mgr.AddPane(self.animationPanel,
  110. wx.aui.AuiPaneInfo().CentrePane().
  111. Name('animPanel').CentrePane().CaptionVisible(False).PaneBorder(False).
  112. Floatable(False).BestSize((-1, -1)).
  113. CloseButton(False).DestroyOnClose(True).Layer(0))
  114. for name, slider in six.iteritems(self.animationSliders):
  115. self._mgr.AddPane(
  116. slider,
  117. wx.aui.AuiPaneInfo().PaneBorder(False).Name(
  118. 'slider_' +
  119. name). Layer(1).CaptionVisible(False).BestSize(
  120. slider.GetBestSize()). DestroyOnClose(True).CloseButton(False).Bottom())
  121. self._mgr.GetPane('slider_' + name).Hide()
  122. def _addToolbar(self, name):
  123. """Add defined toolbar to the window
  124. Currently known toolbars are:
  125. - 'mainToolbar' - data management
  126. - 'animationToolbar' - animation controls
  127. - 'miscToolbar' - help, close
  128. """
  129. if name == "mainToolbar":
  130. self.toolbars[name] = MainToolbar(self)
  131. self._mgr.AddPane(self.toolbars[name],
  132. wx.aui.AuiPaneInfo().
  133. Name('mainToolbar').Caption(_("Main Toolbar")).
  134. ToolbarPane().Top().
  135. LeftDockable(False).RightDockable(False).
  136. BottomDockable(True).TopDockable(True).
  137. CloseButton(False).Layer(2).Row(1).
  138. BestSize((self.toolbars['mainToolbar'].GetBestSize())))
  139. elif name == 'animationToolbar':
  140. self.toolbars[name] = AnimationToolbar(self)
  141. self._mgr.AddPane(self.toolbars[name],
  142. wx.aui.AuiPaneInfo().
  143. Name('animationToolbar').Caption(_("Animation Toolbar")).
  144. ToolbarPane().Top().
  145. LeftDockable(False).RightDockable(False).
  146. BottomDockable(True).TopDockable(True).
  147. CloseButton(False).Layer(2).Row(1).
  148. BestSize((self.toolbars['animationToolbar'].GetBestSize())))
  149. self.controller.SetAnimationToolbar(
  150. self.toolbars['animationToolbar'])
  151. elif name == 'miscToolbar':
  152. self.toolbars[name] = MiscToolbar(self)
  153. self._mgr.AddPane(self.toolbars[name],
  154. wx.aui.AuiPaneInfo().
  155. Name('miscToolbar').Caption(_("Misc Toolbar")).
  156. ToolbarPane().Top().
  157. LeftDockable(False).RightDockable(False).
  158. BottomDockable(True).TopDockable(True).
  159. CloseButton(False).Layer(2).Row(1).
  160. BestSize((self.toolbars['miscToolbar'].GetBestSize())))
  161. def SetAnimations(self, layerLists):
  162. """Set animation data
  163. :param layerLists: list of layerLists
  164. """
  165. self.controller.SetAnimations(layerLists)
  166. def OnAddAnimation(self, event):
  167. self.controller.AddAnimation()
  168. def AddWindow(self, index):
  169. self.animationPanel.AddWindow(index)
  170. def RemoveWindow(self, index):
  171. self.animationPanel.RemoveWindow(index)
  172. def IsWindowShown(self, index):
  173. return self.animationPanel.IsWindowShown(index)
  174. def OnEditAnimation(self, event):
  175. self.controller.EditAnimations()
  176. def SetSlider(self, name):
  177. if name == 'nontemporal':
  178. self._mgr.GetPane('slider_nontemporal').Show()
  179. self._mgr.GetPane('slider_temporal').Hide()
  180. elif name == 'temporal':
  181. self._mgr.GetPane('slider_temporal').Show()
  182. self._mgr.GetPane('slider_nontemporal').Hide()
  183. else:
  184. self._mgr.GetPane('slider_temporal').Hide()
  185. self._mgr.GetPane('slider_nontemporal').Hide()
  186. self._mgr.Update()
  187. def OnPlayForward(self, event):
  188. self.controller.SetOrientation(Orientation.FORWARD)
  189. self.controller.StartAnimation()
  190. def OnPlayBack(self, event):
  191. self.controller.SetOrientation(Orientation.BACKWARD)
  192. self.controller.StartAnimation()
  193. def OnPause(self, event):
  194. self.controller.PauseAnimation(paused=event.IsChecked())
  195. def OnStop(self, event):
  196. self.controller.EndAnimation()
  197. def OnOneDirectionReplay(self, event):
  198. if event.IsChecked():
  199. mode = ReplayMode.REPEAT
  200. else:
  201. mode = ReplayMode.ONESHOT
  202. self.controller.SetReplayMode(mode)
  203. def OnBothDirectionReplay(self, event):
  204. if event.IsChecked():
  205. mode = ReplayMode.REVERSE
  206. else:
  207. mode = ReplayMode.ONESHOT
  208. self.controller.SetReplayMode(mode)
  209. def OnAdjustSpeed(self, event):
  210. win = self.dialogs['speed']
  211. if win:
  212. win.SetTemporalMode(self.controller.GetTemporalMode())
  213. win.SetTimeGranularity(self.controller.GetTimeGranularity())
  214. win.InitTimeSpin(self.controller.GetTimeTick())
  215. if win.IsShown():
  216. win.SetFocus()
  217. else:
  218. win.Show()
  219. else: # start
  220. win = SpeedDialog(
  221. self, temporalMode=self.controller.GetTemporalMode(),
  222. timeGranularity=self.controller.GetTimeGranularity(),
  223. initialSpeed=self.controller.timeTick)
  224. win.CenterOnParent()
  225. self.dialogs['speed'] = win
  226. win.speedChanged.connect(self.ChangeSpeed)
  227. win.Show()
  228. def ChangeSpeed(self, ms):
  229. self.controller.timeTick = ms
  230. def Reload(self, event):
  231. self.controller.Reload()
  232. def _showRenderingProgress(self, count):
  233. # the message is not really visible, it's there for the initial dlg
  234. # size
  235. self._progressDlg = wx.ProgressDialog(
  236. title=_("Loading data"),
  237. message="Loading data started, please be patient.",
  238. maximum=count,
  239. parent=self,
  240. style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
  241. self._progressDlgMax = count
  242. def _updateProgress(self, current, text):
  243. text += _(" ({c} out of {p})").format(c=current,
  244. p=self._progressDlgMax)
  245. keepGoing, skip = self._progressDlg.Update(current, text)
  246. if not keepGoing:
  247. self.provider.RequestStopRendering()
  248. def _closeProgress(self):
  249. self._progressDlg.Destroy()
  250. self._progressDlg = None
  251. def OnExportAnimation(self, event):
  252. self.controller.Export()
  253. def FrameSizeChanged(self, event):
  254. maxWidth = maxHeight = 0
  255. for win in self.windows:
  256. w, h = win.GetClientSize()
  257. if w >= maxWidth and h >= maxHeight:
  258. maxWidth, maxHeight = w, h
  259. self.provider.WindowSizeChanged(maxWidth, maxHeight)
  260. event.Skip()
  261. def OnPreferences(self, event):
  262. if not self.dialogs['preferences']:
  263. dlg = PreferencesDialog(parent=self, giface=self._giface)
  264. self.dialogs['preferences'] = dlg
  265. dlg.formatChanged.connect(
  266. lambda: self.controller.UpdateAnimations())
  267. dlg.CenterOnParent()
  268. self.dialogs['preferences'].ShowModal()
  269. def OnHelp(self, event):
  270. RunCommand('g.manual',
  271. quiet=True,
  272. entry='wxGUI.animation')
  273. def OnCloseWindow(self, event):
  274. if self.controller.timer.IsRunning():
  275. self.controller.timer.Stop()
  276. CleanUp(TMP_DIR)()
  277. self._mgr.UnInit()
  278. self.Destroy()
  279. def __del__(self):
  280. """It might not be called, therefore we try to clean it all in OnCloseWindow."""
  281. if hasattr(self, 'controller') and hasattr(self.controller, 'timer'):
  282. if self.controller.timer.IsRunning():
  283. self.controller.timer.Stop()
  284. CleanUp(TMP_DIR)()
  285. class AnimationsPanel(wx.Panel):
  286. def __init__(self, parent, windows, initialCount=4):
  287. wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.NO_BORDER)
  288. self.shown = []
  289. self.count = initialCount
  290. self.mainSizer = wx.FlexGridSizer(cols=2, hgap=0, vgap=0)
  291. for i in range(initialCount):
  292. w = AnimationWindow(self)
  293. windows.append(w)
  294. self.mainSizer.Add(w, proportion=1, flag=wx.EXPAND)
  295. self.mainSizer.AddGrowableCol(0)
  296. self.mainSizer.AddGrowableCol(1)
  297. self.mainSizer.AddGrowableRow(0)
  298. self.mainSizer.AddGrowableRow(1)
  299. self.windows = windows
  300. self.SetSizerAndFit(self.mainSizer)
  301. for i in range(initialCount):
  302. self.mainSizer.Hide(windows[i])
  303. self.Layout()
  304. def AddWindow(self, index):
  305. if len(self.shown) == self.count:
  306. return
  307. self.mainSizer.Show(self.windows[index])
  308. self.shown.append(index)
  309. self.Layout()
  310. def RemoveWindow(self, index):
  311. if len(self.shown) == 0:
  312. return
  313. self.mainSizer.Hide(self.windows[index])
  314. self.shown.remove(index)
  315. self.Layout()
  316. def IsWindowShown(self, index):
  317. return self.mainSizer.IsShown(self.windows[index])
  318. class AnimationSliderBase(wx.Panel):
  319. def __init__(self, parent):
  320. wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
  321. self.label1 = StaticText(self, id=wx.ID_ANY)
  322. self.slider = wx.Slider(self, id=wx.ID_ANY, style=wx.SL_HORIZONTAL)
  323. self.indexField = TextCtrl(self, id=wx.ID_ANY, size=(40, -1),
  324. style=wx.TE_PROCESS_ENTER | wx.TE_RIGHT,
  325. validator=IntegerValidator())
  326. self.callbackSliderChanging = None
  327. self.callbackSliderChanged = None
  328. self.callbackFrameIndexChanged = None
  329. self.framesCount = 0
  330. self.enable = True
  331. self.slider.Bind(wx.EVT_SPIN, self.OnSliderChanging)
  332. self.slider.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.OnSliderChanged)
  333. self.indexField.Bind(wx.EVT_TEXT_ENTER, self.OnFrameIndexChanged)
  334. def UpdateFrame(self, index):
  335. self._updateFrameIndex(index)
  336. if not self.enable:
  337. return
  338. self.slider.SetValue(index)
  339. def _updateFrameIndex(self, index):
  340. raise NotImplementedError
  341. def OnFrameIndexChanged(self, event):
  342. self._onFrameIndexChanged(event)
  343. def SetFrames(self, frames):
  344. self._setFrames(frames)
  345. def _setFrames(self, frames):
  346. raise NotImplementedError
  347. def SetCallbackSliderChanging(self, callback):
  348. self.callbackSliderChanging = callback
  349. def SetCallbackSliderChanged(self, callback):
  350. self.callbackSliderChanged = callback
  351. def SetCallbackFrameIndexChanged(self, callback):
  352. self.callbackFrameIndexChanged = callback
  353. def EnableSlider(self, enable=True):
  354. if enable and self.framesCount <= 1:
  355. enable = False # we don't want to enable it
  356. self.enable = enable
  357. self.slider.Enable(enable)
  358. self.indexField.Enable(enable)
  359. def OnSliderChanging(self, event):
  360. self.callbackSliderChanging(event.GetInt())
  361. def OnSliderChanged(self, event):
  362. self.callbackSliderChanged()
  363. def _onFrameIndexChanged(self, event):
  364. index = self.indexField.GetValue()
  365. index = self._validate(index)
  366. if index is not None:
  367. self.slider.SetValue(index)
  368. self.callbackFrameIndexChanged(index)
  369. def _validate(self, index):
  370. try:
  371. index = int(index)
  372. except ValueError:
  373. index = self.slider.GetValue()
  374. self.indexField.SetValue(str(index + 1))
  375. return None
  376. start, end = self.slider.GetRange()
  377. index -= 1
  378. if index > end:
  379. index = end
  380. self.indexField.SetValue(str(end + 1))
  381. elif index < start:
  382. index = start
  383. self.indexField.SetValue(str(start + 1))
  384. return index
  385. class SimpleAnimationSlider(AnimationSliderBase):
  386. def __init__(self, parent):
  387. AnimationSliderBase.__init__(self, parent)
  388. self._setLabel()
  389. self._doLayout()
  390. def _doLayout(self):
  391. hbox = wx.BoxSizer(wx.HORIZONTAL)
  392. hbox.Add(self.indexField, proportion=0,
  393. flag=wx.ALIGN_CENTER | wx.LEFT, border=5)
  394. hbox.Add(self.label1, proportion=0,
  395. flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border=5)
  396. hbox.Add(
  397. self.slider,
  398. proportion=1,
  399. flag=wx.ALIGN_CENTER | wx.EXPAND,
  400. border=0)
  401. self.SetSizerAndFit(hbox)
  402. def _setFrames(self, count):
  403. self.framesCount = count
  404. if self.framesCount > 1:
  405. self.slider.SetRange(0, self.framesCount - 1)
  406. self.EnableSlider(True)
  407. else:
  408. self.EnableSlider(False)
  409. self._setLabel()
  410. def _setLabel(self):
  411. label = "/ %(framesCount)s" % {'framesCount': self.framesCount}
  412. self.label1.SetLabel(label)
  413. self.Layout()
  414. def _updateFrameIndex(self, index):
  415. self.indexField.SetValue(str(index + 1))
  416. class TimeAnimationSlider(AnimationSliderBase):
  417. def __init__(self, parent):
  418. AnimationSliderBase.__init__(self, parent)
  419. self.timeLabels = []
  420. self.label2 = StaticText(self, id=wx.ID_ANY)
  421. self.label3 = StaticText(self, id=wx.ID_ANY)
  422. self.label2Length = 0
  423. self.temporalType = TemporalType.RELATIVE
  424. self._setLabel()
  425. self._doLayout()
  426. def _doLayout(self):
  427. vbox = wx.BoxSizer(wx.VERTICAL)
  428. hbox = wx.BoxSizer(wx.HORIZONTAL)
  429. hbox.Add(self.label1, proportion=0,
  430. flag=wx.ALIGN_CENTER_VERTICAL, border=0)
  431. hbox.AddStretchSpacer()
  432. hbox.Add(self.indexField, proportion=0,
  433. flag=wx.ALIGN_CENTER_VERTICAL, border=0)
  434. hbox.Add(self.label2, proportion=0,
  435. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=3)
  436. hbox.AddStretchSpacer()
  437. hbox.Add(self.label3, proportion=0,
  438. flag=wx.ALIGN_CENTER_VERTICAL, border=0)
  439. vbox.Add(hbox, proportion=0, flag=wx.EXPAND, border=0)
  440. hbox = wx.BoxSizer(wx.HORIZONTAL)
  441. hbox.Add(
  442. self.slider,
  443. proportion=1,
  444. flag=wx.ALIGN_CENTER | wx.EXPAND,
  445. border=0)
  446. vbox.Add(hbox, proportion=0, flag=wx.EXPAND, border=0)
  447. self._setTemporalType()
  448. self.SetSizerAndFit(vbox)
  449. def _setTemporalType(self):
  450. sizer = self.indexField.GetContainingSizer()
  451. # sizer.Show(self.indexField, False) # TODO: what to do?
  452. sizer.Show(self.indexField, self.temporalType == TemporalType.RELATIVE)
  453. self.Layout()
  454. def SetTemporalType(self, mode):
  455. self.temporalType = mode
  456. self._setTemporalType()
  457. def _setFrames(self, timeLabels):
  458. self.timeLabels = timeLabels
  459. self.framesCount = len(timeLabels)
  460. if self.framesCount > 1:
  461. self.slider.SetRange(0, self.framesCount - 1)
  462. self.EnableSlider(True)
  463. else:
  464. self.EnableSlider(False)
  465. self._setLabel()
  466. # TODO: fix setting index values, until then:
  467. self.indexField.Disable()
  468. def _setLabel(self):
  469. if self.timeLabels:
  470. if self.temporalType == TemporalType.ABSOLUTE:
  471. start = self.timeLabels[0][0]
  472. self.label1.SetLabel(start)
  473. if self.timeLabels[-1][1]:
  474. end = self.timeLabels[-1][1]
  475. else:
  476. end = self.timeLabels[-1][0]
  477. self.label3.SetLabel(end)
  478. else:
  479. unit = self.timeLabels[0][2]
  480. start = self.timeLabels[0][0]
  481. self.label1.SetLabel(start)
  482. if self.timeLabels[-1][1]:
  483. end = self.timeLabels[-1][1]
  484. else:
  485. end = self.timeLabels[-1][0]
  486. end = "%(end)s %(unit)s" % {'end': end, 'unit': unit}
  487. self.label3.SetLabel(end)
  488. self.label2Length = len(start)
  489. self._updateFrameIndex(0)
  490. else:
  491. self.label1.SetLabel("")
  492. self.label2.SetLabel("")
  493. self.label3.SetLabel("")
  494. self.Layout()
  495. def _updateFrameIndex(self, index):
  496. start = self.timeLabels[index][0]
  497. if self.timeLabels[index][1]: # interval
  498. if self.temporalType == TemporalType.ABSOLUTE:
  499. label = _("%(from)s %(dash)s %(to)s") % {
  500. 'from': start,
  501. 'dash': u"\u2013",
  502. 'to': self.timeLabels[index][1]}
  503. else:
  504. label = _("to %(to)s") % {'to': self.timeLabels[index][1]}
  505. else:
  506. if self.temporalType == TemporalType.ABSOLUTE:
  507. label = start
  508. else:
  509. label = ''
  510. self.label2.SetLabel(label)
  511. if self.temporalType == TemporalType.RELATIVE:
  512. self.indexField.SetValue(start)
  513. if len(label) != self.label2Length:
  514. self.label2Length = len(label)
  515. self.Layout()