frame.py 21 KB

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