frame.py 21 KB

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