dialogs.py 78 KB

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