dialogs.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151
  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. from __future__ import print_function
  17. import os
  18. import wx
  19. import copy
  20. import datetime
  21. import wx.lib.filebrowsebutton as filebrowse
  22. import wx.lib.scrolledpanel as SP
  23. import wx.lib.colourselect as csel
  24. try:
  25. from wx.adv import HyperlinkCtrl
  26. except ImportError:
  27. from wx import HyperlinkCtrl
  28. from core.gcmd import GMessage, GError, GException
  29. from core import globalvar
  30. from gui_core.dialogs import MapLayersDialog, GetImageHandlers
  31. from gui_core.preferences import PreferencesBaseDialog
  32. from gui_core.forms import GUI
  33. from core.settings import UserSettings
  34. from gui_core.gselect import Select
  35. from gui_core.widgets import FloatValidator
  36. from gui_core.wrap import (
  37. BitmapButton,
  38. Button,
  39. CheckBox,
  40. Choice,
  41. ComboBox,
  42. EmptyImage,
  43. RadioButton,
  44. SpinCtrl,
  45. StaticBox,
  46. StaticText,
  47. TextCtrl,
  48. )
  49. from animation.utils import (
  50. TemporalMode,
  51. getRegisteredMaps,
  52. getNameAndLayer,
  53. getCpuCount,
  54. )
  55. from animation.data import AnimationData, AnimLayer
  56. from animation.toolbars import AnimSimpleLmgrToolbar, SIMPLE_LMGR_STDS
  57. from gui_core.simplelmgr import (
  58. SimpleLayerManager,
  59. SIMPLE_LMGR_RASTER,
  60. SIMPLE_LMGR_VECTOR,
  61. SIMPLE_LMGR_TB_TOP,
  62. )
  63. from grass.pydispatch.signal import Signal
  64. import grass.script.core as gcore
  65. class SpeedDialog(wx.Dialog):
  66. def __init__(
  67. self,
  68. parent,
  69. title=_("Adjust speed of animation"),
  70. temporalMode=None,
  71. minimumDuration=0,
  72. timeGranularity=None,
  73. initialSpeed=200,
  74. ):
  75. wx.Dialog.__init__(
  76. self,
  77. parent=parent,
  78. id=wx.ID_ANY,
  79. title=title,
  80. style=wx.DEFAULT_DIALOG_STYLE,
  81. )
  82. # signal emitted when speed has changed; has attribute 'ms'
  83. self.speedChanged = Signal("SpeedDialog.speedChanged")
  84. self.minimumDuration = minimumDuration
  85. # self.framesCount = framesCount
  86. self.defaultSpeed = initialSpeed
  87. self.lastAppliedValue = self.defaultSpeed
  88. self.lastAppliedValueTemp = self.defaultSpeed
  89. self._layout()
  90. self.temporalMode = temporalMode
  91. self.timeGranularity = timeGranularity
  92. self._fillUnitChoice(self.choiceUnits)
  93. self.InitTimeSpin(self.defaultSpeed)
  94. def SetTimeGranularity(self, gran):
  95. self._timeGranularity = gran
  96. def GetTimeGranularity(self):
  97. return self._timeGranularity
  98. timeGranularity = property(fset=SetTimeGranularity, fget=GetTimeGranularity)
  99. def SetTemporalMode(self, mode):
  100. self._temporalMode = mode
  101. self._setTemporalMode()
  102. def GetTemporalMode(self):
  103. return self._temporalMode
  104. temporalMode = property(fset=SetTemporalMode, fget=GetTemporalMode)
  105. def _layout(self):
  106. """Layout window"""
  107. mainSizer = wx.BoxSizer(wx.VERTICAL)
  108. #
  109. # simple mode
  110. #
  111. self.nontemporalBox = StaticBox(
  112. parent=self, id=wx.ID_ANY, label=" %s " % _("Simple mode")
  113. )
  114. box = wx.StaticBoxSizer(self.nontemporalBox, wx.VERTICAL)
  115. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  116. labelDuration = StaticText(self, id=wx.ID_ANY, label=_("Frame duration:"))
  117. labelUnits = StaticText(self, id=wx.ID_ANY, label=_("ms"))
  118. self.spinDuration = SpinCtrl(
  119. self,
  120. id=wx.ID_ANY,
  121. min=self.minimumDuration,
  122. max=10000,
  123. initial=self.defaultSpeed,
  124. )
  125. # TODO total time
  126. gridSizer.Add(
  127. labelDuration, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
  128. )
  129. gridSizer.Add(self.spinDuration, pos=(0, 1), flag=wx.ALIGN_CENTER)
  130. gridSizer.Add(
  131. labelUnits, pos=(0, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
  132. )
  133. gridSizer.AddGrowableCol(0)
  134. box.Add(gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
  135. self.nontemporalSizer = gridSizer
  136. mainSizer.Add(box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  137. #
  138. # temporal mode
  139. #
  140. self.temporalBox = StaticBox(
  141. parent=self, id=wx.ID_ANY, label=" %s " % _("Temporal mode")
  142. )
  143. box = wx.StaticBoxSizer(self.temporalBox, wx.VERTICAL)
  144. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  145. labelTimeUnit = StaticText(self, id=wx.ID_ANY, label=_("Time unit:"))
  146. labelDuration = StaticText(
  147. self, id=wx.ID_ANY, label=_("Duration of time unit:")
  148. )
  149. labelUnits = StaticText(self, id=wx.ID_ANY, label=_("ms"))
  150. self.spinDurationTemp = SpinCtrl(
  151. self,
  152. id=wx.ID_ANY,
  153. min=self.minimumDuration,
  154. max=10000,
  155. initial=self.defaultSpeed,
  156. )
  157. self.choiceUnits = wx.Choice(self, id=wx.ID_ANY)
  158. # TODO total time
  159. gridSizer.Add(
  160. labelTimeUnit, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
  161. )
  162. gridSizer.Add(self.choiceUnits, pos=(0, 1), flag=wx.ALIGN_CENTER | wx.EXPAND)
  163. gridSizer.Add(
  164. labelDuration, pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
  165. )
  166. gridSizer.Add(
  167. self.spinDurationTemp, pos=(1, 1), flag=wx.ALIGN_CENTER | wx.EXPAND
  168. )
  169. gridSizer.Add(
  170. labelUnits, pos=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
  171. )
  172. gridSizer.AddGrowableCol(1)
  173. self.temporalSizer = gridSizer
  174. box.Add(gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
  175. mainSizer.Add(box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  176. self.btnOk = Button(self, wx.ID_OK)
  177. self.btnApply = Button(self, wx.ID_APPLY)
  178. self.btnCancel = Button(self, wx.ID_CANCEL)
  179. self.btnOk.SetDefault()
  180. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  181. self.btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  182. self.btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  183. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  184. # button sizer
  185. btnStdSizer = wx.StdDialogButtonSizer()
  186. btnStdSizer.AddButton(self.btnOk)
  187. btnStdSizer.AddButton(self.btnApply)
  188. btnStdSizer.AddButton(self.btnCancel)
  189. btnStdSizer.Realize()
  190. mainSizer.Add(btnStdSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  191. self.SetSizer(mainSizer)
  192. mainSizer.Fit(self)
  193. def _setTemporalMode(self):
  194. self.nontemporalBox.Enable(self.temporalMode == TemporalMode.NONTEMPORAL)
  195. self.temporalBox.Enable(self.temporalMode == TemporalMode.TEMPORAL)
  196. for child in self.temporalSizer.GetChildren():
  197. child.GetWindow().Enable(self.temporalMode == TemporalMode.TEMPORAL)
  198. for child in self.nontemporalSizer.GetChildren():
  199. child.GetWindow().Enable(self.temporalMode == TemporalMode.NONTEMPORAL)
  200. self.Layout()
  201. def _fillUnitChoice(self, choiceWidget):
  202. timeUnitsChoice = [
  203. _("year"),
  204. _("month"),
  205. _("day"),
  206. _("hour"),
  207. _("minute"),
  208. _("second"),
  209. ]
  210. timeUnits = ["years", "months", "days", "hours", "minutes", "seconds"]
  211. for item, cdata in zip(timeUnitsChoice, timeUnits):
  212. choiceWidget.Append(item, cdata)
  213. if self.temporalMode == TemporalMode.TEMPORAL:
  214. unit = self.timeGranularity[1]
  215. index = 0
  216. for i, timeUnit in enumerate(timeUnits):
  217. if timeUnit.startswith(unit):
  218. index = i
  219. break
  220. choiceWidget.SetSelection(index)
  221. else:
  222. choiceWidget.SetSelection(0)
  223. def OnOk(self, event):
  224. self._apply()
  225. self.OnCancel(None)
  226. def OnApply(self, event):
  227. self._apply()
  228. def OnCancel(self, event):
  229. self.spinDuration.SetValue(self.lastAppliedValue)
  230. self.spinDurationTemp.SetValue(self.lastAppliedValueTemp)
  231. self.Hide()
  232. def InitTimeSpin(self, timeTick):
  233. if self.temporalMode == TemporalMode.TEMPORAL:
  234. index = self.choiceUnits.GetSelection()
  235. unit = self.choiceUnits.GetClientData(index)
  236. delta = self._timedelta(unit=unit, number=1)
  237. seconds1 = self._total_seconds(delta)
  238. number, unit = self.timeGranularity
  239. number = float(number)
  240. delta = self._timedelta(unit=unit, number=number)
  241. seconds2 = self._total_seconds(delta)
  242. value = timeTick
  243. ms = value * seconds1 / float(seconds2)
  244. self.spinDurationTemp.SetValue(ms)
  245. else:
  246. self.spinDuration.SetValue(timeTick)
  247. def _apply(self):
  248. if self.temporalMode == TemporalMode.NONTEMPORAL:
  249. ms = self.spinDuration.GetValue()
  250. self.lastAppliedValue = self.spinDuration.GetValue()
  251. elif self.temporalMode == TemporalMode.TEMPORAL:
  252. index = self.choiceUnits.GetSelection()
  253. unit = self.choiceUnits.GetClientData(index)
  254. delta = self._timedelta(unit=unit, number=1)
  255. seconds1 = self._total_seconds(delta)
  256. number, unit = self.timeGranularity
  257. number = float(number)
  258. delta = self._timedelta(unit=unit, number=number)
  259. seconds2 = self._total_seconds(delta)
  260. value = self.spinDurationTemp.GetValue()
  261. ms = value * seconds2 / float(seconds1)
  262. # minimumDuration set to 0, too restrictive
  263. if ms < self.minimumDuration:
  264. GMessage(parent=self, message=_("Animation speed is too high."))
  265. return
  266. self.lastAppliedValueTemp = self.spinDurationTemp.GetValue()
  267. else:
  268. return
  269. self.speedChanged.emit(ms=ms)
  270. def _timedelta(self, unit, number):
  271. if unit in "years":
  272. delta = datetime.timedelta(days=365.25 * number)
  273. elif unit in "months":
  274. delta = datetime.timedelta(days=30.4375 * number) # 365.25/12
  275. elif unit in "days":
  276. delta = datetime.timedelta(days=1 * number)
  277. elif unit in "hours":
  278. delta = datetime.timedelta(hours=1 * number)
  279. elif unit in "minutes":
  280. delta = datetime.timedelta(minutes=1 * number)
  281. elif unit in "seconds":
  282. delta = datetime.timedelta(seconds=1 * number)
  283. return delta
  284. def _total_seconds(self, delta):
  285. """timedelta.total_seconds is new in version 2.7."""
  286. return delta.seconds + delta.days * 24 * 3600
  287. class InputDialog(wx.Dialog):
  288. def __init__(self, parent, mode, animationData):
  289. wx.Dialog.__init__(
  290. self,
  291. parent=parent,
  292. id=wx.ID_ANY,
  293. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  294. )
  295. if mode == "add":
  296. self.SetTitle(_("Add new animation"))
  297. elif mode == "edit":
  298. self.SetTitle(_("Edit animation"))
  299. self.animationData = animationData
  300. self._tmpLegendCmd = None
  301. self._layout()
  302. self.OnViewMode(event=None)
  303. def _layout(self):
  304. self.notebook = wx.Notebook(parent=self, style=wx.BK_DEFAULT)
  305. sizer = wx.BoxSizer(wx.VERTICAL)
  306. self.notebook.AddPage(self._createGeneralPage(self.notebook), _("General"))
  307. self.notebook.AddPage(self._createAdvancedPage(self.notebook), _("Advanced"))
  308. sizer.Add(self.notebook, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
  309. # buttons
  310. self.btnOk = Button(self, wx.ID_OK)
  311. self.btnCancel = Button(self, wx.ID_CANCEL)
  312. self.btnOk.SetDefault()
  313. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  314. # button sizer
  315. btnStdSizer = wx.StdDialogButtonSizer()
  316. btnStdSizer.AddButton(self.btnOk)
  317. btnStdSizer.AddButton(self.btnCancel)
  318. btnStdSizer.Realize()
  319. sizer.Add(btnStdSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  320. self.SetSizer(sizer)
  321. sizer.Fit(self)
  322. def _createGeneralPage(self, parent):
  323. panel = wx.Panel(parent=parent)
  324. mainSizer = wx.BoxSizer(wx.VERTICAL)
  325. self.windowChoice = wx.Choice(
  326. panel,
  327. id=wx.ID_ANY,
  328. choices=[
  329. _("top left"),
  330. _("top right"),
  331. _("bottom left"),
  332. _("bottom right"),
  333. ],
  334. )
  335. self.windowChoice.SetSelection(self.animationData.windowIndex)
  336. self.nameCtrl = TextCtrl(panel, id=wx.ID_ANY, value=self.animationData.name)
  337. self.nDChoice = Choice(panel, id=wx.ID_ANY)
  338. mode = self.animationData.viewMode
  339. index = 0
  340. for i, (viewMode, viewModeName) in enumerate(self.animationData.viewModes):
  341. self.nDChoice.Append(viewModeName, clientData=viewMode)
  342. if mode == viewMode:
  343. index = i
  344. self.nDChoice.SetSelection(index)
  345. self.nDChoice.SetToolTip(_("Select 2D or 3D view"))
  346. self.nDChoice.Bind(wx.EVT_CHOICE, self.OnViewMode)
  347. gridSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
  348. gridSizer.Add(
  349. StaticText(panel, id=wx.ID_ANY, label=_("Name:")),
  350. flag=wx.ALIGN_CENTER_VERTICAL,
  351. )
  352. gridSizer.Add(self.nameCtrl, proportion=1, flag=wx.EXPAND)
  353. gridSizer.Add(
  354. StaticText(panel, id=wx.ID_ANY, label=_("Window position:")),
  355. flag=wx.ALIGN_CENTER_VERTICAL,
  356. )
  357. gridSizer.Add(self.windowChoice, proportion=1, flag=wx.ALIGN_RIGHT)
  358. gridSizer.Add(
  359. StaticText(panel, id=wx.ID_ANY, label=_("View mode:")),
  360. flag=wx.ALIGN_CENTER_VERTICAL,
  361. )
  362. gridSizer.Add(self.nDChoice, proportion=1, flag=wx.ALIGN_RIGHT)
  363. gridSizer.AddGrowableCol(0, 1)
  364. gridSizer.AddGrowableCol(1, 1)
  365. mainSizer.Add(gridSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
  366. label = _(
  367. "For 3D animation, please select only one space-time dataset\n"
  368. "or one series of map layers."
  369. )
  370. self.warning3DLayers = StaticText(panel, label=label)
  371. self.warning3DLayers.SetForegroundColour(
  372. wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
  373. )
  374. mainSizer.Add(
  375. self.warning3DLayers, proportion=0, flag=wx.EXPAND | wx.LEFT, border=5
  376. )
  377. self.dataPanel = self._createDataPanel(panel)
  378. self.threeDPanel = self._create3DPanel(panel)
  379. mainSizer.Add(self.dataPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
  380. mainSizer.Add(self.threeDPanel, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  381. panel.SetSizer(mainSizer)
  382. mainSizer.Fit(panel)
  383. return panel
  384. def _createDataPanel(self, parent):
  385. panel = wx.Panel(parent)
  386. slmgrSizer = wx.BoxSizer(wx.VERTICAL)
  387. self._layerList = copy.deepcopy(self.animationData.layerList)
  388. self.simpleLmgr = AnimSimpleLayerManager(
  389. parent=panel, layerList=self._layerList, modal=True
  390. )
  391. self.simpleLmgr.SetMinSize((globalvar.DIALOG_GSELECT_SIZE[0], 80))
  392. slmgrSizer.Add(self.simpleLmgr, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  393. self.legend = wx.CheckBox(panel, label=_("Show raster legend"))
  394. self.legend.SetValue(bool(self.animationData.legendCmd))
  395. self.legendBtn = Button(panel, label=_("Set options"))
  396. self.legend.Bind(wx.EVT_CHECKBOX, self.OnLegend)
  397. self.legendBtn.Bind(wx.EVT_BUTTON, self.OnLegendProperties)
  398. hbox = wx.BoxSizer(wx.HORIZONTAL)
  399. hbox.Add(self.legend, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
  400. hbox.Add(self.legendBtn, proportion=0, flag=wx.LEFT, border=5)
  401. slmgrSizer.Add(hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  402. panel.SetSizerAndFit(slmgrSizer)
  403. panel.SetAutoLayout(True)
  404. return panel
  405. def _create3DPanel(self, parent):
  406. panel = wx.Panel(parent, id=wx.ID_ANY)
  407. dataStBox = StaticBox(
  408. parent=panel, id=wx.ID_ANY, label=" %s " % _("3D view parameters")
  409. )
  410. dataBoxSizer = wx.StaticBoxSizer(dataStBox, wx.VERTICAL)
  411. # workspace file
  412. self.fileSelector = filebrowse.FileBrowseButton(
  413. parent=panel,
  414. id=wx.ID_ANY,
  415. size=globalvar.DIALOG_GSELECT_SIZE,
  416. labelText=_("Workspace file:"),
  417. dialogTitle=_("Choose workspace file to " "import 3D view parameters"),
  418. buttonText=_("Browse"),
  419. startDirectory=os.getcwd(),
  420. fileMode=0,
  421. fileMask="GRASS Workspace File (*.gxw)|*.gxw",
  422. )
  423. if self.animationData.workspaceFile:
  424. self.fileSelector.SetValue(self.animationData.workspaceFile)
  425. self.paramLabel = StaticText(
  426. panel, wx.ID_ANY, label=_("Parameter for animation:")
  427. )
  428. self.paramChoice = wx.Choice(
  429. panel, id=wx.ID_ANY, choices=self.animationData.nvizParameters
  430. )
  431. self.paramChoice.SetStringSelection(self.animationData.nvizParameter)
  432. hbox = wx.BoxSizer(wx.HORIZONTAL)
  433. hbox.Add(self.fileSelector, proportion=1, flag=wx.EXPAND)
  434. dataBoxSizer.Add(hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  435. hbox = wx.BoxSizer(wx.HORIZONTAL)
  436. hbox.Add(self.paramLabel, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
  437. hbox.Add(self.paramChoice, proportion=1, flag=wx.EXPAND)
  438. dataBoxSizer.Add(hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  439. panel.SetSizerAndFit(dataBoxSizer)
  440. panel.SetAutoLayout(True)
  441. return panel
  442. def _createAdvancedPage(self, parent):
  443. panel = wx.Panel(parent=parent)
  444. mainSizer = wx.BoxSizer(wx.VERTICAL)
  445. box = StaticBox(parent=panel, label=" %s " % _("Set spatial extent in 2D view"))
  446. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  447. gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
  448. self.stRegionLabel = StaticText(panel, label=_("Use saved region:"))
  449. gridSizer.Add(self.stRegionLabel, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
  450. self.stRegion = Select(parent=panel, type="region", size=(200, -1))
  451. if self.animationData.startRegion:
  452. self.stRegion.SetValue(self.animationData.startRegion)
  453. gridSizer.Add(
  454. self.stRegion, pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
  455. )
  456. self.animateRegionCheckbox = CheckBox(panel, label=_("Animate region change"))
  457. self.animateRegionCheckbox.SetValue(False)
  458. gridSizer.Add(
  459. self.animateRegionCheckbox, pos=(1, 0), span=(1, 2), flag=wx.EXPAND
  460. )
  461. self.animateRegionCheckbox.Bind(
  462. wx.EVT_CHECKBOX, lambda evt: self._onAnimateExtent()
  463. )
  464. self.endRegRadio = RadioButton(panel, label=_("End region:"), style=wx.RB_GROUP)
  465. gridSizer.Add(self.endRegRadio, pos=(2, 0), border=10, flag=wx.EXPAND | wx.LEFT)
  466. self.endRegion = Select(parent=panel, type="region", size=(200, -1))
  467. gridSizer.Add(
  468. self.endRegion, pos=(2, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
  469. )
  470. self.zoomRadio = RadioButton(panel, label=_("Zoom value:"))
  471. self.zoomRadio.SetToolTip(
  472. _("N-S/E-W distances in map units used to " "gradually reduce region.")
  473. )
  474. gridSizer.Add(self.zoomRadio, pos=(3, 0), border=10, flag=wx.EXPAND | wx.LEFT)
  475. zoomSizer = wx.BoxSizer(wx.HORIZONTAL)
  476. self.zoomNS = TextCtrl(panel, validator=FloatValidator())
  477. self.zoomEW = TextCtrl(panel, validator=FloatValidator())
  478. zoomSizer.Add(
  479. StaticText(panel, label=_("N-S:")),
  480. proportion=0,
  481. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
  482. border=3,
  483. )
  484. zoomSizer.Add(self.zoomNS, proportion=1, flag=wx.LEFT, border=3)
  485. zoomSizer.Add(
  486. StaticText(panel, label=_("E-W:")),
  487. proportion=0,
  488. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
  489. border=3,
  490. )
  491. zoomSizer.Add(self.zoomEW, proportion=1, flag=wx.LEFT, border=3)
  492. gridSizer.Add(zoomSizer, pos=(3, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  493. if self.animationData.endRegion:
  494. self.animateRegionCheckbox.SetValue(True)
  495. self.endRegRadio.SetValue(True)
  496. self.zoomRadio.SetValue(False)
  497. self.endRegion.SetValue(self.animationData.endRegion)
  498. if self.animationData.zoomRegionValue:
  499. self.animateRegionCheckbox.SetValue(True)
  500. self.endRegRadio.SetValue(False)
  501. self.zoomRadio.SetValue(True)
  502. zoom = self.animationData.zoomRegionValue
  503. self.zoomNS.SetValue(str(zoom[0]))
  504. self.zoomEW.SetValue(str(zoom[1]))
  505. self.endRegRadio.Bind(
  506. wx.EVT_RADIOBUTTON, lambda evt: self._enableRegionWidgets()
  507. )
  508. self.zoomRadio.Bind(wx.EVT_RADIOBUTTON, lambda evt: self._enableRegionWidgets())
  509. self._onAnimateExtent()
  510. gridSizer.AddGrowableCol(1)
  511. sizer.Add(gridSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  512. mainSizer.Add(sizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  513. panel.SetSizer(mainSizer)
  514. mainSizer.Fit(panel)
  515. return panel
  516. def _onAnimateExtent(self):
  517. checked = self.animateRegionCheckbox.IsChecked()
  518. self.endRegion.Enable(checked)
  519. self.zoomNS.Enable(checked)
  520. self.zoomEW.Enable(checked)
  521. self.zoomRadio.Enable(checked)
  522. self.endRegRadio.Enable(checked)
  523. if checked:
  524. self._enableRegionWidgets()
  525. def _enableRegionWidgets(self):
  526. """Enables/disables region widgets
  527. according to which radiobutton is active."""
  528. endReg = self.endRegRadio.GetValue()
  529. self.endRegion.Enable(endReg)
  530. self.zoomNS.Enable(not endReg)
  531. self.zoomEW.Enable(not endReg)
  532. def OnViewMode(self, event):
  533. mode = self.nDChoice.GetSelection()
  534. self.Freeze()
  535. self.simpleLmgr.Activate3D(mode == 1)
  536. self.warning3DLayers.Show(mode == 1)
  537. # disable region widgets for 3d
  538. regSizer = self.stRegion.GetContainingSizer()
  539. for child in regSizer.GetChildren():
  540. if child.IsSizer():
  541. for child_ in child.GetSizer().GetChildren():
  542. child_.GetWindow().Enable(mode != 1)
  543. elif child.IsWindow():
  544. child.GetWindow().Enable(mode != 1)
  545. if mode == 0:
  546. self._onAnimateExtent()
  547. # update layout
  548. sizer = self.threeDPanel.GetContainingSizer()
  549. sizer.Show(self.threeDPanel, mode == 1, True)
  550. sizer.Layout()
  551. self.Thaw()
  552. def OnLegend(self, event):
  553. if not self.legend.IsChecked():
  554. return
  555. if self._tmpLegendCmd or self.animationData.legendCmd:
  556. return
  557. cmd = ["d.legend", "at=5,50,2,5"]
  558. GUI(parent=self, modal=True).ParseCommand(
  559. cmd=cmd, completed=(self.GetOptData, "", "")
  560. )
  561. def OnLegendProperties(self, event):
  562. """Set options for legend"""
  563. if self._tmpLegendCmd:
  564. cmd = self._tmpLegendCmd
  565. elif self.animationData.legendCmd:
  566. cmd = self.animationData.legendCmd
  567. else:
  568. cmd = ["d.legend", "at=5,50,2,5"]
  569. GUI(parent=self, modal=True).ParseCommand(
  570. cmd=cmd, completed=(self.GetOptData, "", "")
  571. )
  572. def GetOptData(self, dcmd, layer, params, propwin):
  573. """Process decoration layer data"""
  574. if dcmd:
  575. self._tmpLegendCmd = dcmd
  576. if not self.legend.IsChecked():
  577. self.legend.SetValue(True)
  578. else:
  579. if not self._tmpLegendCmd and not self.animationData.legendCmd:
  580. self.legend.SetValue(False)
  581. def _update(self):
  582. if self.nDChoice.GetSelection() == 1 and len(self._layerList) > 1:
  583. raise GException(
  584. _("Only one series or space-time " "dataset is accepted for 3D mode.")
  585. )
  586. hasSeries = False
  587. for layer in self._layerList:
  588. if layer.active and hasattr(layer, "maps"):
  589. hasSeries = True
  590. break
  591. if not hasSeries:
  592. raise GException(_("No map series or space-time dataset added."))
  593. self.animationData.layerList = self._layerList
  594. self.animationData.name = self.nameCtrl.GetValue()
  595. self.animationData.windowIndex = self.windowChoice.GetSelection()
  596. sel = self.nDChoice.GetSelection()
  597. self.animationData.viewMode = self.nDChoice.GetClientData(sel)
  598. self.animationData.legendCmd = None
  599. if self._tmpLegendCmd:
  600. if self.legend.IsChecked():
  601. self.animationData.legendCmd = self._tmpLegendCmd
  602. if self.threeDPanel.IsShown():
  603. self.animationData.workspaceFile = self.fileSelector.GetValue()
  604. if self.threeDPanel.IsShown():
  605. self.animationData.nvizParameter = self.paramChoice.GetStringSelection()
  606. # region (2d only)
  607. if self.animationData.viewMode == "3d":
  608. self.animationData.startRegion = None
  609. self.animationData.endRegion = None
  610. self.animationData.zoomRegionValue = None
  611. return
  612. isEnd = self.endRegRadio.GetValue() and self.endRegion.GetValue()
  613. isZoom = (
  614. self.zoomRadio.GetValue()
  615. and self.zoomNS.GetValue()
  616. and self.zoomEW.GetValue()
  617. )
  618. isStart = self.stRegion.GetValue()
  619. useAnim = self.animateRegionCheckbox.GetValue()
  620. self.animationData.startRegion = None
  621. self.animationData.endRegion = None
  622. self.animationData.zoomRegionValue = None
  623. if not useAnim:
  624. if isStart:
  625. self.animationData.startRegion = isStart
  626. else:
  627. if isStart:
  628. self.animationData.startRegion = isStart
  629. else:
  630. raise GException(_("Region information is not complete"))
  631. if isEnd:
  632. self.animationData.endRegion = self.endRegion.GetValue()
  633. self.animationData.zoomRegionValue = None
  634. elif isZoom:
  635. self.animationData.zoomRegionValue = (
  636. float(self.zoomNS.GetValue()),
  637. float(self.zoomEW.GetValue()),
  638. )
  639. self.animationData.endRegion = None
  640. else:
  641. raise GException(_("Region information is not complete"))
  642. def UnInit(self):
  643. self.simpleLmgr.UnInit()
  644. def OnOk(self, event):
  645. try:
  646. self._update()
  647. self.UnInit()
  648. self.EndModal(wx.ID_OK)
  649. except (GException, ValueError, IOError) as e:
  650. GError(message=str(e), showTraceback=False, caption=_("Invalid input"))
  651. class EditDialog(wx.Dialog):
  652. def __init__(self, parent, evalFunction, animationData, maxAnimations):
  653. wx.Dialog.__init__(
  654. self, parent=parent, id=wx.ID_ANY, style=wx.DEFAULT_DIALOG_STYLE
  655. )
  656. self.animationData = copy.deepcopy(animationData)
  657. self.eval = evalFunction
  658. self.SetTitle(_("Add, edit or remove animations"))
  659. self._layout()
  660. self.SetSize((300, -1))
  661. self.maxAnimations = maxAnimations
  662. self.result = None
  663. def _layout(self):
  664. mainSizer = wx.BoxSizer(wx.VERTICAL)
  665. box = StaticBox(
  666. parent=self, id=wx.ID_ANY, label=" %s " % _("List of animations")
  667. )
  668. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  669. gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
  670. gridBagSizer.AddGrowableCol(0)
  671. # gridBagSizer.AddGrowableCol(1,1)
  672. self.listbox = wx.ListBox(
  673. self, id=wx.ID_ANY, choices=[], style=wx.LB_SINGLE | wx.LB_NEEDED_SB
  674. )
  675. self.listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnEdit)
  676. self.addButton = Button(self, id=wx.ID_ANY, label=_("Add"))
  677. self.addButton.Bind(wx.EVT_BUTTON, self.OnAdd)
  678. self.editButton = Button(self, id=wx.ID_ANY, label=_("Edit"))
  679. self.editButton.Bind(wx.EVT_BUTTON, self.OnEdit)
  680. self.removeButton = Button(self, id=wx.ID_ANY, label=_("Remove"))
  681. self.removeButton.Bind(wx.EVT_BUTTON, self.OnRemove)
  682. self._updateListBox()
  683. gridBagSizer.Add(
  684. self.listbox,
  685. pos=(0, 0),
  686. span=(3, 1),
  687. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  688. border=0,
  689. )
  690. gridBagSizer.Add(
  691. self.addButton,
  692. pos=(0, 1),
  693. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  694. border=0,
  695. )
  696. gridBagSizer.Add(
  697. self.editButton,
  698. pos=(1, 1),
  699. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  700. border=0,
  701. )
  702. gridBagSizer.Add(
  703. self.removeButton,
  704. pos=(2, 1),
  705. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  706. border=0,
  707. )
  708. sizer.Add(gridBagSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
  709. mainSizer.Add(sizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  710. # buttons
  711. self.btnOk = Button(self, wx.ID_OK)
  712. self.btnCancel = Button(self, wx.ID_CANCEL)
  713. self.btnOk.SetDefault()
  714. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  715. # button sizer
  716. btnStdSizer = wx.StdDialogButtonSizer()
  717. btnStdSizer.AddButton(self.btnOk)
  718. btnStdSizer.AddButton(self.btnCancel)
  719. btnStdSizer.Realize()
  720. mainSizer.Add(btnStdSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  721. self.SetSizer(mainSizer)
  722. mainSizer.Fit(self)
  723. def _updateListBox(self):
  724. self.listbox.Clear()
  725. for anim in self.animationData:
  726. self.listbox.Append(anim.name, clientData=anim)
  727. if self.animationData:
  728. self.listbox.SetSelection(0)
  729. def _getNextIndex(self):
  730. indices = [anim.windowIndex for anim in self.animationData]
  731. for i in range(self.maxAnimations):
  732. if i not in indices:
  733. return i
  734. return None
  735. def OnAdd(self, event):
  736. windowIndex = self._getNextIndex()
  737. if windowIndex is None:
  738. GMessage(
  739. self,
  740. message=_("Maximum number of animations is %d.") % self.maxAnimations,
  741. )
  742. return
  743. animData = AnimationData()
  744. # number of active animations
  745. animationIndex = len(self.animationData)
  746. animData.SetDefaultValues(windowIndex, animationIndex)
  747. dlg = InputDialog(parent=self, mode="add", animationData=animData)
  748. dlg.CenterOnParent()
  749. if dlg.ShowModal() == wx.ID_CANCEL:
  750. dlg.UnInit()
  751. dlg.Destroy()
  752. return
  753. dlg.Destroy()
  754. self.animationData.append(animData)
  755. self._updateListBox()
  756. def OnEdit(self, event):
  757. index = self.listbox.GetSelection()
  758. if index == wx.NOT_FOUND:
  759. return
  760. animData = self.listbox.GetClientData(index)
  761. dlg = InputDialog(parent=self, mode="edit", animationData=animData)
  762. dlg.CenterOnParent()
  763. if dlg.ShowModal() == wx.ID_CANCEL:
  764. dlg.UnInit()
  765. dlg.Destroy()
  766. return
  767. dlg.Destroy()
  768. self._updateListBox()
  769. def OnRemove(self, event):
  770. index = self.listbox.GetSelection()
  771. if index == wx.NOT_FOUND:
  772. return
  773. animData = self.listbox.GetClientData(index)
  774. self.animationData.remove(animData)
  775. self._updateListBox()
  776. def GetResult(self):
  777. return self.result
  778. def OnOk(self, event):
  779. indices = set([anim.windowIndex for anim in self.animationData])
  780. if len(indices) != len(self.animationData):
  781. GError(
  782. parent=self,
  783. message=_(
  784. "More animations are using one window."
  785. " Please select different window for each animation."
  786. ),
  787. )
  788. return
  789. try:
  790. temporalMode, tempManager = self.eval(self.animationData)
  791. except GException as e:
  792. GError(parent=self, message=e.value, showTraceback=False)
  793. return
  794. self.result = (self.animationData, temporalMode, tempManager)
  795. self.EndModal(wx.ID_OK)
  796. class ExportDialog(wx.Dialog):
  797. def __init__(self, parent, temporal, timeTick):
  798. wx.Dialog.__init__(
  799. self,
  800. parent=parent,
  801. id=wx.ID_ANY,
  802. title=_("Export animation"),
  803. style=wx.DEFAULT_DIALOG_STYLE,
  804. )
  805. self.decorations = []
  806. self.temporal = temporal
  807. self.timeTick = timeTick
  808. self._layout()
  809. # export animation
  810. self.doExport = Signal("ExportDialog::doExport")
  811. wx.CallAfter(self._hideAll)
  812. def _layout(self):
  813. notebook = wx.Notebook(self, id=wx.ID_ANY)
  814. mainSizer = wx.BoxSizer(wx.VERTICAL)
  815. notebook.AddPage(page=self._createExportFormatPanel(notebook), text=_("Format"))
  816. notebook.AddPage(
  817. page=self._createDecorationsPanel(notebook), text=_("Decorations")
  818. )
  819. mainSizer.Add(notebook, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  820. self.btnExport = Button(self, wx.ID_OK)
  821. self.btnExport.SetLabel(_("Export"))
  822. self.btnCancel = Button(self, wx.ID_CANCEL)
  823. self.btnExport.SetDefault()
  824. self.btnExport.Bind(wx.EVT_BUTTON, self.OnExport)
  825. # button sizer
  826. btnStdSizer = wx.StdDialogButtonSizer()
  827. btnStdSizer.AddButton(self.btnExport)
  828. btnStdSizer.AddButton(self.btnCancel)
  829. btnStdSizer.Realize()
  830. mainSizer.Add(btnStdSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  831. self.SetSizer(mainSizer)
  832. # set the longest option to fit
  833. self.hidevbox.Show(self.fontBox, True)
  834. self.hidevbox.Show(self.imageBox, False)
  835. self.hidevbox.Show(self.textBox, True)
  836. self.hidevbox.Show(self.posBox, True)
  837. self.hidevbox.Show(self.informBox, False)
  838. mainSizer.Fit(self)
  839. def _createDecorationsPanel(self, notebook):
  840. panel = wx.Panel(notebook, id=wx.ID_ANY)
  841. sizer = wx.BoxSizer(wx.VERTICAL)
  842. sizer.Add(
  843. self._createDecorationsList(panel),
  844. proportion=0,
  845. flag=wx.ALL | wx.EXPAND,
  846. border=10,
  847. )
  848. sizer.Add(
  849. self._createDecorationsProperties(panel),
  850. proportion=0,
  851. flag=wx.ALL | wx.EXPAND,
  852. border=10,
  853. )
  854. panel.SetSizer(sizer)
  855. sizer.Fit(panel)
  856. return panel
  857. def _createDecorationsList(self, panel):
  858. gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
  859. gridBagSizer.AddGrowableCol(0)
  860. self.listbox = wx.ListBox(
  861. panel, id=wx.ID_ANY, choices=[], style=wx.LB_SINGLE | wx.LB_NEEDED_SB
  862. )
  863. self.listbox.Bind(wx.EVT_LISTBOX, self.OnSelectionChanged)
  864. gridBagSizer.Add(
  865. self.listbox,
  866. pos=(0, 0),
  867. span=(4, 1),
  868. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  869. border=0,
  870. )
  871. buttonNames = ["time", "image", "text"]
  872. buttonLabels = [_("Add time stamp"), _("Add image"), _("Add text")]
  873. i = 0
  874. for buttonName, buttonLabel in zip(buttonNames, buttonLabels):
  875. if buttonName == "time" and self.temporal == TemporalMode.NONTEMPORAL:
  876. continue
  877. btn = Button(panel, id=wx.ID_ANY, name=buttonName, label=buttonLabel)
  878. btn.Bind(
  879. wx.EVT_BUTTON,
  880. lambda evt, temp=buttonName: self.OnAddDecoration(evt, temp),
  881. )
  882. gridBagSizer.Add(
  883. btn, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0
  884. )
  885. i += 1
  886. removeButton = Button(panel, id=wx.ID_ANY, label=_("Remove"))
  887. removeButton.Bind(wx.EVT_BUTTON, self.OnRemove)
  888. gridBagSizer.Add(
  889. removeButton,
  890. pos=(i, 1),
  891. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  892. border=0,
  893. )
  894. return gridBagSizer
  895. def _createDecorationsProperties(self, panel):
  896. self.hidevbox = wx.BoxSizer(wx.VERTICAL)
  897. # inform label
  898. self.informBox = wx.BoxSizer(wx.HORIZONTAL)
  899. if self.temporal == TemporalMode.TEMPORAL:
  900. label = _(
  901. "Add time stamp, image or text decoration by one of the buttons above."
  902. )
  903. else:
  904. label = _("Add image or text decoration by one of the buttons above.")
  905. label = StaticText(panel, id=wx.ID_ANY, label=label)
  906. label.Wrap(400)
  907. self.informBox.Add(
  908. label, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5
  909. )
  910. self.hidevbox.Add(
  911. self.informBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5
  912. )
  913. # font
  914. self.fontBox = wx.BoxSizer(wx.HORIZONTAL)
  915. self.fontBox.Add(
  916. StaticText(panel, id=wx.ID_ANY, label=_("Font settings:")),
  917. proportion=0,
  918. flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
  919. border=5,
  920. )
  921. self.sampleLabel = StaticText(panel, id=wx.ID_ANY, label=_("Sample text"))
  922. self.fontBox.Add(
  923. self.sampleLabel,
  924. proportion=1,
  925. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT,
  926. border=5,
  927. )
  928. fontButton = Button(panel, id=wx.ID_ANY, label=_("Set font"))
  929. fontButton.Bind(wx.EVT_BUTTON, self.OnFont)
  930. self.fontBox.Add(fontButton, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
  931. self.hidevbox.Add(
  932. self.fontBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5
  933. )
  934. # image
  935. self.imageBox = wx.BoxSizer(wx.HORIZONTAL)
  936. filetype, ltype = GetImageHandlers(EmptyImage(10, 10))
  937. self.browse = filebrowse.FileBrowseButton(
  938. parent=panel,
  939. id=wx.ID_ANY,
  940. fileMask=filetype,
  941. labelText=_("Image file:"),
  942. dialogTitle=_("Choose image file"),
  943. buttonText=_("Browse"),
  944. startDirectory=os.getcwd(),
  945. fileMode=wx.FD_OPEN,
  946. changeCallback=self.OnSetImage,
  947. )
  948. self.imageBox.Add(self.browse, proportion=1, flag=wx.EXPAND)
  949. self.hidevbox.Add(
  950. self.imageBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5
  951. )
  952. # text
  953. self.textBox = wx.BoxSizer(wx.HORIZONTAL)
  954. self.textBox.Add(
  955. StaticText(panel, id=wx.ID_ANY, label=_("Text:")),
  956. proportion=0,
  957. flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
  958. border=5,
  959. )
  960. self.textCtrl = TextCtrl(panel, id=wx.ID_ANY)
  961. self.textCtrl.Bind(wx.EVT_TEXT, self.OnText)
  962. self.textBox.Add(self.textCtrl, proportion=1, flag=wx.EXPAND)
  963. self.hidevbox.Add(self.textBox, proportion=0, flag=wx.EXPAND)
  964. self.posBox = self._positionWidget(panel)
  965. self.hidevbox.Add(self.posBox, proportion=0, flag=wx.EXPAND | wx.TOP, border=5)
  966. return self.hidevbox
  967. def _positionWidget(self, panel):
  968. grid = wx.GridBagSizer(vgap=5, hgap=5)
  969. label = StaticText(
  970. panel,
  971. id=wx.ID_ANY,
  972. label=_(
  973. "Placement as percentage of"
  974. " screen coordinates (X: 0, Y: 0 is top left):"
  975. ),
  976. )
  977. label.Wrap(400)
  978. self.spinX = SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
  979. self.spinY = SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
  980. self.spinX.Bind(
  981. wx.EVT_SPINCTRL, lambda evt, temp="X": self.OnPosition(evt, temp)
  982. )
  983. self.spinY.Bind(
  984. wx.EVT_SPINCTRL, lambda evt, temp="Y": self.OnPosition(evt, temp)
  985. )
  986. grid.Add(label, pos=(0, 0), span=(1, 4), flag=wx.EXPAND)
  987. grid.Add(
  988. StaticText(panel, id=wx.ID_ANY, label=_("X:")),
  989. pos=(1, 0),
  990. flag=wx.ALIGN_CENTER_VERTICAL,
  991. )
  992. grid.Add(
  993. StaticText(panel, id=wx.ID_ANY, label=_("Y:")),
  994. pos=(1, 2),
  995. flag=wx.ALIGN_CENTER_VERTICAL,
  996. )
  997. grid.Add(self.spinX, pos=(1, 1))
  998. grid.Add(self.spinY, pos=(1, 3))
  999. return grid
  1000. def _createExportFormatPanel(self, notebook):
  1001. panel = wx.Panel(notebook, id=wx.ID_ANY)
  1002. borderSizer = wx.BoxSizer(wx.VERTICAL)
  1003. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1004. choices = [_("image sequence"), _("animated GIF"), _("SWF"), _("AVI")]
  1005. self.formatChoice = wx.Choice(parent=panel, id=wx.ID_ANY, choices=choices)
  1006. self.formatChoice.SetSelection(0)
  1007. self.formatChoice.Bind(
  1008. wx.EVT_CHOICE, lambda event: self.ChangeFormat(event.GetSelection())
  1009. )
  1010. hSizer.Add(
  1011. StaticText(panel, id=wx.ID_ANY, label=_("Export to:")),
  1012. proportion=0,
  1013. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  1014. border=2,
  1015. )
  1016. hSizer.Add(self.formatChoice, proportion=1, flag=wx.EXPAND | wx.ALL, border=2)
  1017. borderSizer.Add(hSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
  1018. helpSizer = wx.BoxSizer(wx.HORIZONTAL)
  1019. helpSizer.AddStretchSpacer(1)
  1020. self.formatPanelSizer = wx.BoxSizer(wx.VERTICAL)
  1021. helpSizer.Add(self.formatPanelSizer, proportion=5, flag=wx.EXPAND)
  1022. borderSizer.Add(helpSizer, proportion=1, flag=wx.EXPAND)
  1023. self.formatPanels = []
  1024. # panel for image sequence
  1025. imSeqPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  1026. prefixLabel = StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File prefix:"))
  1027. self.prefixCtrl = TextCtrl(imSeqPanel, id=wx.ID_ANY, value=_("animation_"))
  1028. formatLabel = StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File format:"))
  1029. imageTypes = ["PNG", "JPEG", "GIF", "TIFF", "PPM", "BMP"]
  1030. self.imSeqFormatChoice = wx.Choice(imSeqPanel, choices=imageTypes)
  1031. self.imSeqFormatChoice.SetSelection(0)
  1032. self.dirBrowse = filebrowse.DirBrowseButton(
  1033. parent=imSeqPanel,
  1034. id=wx.ID_ANY,
  1035. labelText=_("Directory:"),
  1036. dialogTitle=_("Choose directory for export"),
  1037. buttonText=_("Browse"),
  1038. startDirectory=os.getcwd(),
  1039. )
  1040. dirGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1041. dirGridSizer.Add(prefixLabel, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
  1042. dirGridSizer.Add(self.prefixCtrl, pos=(0, 1), flag=wx.EXPAND)
  1043. dirGridSizer.Add(formatLabel, pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
  1044. dirGridSizer.Add(self.imSeqFormatChoice, pos=(1, 1), flag=wx.EXPAND)
  1045. dirGridSizer.Add(self.dirBrowse, pos=(2, 0), flag=wx.EXPAND, span=(1, 2))
  1046. dirGridSizer.AddGrowableCol(1)
  1047. imSeqPanel.SetSizer(dirGridSizer)
  1048. dirGridSizer.Fit(imSeqPanel)
  1049. self.formatPanelSizer.Add(
  1050. imSeqPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5
  1051. )
  1052. self.formatPanels.append(imSeqPanel)
  1053. # panel for gif
  1054. gifPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  1055. self.gifBrowse = filebrowse.FileBrowseButton(
  1056. parent=gifPanel,
  1057. id=wx.ID_ANY,
  1058. fileMask="GIF file (*.gif)|*.gif",
  1059. labelText=_("GIF file:"),
  1060. dialogTitle=_("Choose file to save animation"),
  1061. buttonText=_("Browse"),
  1062. startDirectory=os.getcwd(),
  1063. fileMode=wx.FD_SAVE,
  1064. )
  1065. gifGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1066. gifGridSizer.AddGrowableCol(0)
  1067. gifGridSizer.Add(self.gifBrowse, pos=(0, 0), flag=wx.EXPAND)
  1068. gifPanel.SetSizer(gifGridSizer)
  1069. gifGridSizer.Fit(gifPanel)
  1070. self.formatPanelSizer.Add(
  1071. gifPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5
  1072. )
  1073. self.formatPanels.append(gifPanel)
  1074. # panel for swf
  1075. swfPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  1076. self.swfBrowse = filebrowse.FileBrowseButton(
  1077. parent=swfPanel,
  1078. id=wx.ID_ANY,
  1079. fileMask="SWF file (*.swf)|*.swf",
  1080. labelText=_("SWF file:"),
  1081. dialogTitle=_("Choose file to save animation"),
  1082. buttonText=_("Browse"),
  1083. startDirectory=os.getcwd(),
  1084. fileMode=wx.FD_SAVE,
  1085. )
  1086. swfGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1087. swfGridSizer.AddGrowableCol(0)
  1088. swfGridSizer.Add(self.swfBrowse, pos=(0, 0), flag=wx.EXPAND)
  1089. swfPanel.SetSizer(swfGridSizer)
  1090. swfGridSizer.Fit(swfPanel)
  1091. self.formatPanelSizer.Add(
  1092. swfPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5
  1093. )
  1094. self.formatPanels.append(swfPanel)
  1095. # panel for avi
  1096. aviPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
  1097. ffmpeg = gcore.find_program("ffmpeg", "--help")
  1098. if not ffmpeg:
  1099. warning = _(
  1100. "Program 'ffmpeg' was not found.\nPlease install it first "
  1101. "and make sure\nit's in the PATH variable."
  1102. )
  1103. warningLabel = StaticText(parent=aviPanel, label=warning)
  1104. warningLabel.SetForegroundColour(wx.RED)
  1105. self.aviBrowse = filebrowse.FileBrowseButton(
  1106. parent=aviPanel,
  1107. id=wx.ID_ANY,
  1108. fileMask="AVI file (*.avi)|*.avi",
  1109. labelText=_("AVI file:"),
  1110. dialogTitle=_("Choose file to save animation"),
  1111. buttonText=_("Browse"),
  1112. startDirectory=os.getcwd(),
  1113. fileMode=wx.FD_SAVE,
  1114. )
  1115. encodingLabel = StaticText(
  1116. parent=aviPanel, id=wx.ID_ANY, label=_("Video codec:")
  1117. )
  1118. self.encodingText = TextCtrl(parent=aviPanel, id=wx.ID_ANY, value="mpeg4")
  1119. optionsLabel = StaticText(parent=aviPanel, label=_("Additional options:"))
  1120. self.optionsText = TextCtrl(parent=aviPanel)
  1121. self.optionsText.SetToolTip(
  1122. _(
  1123. "Consider adding '-sameq' or '-qscale 1' "
  1124. "if not satisfied with video quality. "
  1125. "Options depend on ffmpeg version."
  1126. )
  1127. )
  1128. aviGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1129. aviGridSizer.Add(self.aviBrowse, pos=(0, 0), span=(1, 2), flag=wx.EXPAND)
  1130. aviGridSizer.Add(encodingLabel, pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
  1131. aviGridSizer.Add(self.encodingText, pos=(1, 1), flag=wx.EXPAND)
  1132. aviGridSizer.Add(optionsLabel, pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
  1133. aviGridSizer.Add(self.optionsText, pos=(2, 1), flag=wx.EXPAND)
  1134. if not ffmpeg:
  1135. aviGridSizer.Add(
  1136. warningLabel,
  1137. pos=(3, 0),
  1138. span=(1, 2),
  1139. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  1140. )
  1141. aviGridSizer.AddGrowableCol(1)
  1142. aviPanel.SetSizer(aviGridSizer)
  1143. aviGridSizer.Fit(aviPanel)
  1144. self.formatPanelSizer.Add(
  1145. aviPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5
  1146. )
  1147. self.formatPanels.append(aviPanel)
  1148. fpsSizer = wx.BoxSizer(wx.HORIZONTAL)
  1149. fps = 1000 / self.timeTick
  1150. fpsSizer.Add(
  1151. StaticText(
  1152. panel, id=wx.ID_ANY, label=_("Current frame rate: %.2f fps") % fps
  1153. ),
  1154. proportion=1,
  1155. flag=wx.EXPAND,
  1156. )
  1157. borderSizer.Add(fpsSizer, proportion=0, flag=wx.ALL, border=5)
  1158. panel.SetSizer(borderSizer)
  1159. borderSizer.Fit(panel)
  1160. self.ChangeFormat(index=0)
  1161. return panel
  1162. def ChangeFormat(self, index):
  1163. for i, panel in enumerate(self.formatPanels):
  1164. self.formatPanelSizer.Show(window=panel, show=(i == index))
  1165. self.formatPanelSizer.Layout()
  1166. def OnFont(self, event):
  1167. index = self.listbox.GetSelection()
  1168. # should not happen
  1169. if index == wx.NOT_FOUND:
  1170. return
  1171. cdata = self.listbox.GetClientData(index)
  1172. font = cdata["font"]
  1173. fontdata = wx.FontData()
  1174. fontdata.EnableEffects(True)
  1175. fontdata.SetColour("black")
  1176. fontdata.SetInitialFont(font)
  1177. dlg = wx.FontDialog(self, fontdata)
  1178. dlg.CenterOnParent()
  1179. if dlg.ShowModal() == wx.ID_OK:
  1180. newfontdata = dlg.GetFontData()
  1181. font = newfontdata.GetChosenFont()
  1182. self.sampleLabel.SetFont(font)
  1183. cdata["font"] = font
  1184. self.Layout()
  1185. def OnPosition(self, event, coord):
  1186. index = self.listbox.GetSelection()
  1187. # should not happen
  1188. if index == wx.NOT_FOUND:
  1189. return
  1190. cdata = self.listbox.GetClientData(index)
  1191. cdata["pos"][coord == "Y"] = event.GetInt()
  1192. def OnSetImage(self, event):
  1193. index = self.listbox.GetSelection()
  1194. # should not happen
  1195. if index == wx.NOT_FOUND:
  1196. return
  1197. cdata = self.listbox.GetClientData(index)
  1198. cdata["file"] = event.GetString()
  1199. def OnAddDecoration(self, event, name):
  1200. if name == "time":
  1201. timeInfo = {"name": name, "font": self.GetFont(), "pos": [10, 10]}
  1202. self.decorations.append(timeInfo)
  1203. elif name == "image":
  1204. imageInfo = {"name": name, "file": "", "pos": [10, 10]}
  1205. self.decorations.append(imageInfo)
  1206. elif name == "text":
  1207. textInfo = {
  1208. "name": name,
  1209. "font": self.GetFont(),
  1210. "text": "",
  1211. "pos": [10, 10],
  1212. }
  1213. self.decorations.append(textInfo)
  1214. self._updateListBox()
  1215. self.listbox.SetSelection(self.listbox.GetCount() - 1)
  1216. self.OnSelectionChanged(event=None)
  1217. def OnSelectionChanged(self, event):
  1218. index = self.listbox.GetSelection()
  1219. if index == wx.NOT_FOUND:
  1220. self._hideAll()
  1221. return
  1222. cdata = self.listbox.GetClientData(index)
  1223. self.hidevbox.Show(self.fontBox, (cdata["name"] in ("time", "text")))
  1224. self.hidevbox.Show(self.imageBox, (cdata["name"] == "image"))
  1225. self.hidevbox.Show(self.textBox, (cdata["name"] == "text"))
  1226. self.hidevbox.Show(self.posBox, True)
  1227. self.hidevbox.Show(self.informBox, False)
  1228. self.spinX.SetValue(cdata["pos"][0])
  1229. self.spinY.SetValue(cdata["pos"][1])
  1230. if cdata["name"] == "image":
  1231. self.browse.SetValue(cdata["file"])
  1232. elif cdata["name"] in ("time", "text"):
  1233. self.sampleLabel.SetFont(cdata["font"])
  1234. if cdata["name"] == "text":
  1235. self.textCtrl.SetValue(cdata["text"])
  1236. self.hidevbox.Layout()
  1237. # self.Layout()
  1238. def OnText(self, event):
  1239. index = self.listbox.GetSelection()
  1240. # should not happen
  1241. if index == wx.NOT_FOUND:
  1242. return
  1243. cdata = self.listbox.GetClientData(index)
  1244. cdata["text"] = event.GetString()
  1245. def OnRemove(self, event):
  1246. index = self.listbox.GetSelection()
  1247. if index == wx.NOT_FOUND:
  1248. return
  1249. decData = self.listbox.GetClientData(index)
  1250. self.decorations.remove(decData)
  1251. self._updateListBox()
  1252. if self.listbox.GetCount():
  1253. self.listbox.SetSelection(0)
  1254. self.OnSelectionChanged(event=None)
  1255. def OnExport(self, event):
  1256. for decor in self.decorations:
  1257. if decor["name"] == "image":
  1258. if not os.path.exists(decor["file"]):
  1259. if decor["file"]:
  1260. GError(
  1261. parent=self, message=_("File %s not found.") % decor["file"]
  1262. )
  1263. else:
  1264. GError(
  1265. parent=self, message=_("Decoration image file is missing.")
  1266. )
  1267. return
  1268. if self.formatChoice.GetSelection() == 0:
  1269. name = self.dirBrowse.GetValue()
  1270. if not os.path.exists(name):
  1271. if name:
  1272. GError(parent=self, message=_("Directory %s not found.") % name)
  1273. else:
  1274. GError(parent=self, message=_("Export directory is missing."))
  1275. return
  1276. elif self.formatChoice.GetSelection() == 1:
  1277. if not self._export_file_validation(
  1278. filebrowsebtn=self.gifBrowse,
  1279. file_path=self.gifBrowse.GetValue(),
  1280. file_postfix=".gif",
  1281. ):
  1282. return
  1283. elif self.formatChoice.GetSelection() == 2:
  1284. if not self._export_file_validation(
  1285. filebrowsebtn=self.swfBrowse,
  1286. file_path=self.swfBrowse.GetValue(),
  1287. file_postfix=".swf",
  1288. ):
  1289. return
  1290. elif self.formatChoice.GetSelection() == 3:
  1291. if not self._export_file_validation(
  1292. filebrowsebtn=self.aviBrowse,
  1293. file_path=self.aviBrowse.GetValue(),
  1294. file_postfix=".avi",
  1295. ):
  1296. return
  1297. # hide only to keep previous values
  1298. self.Hide()
  1299. self.doExport.emit(
  1300. exportInfo=self.GetExportInformation(), decorations=self.GetDecorations()
  1301. )
  1302. def GetDecorations(self):
  1303. return self.decorations
  1304. def GetExportInformation(self):
  1305. info = {}
  1306. if self.formatChoice.GetSelection() == 0:
  1307. info["method"] = "sequence"
  1308. info["directory"] = self.dirBrowse.GetValue()
  1309. info["prefix"] = self.prefixCtrl.GetValue()
  1310. info["format"] = self.imSeqFormatChoice.GetStringSelection()
  1311. elif self.formatChoice.GetSelection() == 1:
  1312. info["method"] = "gif"
  1313. info["file"] = self.gifBrowse.GetValue()
  1314. elif self.formatChoice.GetSelection() == 2:
  1315. info["method"] = "swf"
  1316. info["file"] = self.swfBrowse.GetValue()
  1317. elif self.formatChoice.GetSelection() == 3:
  1318. info["method"] = "avi"
  1319. info["file"] = self.aviBrowse.GetValue()
  1320. info["encoding"] = self.encodingText.GetValue()
  1321. info["options"] = self.optionsText.GetValue()
  1322. return info
  1323. def _updateListBox(self):
  1324. self.listbox.Clear()
  1325. names = {"time": _("Time stamp"), "image": _("Image"), "text": _("Text")}
  1326. for decor in self.decorations:
  1327. self.listbox.Append(names[decor["name"]], clientData=decor)
  1328. def _hideAll(self):
  1329. self.hidevbox.Show(self.fontBox, False)
  1330. self.hidevbox.Show(self.imageBox, False)
  1331. self.hidevbox.Show(self.textBox, False)
  1332. self.hidevbox.Show(self.posBox, False)
  1333. self.hidevbox.Show(self.informBox, True)
  1334. self.hidevbox.Layout()
  1335. def _export_file_validation(self, filebrowsebtn, file_path, file_postfix):
  1336. """File validation before export
  1337. :param obj filebrowsebutton: filebrowsebutton widget
  1338. :param str file_path: exported file path
  1339. :param str file_postfix: exported file postfix
  1340. (.gif, .swf, .avi)
  1341. :return bool: True if validation is ok
  1342. """
  1343. file_path_does_not_exist_err_message = _(
  1344. "Exported file directory '{base_dir}' " "does not exist."
  1345. )
  1346. if not file_path:
  1347. GError(parent=self, message=_("Export file is missing."))
  1348. return False
  1349. else:
  1350. if not file_path.endswith(file_postfix):
  1351. filebrowsebtn.SetValue(file_path + file_postfix)
  1352. file_path += file_postfix
  1353. base_dir = os.path.dirname(file_path)
  1354. if not os.path.exists(base_dir):
  1355. GError(
  1356. parent=self,
  1357. message=file_path_does_not_exist_err_message.format(
  1358. base_dir=base_dir,
  1359. ),
  1360. )
  1361. return False
  1362. if os.path.exists(file_path):
  1363. overwrite_dlg = wx.MessageDialog(
  1364. self.GetParent(),
  1365. message=_(
  1366. "Exported animation file <{file}> exists. "
  1367. "Do you want to overwrite it?".format(
  1368. file=file_path,
  1369. ),
  1370. ),
  1371. caption=_("Overwrite?"),
  1372. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION,
  1373. )
  1374. if not overwrite_dlg.ShowModal() == wx.ID_YES:
  1375. overwrite_dlg.Destroy()
  1376. return False
  1377. overwrite_dlg.Destroy()
  1378. return True
  1379. class AnimSimpleLayerManager(SimpleLayerManager):
  1380. """Simple layer manager for animation tool.
  1381. Allows adding space-time dataset or series of maps.
  1382. """
  1383. def __init__(
  1384. self,
  1385. parent,
  1386. layerList,
  1387. lmgrStyle=SIMPLE_LMGR_RASTER
  1388. | SIMPLE_LMGR_VECTOR
  1389. | SIMPLE_LMGR_TB_TOP
  1390. | SIMPLE_LMGR_STDS,
  1391. toolbarCls=AnimSimpleLmgrToolbar,
  1392. modal=True,
  1393. ):
  1394. SimpleLayerManager.__init__(
  1395. self, parent, layerList, lmgrStyle, toolbarCls, modal
  1396. )
  1397. self._3dActivated = False
  1398. def OnAddStds(self, event):
  1399. """Opens dialog for specifying temporal dataset.
  1400. Dummy layer is added first."""
  1401. layer = AnimLayer()
  1402. layer.hidden = True
  1403. self._layerList.AddLayer(layer)
  1404. self.SetStdsProperties(layer)
  1405. event.Skip()
  1406. def SetStdsProperties(self, layer):
  1407. dlg = AddTemporalLayerDialog(parent=self, layer=layer, volume=self._3dActivated)
  1408. # first get hidden property, it's altered afterwards
  1409. hidden = layer.hidden
  1410. dlg.CenterOnParent()
  1411. if dlg.ShowModal() == wx.ID_OK:
  1412. layer = dlg.GetLayer()
  1413. if hidden:
  1414. signal = self.layerAdded
  1415. else:
  1416. signal = self.cmdChanged
  1417. signal.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
  1418. else:
  1419. if hidden:
  1420. self._layerList.RemoveLayer(layer)
  1421. dlg.Destroy()
  1422. self._update()
  1423. self.anyChange.emit()
  1424. def _layerChangeProperties(self, layer):
  1425. """Opens new module dialog or recycles it."""
  1426. if not hasattr(layer, "maps"):
  1427. GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
  1428. cmd=layer.cmd, completed=(self.GetOptData, layer, "")
  1429. )
  1430. else:
  1431. self.SetStdsProperties(layer)
  1432. def Activate3D(self, activate=True):
  1433. """Activates/deactivates certain tool depending on 2D/3D view."""
  1434. self._toolbar.EnableTools(
  1435. ["addRaster", "addVector", "opacity", "up", "down"], not activate
  1436. )
  1437. self._3dActivated = activate
  1438. class AddTemporalLayerDialog(wx.Dialog):
  1439. """Dialog for adding space-time dataset/ map series."""
  1440. def __init__(
  1441. self, parent, layer, volume=False, title=_("Add space-time dataset layer")
  1442. ):
  1443. wx.Dialog.__init__(self, parent=parent, title=title)
  1444. self.layer = layer
  1445. self._mapType = None
  1446. self._name = None
  1447. self._cmd = None
  1448. self.tselect = Select(parent=self, type="strds")
  1449. iconTheme = UserSettings.Get(group="appearance", key="iconTheme", subkey="type")
  1450. bitmapPath = os.path.join(globalvar.ICONDIR, iconTheme, "layer-open.png")
  1451. if os.path.isfile(bitmapPath) and os.path.getsize(bitmapPath):
  1452. bitmap = wx.Bitmap(name=bitmapPath)
  1453. else:
  1454. bitmap = wx.ArtProvider.GetBitmap(
  1455. id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR
  1456. )
  1457. self.addManyMapsButton = BitmapButton(self, bitmap=bitmap)
  1458. self.addManyMapsButton.Bind(wx.EVT_BUTTON, self._onAddMaps)
  1459. types = [
  1460. ("raster", _("Multiple raster maps")),
  1461. ("vector", _("Multiple vector maps")),
  1462. ("raster_3d", _("Multiple 3D raster maps")),
  1463. ("strds", _("Space time raster dataset")),
  1464. ("stvds", _("Space time vector dataset")),
  1465. ("str3ds", _("Space time 3D raster dataset")),
  1466. ]
  1467. if not volume:
  1468. del types[5]
  1469. del types[2]
  1470. self._types = dict(types)
  1471. self.tchoice = wx.Choice(parent=self)
  1472. for type_, text in types:
  1473. self.tchoice.Append(text, clientData=type_)
  1474. self.editBtn = Button(parent=self, label="Set properties")
  1475. self.okBtn = Button(parent=self, id=wx.ID_OK)
  1476. self.cancelBtn = Button(parent=self, id=wx.ID_CANCEL)
  1477. self.okBtn.Bind(wx.EVT_BUTTON, self._onOK)
  1478. self.editBtn.Bind(wx.EVT_BUTTON, self._onProperties)
  1479. self.tchoice.Bind(wx.EVT_CHOICE, lambda evt: self._setType())
  1480. self.tselect.Bind(wx.EVT_TEXT, lambda evt: self._datasetChanged())
  1481. if self.layer.mapType:
  1482. self._setType(self.layer.mapType)
  1483. else:
  1484. self._setType("raster")
  1485. if self.layer.name:
  1486. self.tselect.SetValue(self.layer.name)
  1487. if self.layer.cmd:
  1488. self._cmd = self.layer.cmd
  1489. self._layout()
  1490. self.SetSize(self.GetBestSize())
  1491. def _layout(self):
  1492. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1493. bodySizer = wx.BoxSizer(wx.VERTICAL)
  1494. typeSizer = wx.BoxSizer(wx.HORIZONTAL)
  1495. selectSizer = wx.BoxSizer(wx.HORIZONTAL)
  1496. typeSizer.Add(
  1497. StaticText(self, label=_("Input data type:")), flag=wx.ALIGN_CENTER_VERTICAL
  1498. )
  1499. typeSizer.AddStretchSpacer()
  1500. typeSizer.Add(self.tchoice)
  1501. bodySizer.Add(typeSizer, flag=wx.EXPAND | wx.BOTTOM, border=5)
  1502. selectSizer.Add(
  1503. self.tselect, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=5
  1504. )
  1505. selectSizer.Add(self.addManyMapsButton, flag=wx.EXPAND)
  1506. bodySizer.Add(selectSizer, flag=wx.BOTTOM, border=5)
  1507. bodySizer.Add(self.editBtn, flag=wx.BOTTOM, border=5)
  1508. mainSizer.Add(bodySizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  1509. btnSizer = wx.StdDialogButtonSizer()
  1510. btnSizer.AddButton(self.okBtn)
  1511. btnSizer.AddButton(self.cancelBtn)
  1512. btnSizer.Realize()
  1513. mainSizer.Add(btnSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  1514. self.SetSizer(mainSizer)
  1515. mainSizer.Fit(self)
  1516. def _datasetChanged(self):
  1517. if self._name != self.tselect.GetValue():
  1518. self._name = self.tselect.GetValue()
  1519. self._cmd = None
  1520. def _setType(self, typeName=None):
  1521. if typeName:
  1522. self.tchoice.SetStringSelection(self._types[typeName])
  1523. self.tselect.SetType(typeName)
  1524. if typeName in ("strds", "stvds", "str3ds"):
  1525. self.tselect.SetType(typeName, multiple=False)
  1526. self.addManyMapsButton.Disable()
  1527. else:
  1528. self.tselect.SetType(typeName, multiple=True)
  1529. self.addManyMapsButton.Enable()
  1530. self._mapType = typeName
  1531. self.tselect.SetValue("")
  1532. else:
  1533. typeName = self.tchoice.GetClientData(self.tchoice.GetSelection())
  1534. if typeName in ("strds", "stvds", "str3ds"):
  1535. self.tselect.SetType(typeName, multiple=False)
  1536. self.addManyMapsButton.Disable()
  1537. else:
  1538. self.tselect.SetType(typeName, multiple=True)
  1539. self.addManyMapsButton.Enable()
  1540. if typeName != self._mapType:
  1541. self._cmd = None
  1542. self._mapType = typeName
  1543. self.tselect.SetValue("")
  1544. def _createDefaultCommand(self):
  1545. cmd = []
  1546. if self._mapType in ("raster", "strds"):
  1547. cmd.append("d.rast")
  1548. elif self._mapType in ("vector", "stvds"):
  1549. cmd.append("d.vect")
  1550. elif self._mapType in ("raster_3d", "str3ds"):
  1551. cmd.append("d.rast3d")
  1552. if self._name:
  1553. if self._mapType in ("raster", "vector", "raster_3d"):
  1554. cmd.append("map={name}".format(name=self._name.split(",")[0]))
  1555. else:
  1556. try:
  1557. maps = getRegisteredMaps(self._name, etype=self._mapType)
  1558. if maps:
  1559. mapName, mapLayer = getNameAndLayer(maps[0])
  1560. cmd.append("map={name}".format(name=mapName))
  1561. except gcore.ScriptError as e:
  1562. GError(parent=self, message=str(e), showTraceback=False)
  1563. return None
  1564. return cmd
  1565. def _onAddMaps(self, event):
  1566. dlg = MapLayersDialog(self, title=_("Select raster/vector maps."))
  1567. dlg.applyAddingMapLayers.connect(
  1568. lambda mapLayers: self.tselect.SetValue(",".join(mapLayers))
  1569. )
  1570. if self._mapType == "raster":
  1571. index = 0
  1572. elif self._mapType == "vector":
  1573. index = 2
  1574. else: # rast3d
  1575. index = 1
  1576. dlg.layerType.SetSelection(index)
  1577. dlg.LoadMapLayers(dlg.GetLayerType(cmd=True), dlg.mapset.GetStringSelection())
  1578. dlg.CenterOnParent()
  1579. if dlg.ShowModal() == wx.ID_OK:
  1580. self.tselect.SetValue(",".join(dlg.GetMapLayers()))
  1581. dlg.Destroy()
  1582. def _onProperties(self, event):
  1583. self._checkInput()
  1584. if self._cmd:
  1585. GUI(parent=self, show=True, modal=True).ParseCommand(
  1586. cmd=self._cmd, completed=(self._getOptData, "", "")
  1587. )
  1588. def _checkInput(self):
  1589. if not self.tselect.GetValue():
  1590. GMessage(parent=self, message=_("Please select maps or dataset first."))
  1591. return
  1592. if not self._cmd:
  1593. self._cmd = self._createDefaultCommand()
  1594. def _getOptData(self, dcmd, layer, params, propwin):
  1595. if dcmd:
  1596. self._cmd = dcmd
  1597. def _onOK(self, event):
  1598. self._checkInput()
  1599. if self._cmd:
  1600. try:
  1601. self.layer.hidden = False
  1602. self.layer.mapType = self._mapType
  1603. self.layer.name = self._name
  1604. self.layer.cmd = self._cmd
  1605. event.Skip()
  1606. except (GException, gcore.ScriptError) as e:
  1607. GError(parent=self, message=str(e))
  1608. def GetLayer(self):
  1609. return self.layer
  1610. class PreferencesDialog(PreferencesBaseDialog):
  1611. """Animation preferences dialog"""
  1612. def __init__(
  1613. self, parent, giface, title=_("Animation Tool settings"), settings=UserSettings
  1614. ):
  1615. PreferencesBaseDialog.__init__(
  1616. self,
  1617. parent=parent,
  1618. giface=giface,
  1619. title=title,
  1620. settings=settings,
  1621. size=(-1, 270),
  1622. )
  1623. self.formatChanged = Signal("PreferencesDialog.formatChanged")
  1624. self._timeFormats = [
  1625. "%Y-%m-%d %H:%M:%S", # 2013-12-29 11:16:26
  1626. "%Y-%m-%d", # 2013-12-29
  1627. "%c",
  1628. # Sun Dec 29 11:16:26 2013 (locale-dependent)
  1629. "%x", # 12/29/13 (locale-dependent)
  1630. "%X", # 11:16:26 (locale-dependent)
  1631. "%b %d, %Y", # Dec 29, 2013
  1632. "%B %d, %Y", # December 29, 2013
  1633. "%B, %Y", # December 2013
  1634. "%I:%M %p", # 11:16 AM
  1635. "%I %p", # 11 AM
  1636. ]
  1637. self._format = None
  1638. self._initFormat = self.settings.Get(
  1639. group="animation", key="temporal", subkey="format"
  1640. )
  1641. # create notebook pages
  1642. self._createGeneralPage(self.notebook)
  1643. self._createTemporalPage(self.notebook)
  1644. self.SetMinSize(self.GetBestSize())
  1645. self.SetSize(self.size)
  1646. def _createGeneralPage(self, notebook):
  1647. """Create notebook page for general settings"""
  1648. panel = SP.ScrolledPanel(parent=notebook)
  1649. panel.SetupScrolling(scroll_x=False, scroll_y=True)
  1650. notebook.AddPage(page=panel, text=_("General"))
  1651. border = wx.BoxSizer(wx.VERTICAL)
  1652. sizer = wx.BoxSizer(wx.VERTICAL)
  1653. gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
  1654. row = 0
  1655. gridSizer.Add(
  1656. StaticText(parent=panel, label=_("Background color:")),
  1657. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
  1658. pos=(row, 0),
  1659. )
  1660. color = csel.ColourSelect(
  1661. parent=panel,
  1662. colour=UserSettings.Get(group="animation", key="bgcolor", subkey="color"),
  1663. size=globalvar.DIALOG_COLOR_SIZE,
  1664. )
  1665. color.SetName("GetColour")
  1666. self.winId["animation:bgcolor:color"] = color.GetId()
  1667. gridSizer.Add(color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
  1668. row += 1
  1669. gridSizer.Add(
  1670. StaticText(parent=panel, label=_("Number of parallel processes:")),
  1671. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
  1672. pos=(row, 0),
  1673. )
  1674. # when running for the first time, set nprocs based on the number of
  1675. # processes
  1676. if UserSettings.Get(group="animation", key="nprocs", subkey="value") == -1:
  1677. UserSettings.Set(
  1678. group="animation", key="nprocs", subkey="value", value=getCpuCount()
  1679. )
  1680. nprocs = SpinCtrl(
  1681. parent=panel,
  1682. initial=UserSettings.Get(group="animation", key="nprocs", subkey="value"),
  1683. )
  1684. nprocs.SetName("GetValue")
  1685. self.winId["animation:nprocs:value"] = nprocs.GetId()
  1686. gridSizer.Add(nprocs, pos=(row, 1), flag=wx.ALIGN_RIGHT)
  1687. row += 1
  1688. gridSizer.Add(
  1689. StaticText(parent=panel, label=_("Text foreground color:")),
  1690. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
  1691. pos=(row, 0),
  1692. )
  1693. color = csel.ColourSelect(
  1694. parent=panel,
  1695. colour=UserSettings.Get(group="animation", key="font", subkey="fgcolor"),
  1696. size=globalvar.DIALOG_COLOR_SIZE,
  1697. )
  1698. color.SetName("GetColour")
  1699. self.winId["animation:font:fgcolor"] = color.GetId()
  1700. gridSizer.Add(color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
  1701. row += 1
  1702. gridSizer.Add(
  1703. StaticText(parent=panel, label=_("Text background color:")),
  1704. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
  1705. pos=(row, 0),
  1706. )
  1707. color = csel.ColourSelect(
  1708. parent=panel,
  1709. colour=UserSettings.Get(group="animation", key="font", subkey="bgcolor"),
  1710. size=globalvar.DIALOG_COLOR_SIZE,
  1711. )
  1712. color.SetName("GetColour")
  1713. self.winId["animation:font:bgcolor"] = color.GetId()
  1714. gridSizer.Add(color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
  1715. gridSizer.AddGrowableCol(1)
  1716. sizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
  1717. border.Add(sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
  1718. panel.SetSizer(border)
  1719. return panel
  1720. def _createTemporalPage(self, notebook):
  1721. """Create notebook page for temporal settings"""
  1722. panel = SP.ScrolledPanel(parent=notebook)
  1723. panel.SetupScrolling(scroll_x=False, scroll_y=True)
  1724. notebook.AddPage(page=panel, text=_("Time"))
  1725. border = wx.BoxSizer(wx.VERTICAL)
  1726. sizer = wx.BoxSizer(wx.VERTICAL)
  1727. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1728. row = 0
  1729. gridSizer.Add(
  1730. StaticText(parent=panel, label=_("Absolute time format:")),
  1731. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
  1732. pos=(row, 0),
  1733. )
  1734. self.tempFormat = ComboBox(parent=panel, name="GetValue")
  1735. self.tempFormat.SetItems(self._timeFormats)
  1736. self.tempFormat.SetValue(self._initFormat)
  1737. self.winId["animation:temporal:format"] = self.tempFormat.GetId()
  1738. gridSizer.Add(self.tempFormat, pos=(row, 1), flag=wx.ALIGN_RIGHT)
  1739. self.infoTimeLabel = StaticText(parent=panel)
  1740. self.tempFormat.Bind(
  1741. wx.EVT_COMBOBOX, lambda evt: self._setTimeFormat(self.tempFormat.GetValue())
  1742. )
  1743. self.tempFormat.Bind(
  1744. wx.EVT_TEXT, lambda evt: self._setTimeFormat(self.tempFormat.GetValue())
  1745. )
  1746. self.tempFormat.SetToolTip(
  1747. _(
  1748. "Click and then press key up or down to preview "
  1749. "different date and time formats. "
  1750. "Type custom format string."
  1751. )
  1752. )
  1753. row += 1
  1754. gridSizer.Add(
  1755. self.infoTimeLabel,
  1756. pos=(row, 0),
  1757. span=(1, 2),
  1758. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
  1759. )
  1760. self._setTimeFormat(self.tempFormat.GetValue())
  1761. row += 1
  1762. link = HyperlinkCtrl(
  1763. panel,
  1764. id=wx.ID_ANY,
  1765. label=_("Learn more about formatting options"),
  1766. url="http://docs.python.org/2/library/datetime.html#"
  1767. "strftime-and-strptime-behavior",
  1768. )
  1769. link.SetNormalColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
  1770. link.SetVisitedColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
  1771. gridSizer.Add(
  1772. link,
  1773. pos=(row, 0),
  1774. span=(1, 2),
  1775. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
  1776. )
  1777. row += 2
  1778. noDataCheck = CheckBox(panel, label=_("Display instances with no data"))
  1779. noDataCheck.SetToolTip(
  1780. _(
  1781. "When animating instant-based data which have irregular timestamps "
  1782. "you can display 'no data frame' (checked option) or "
  1783. "keep last frame."
  1784. )
  1785. )
  1786. noDataCheck.SetValue(
  1787. self.settings.Get(
  1788. group="animation", key="temporal", subkey=["nodata", "enable"]
  1789. )
  1790. )
  1791. self.winId["animation:temporal:nodata:enable"] = noDataCheck.GetId()
  1792. gridSizer.Add(
  1793. noDataCheck,
  1794. pos=(row, 0),
  1795. span=(1, 2),
  1796. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
  1797. )
  1798. gridSizer.AddGrowableCol(1)
  1799. sizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
  1800. border.Add(sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
  1801. panel.SetSizer(border)
  1802. return panel
  1803. def _setTimeFormat(self, formatString):
  1804. now = datetime.datetime.now()
  1805. try:
  1806. label = datetime.datetime.strftime(now, formatString)
  1807. self._format = formatString
  1808. except ValueError:
  1809. label = _("Invalid")
  1810. self.infoTimeLabel.SetLabel(label)
  1811. self.infoTimeLabel.GetContainingSizer().Layout()
  1812. def _updateSettings(self):
  1813. self.tempFormat.SetValue(self._format)
  1814. PreferencesBaseDialog._updateSettings(self)
  1815. if self._format != self._initFormat:
  1816. self.formatChanged.emit()
  1817. return True
  1818. def test():
  1819. import wx.lib.inspection
  1820. app = wx.App()
  1821. # testTemporalLayer()
  1822. # testAnimLmgr()
  1823. testAnimInput()
  1824. # wx.lib.inspection.InspectionTool().Show()
  1825. app.MainLoop()
  1826. def testAnimInput():
  1827. anim = AnimationData()
  1828. anim.SetDefaultValues(animationIndex=0, windowIndex=0)
  1829. dlg = InputDialog(parent=None, mode="add", animationData=anim)
  1830. dlg.Show()
  1831. def testAnimEdit():
  1832. anim = AnimationData()
  1833. anim.SetDefaultValues(animationIndex=0, windowIndex=0)
  1834. dlg = EditDialog(parent=None, animationData=[anim])
  1835. dlg.Show()
  1836. def testExport():
  1837. dlg = ExportDialog(parent=None, temporal=TemporalMode.TEMPORAL, timeTick=200)
  1838. if dlg.ShowModal() == wx.ID_OK:
  1839. print(dlg.GetDecorations())
  1840. print(dlg.GetExportInformation())
  1841. dlg.Destroy()
  1842. else:
  1843. dlg.Destroy()
  1844. def testTemporalLayer():
  1845. frame = wx.Frame(None)
  1846. frame.Show()
  1847. layer = AnimLayer()
  1848. dlg = AddTemporalLayerDialog(parent=frame, layer=layer)
  1849. if dlg.ShowModal() == wx.ID_OK:
  1850. layer = dlg.GetLayer()
  1851. print(layer.name, layer.cmd, layer.mapType)
  1852. dlg.Destroy()
  1853. else:
  1854. dlg.Destroy()
  1855. def testAnimLmgr():
  1856. from core.layerlist import LayerList
  1857. frame = wx.Frame(None)
  1858. mgr = AnimSimpleLayerManager(parent=frame, layerList=LayerList())
  1859. frame.mgr = mgr
  1860. frame.Show()
  1861. if __name__ == "__main__":
  1862. gcore.set_raise_on_error(True)
  1863. test()