You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1451 lines
49 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """Youtubedlg module responsible for the main app window. """
  4. from __future__ import unicode_literals
  5. import os
  6. import gettext
  7. import wx
  8. from wx.lib.pubsub import setuparg1 #NOTE Should remove deprecated
  9. from wx.lib.pubsub import pub as Publisher
  10. from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
  11. from .parsers import OptionsParser
  12. from .optionsframe import (
  13. OptionsFrame,
  14. LogGUI
  15. )
  16. from .updatemanager import (
  17. UPDATE_PUB_TOPIC,
  18. UpdateThread
  19. )
  20. from .downloadmanager import (
  21. MANAGER_PUB_TOPIC,
  22. WORKER_PUB_TOPIC,
  23. DownloadManager,
  24. DownloadList,
  25. DownloadItem
  26. )
  27. from .utils import (
  28. YOUTUBEDL_BIN,
  29. get_pixmaps_dir,
  30. get_icon_file,
  31. shutdown_sys,
  32. remove_file,
  33. open_file,
  34. get_time
  35. )
  36. from .widgets import CustomComboBox
  37. from .formats import (
  38. DEFAULT_FORMATS,
  39. VIDEO_FORMATS,
  40. AUDIO_FORMATS,
  41. FORMATS
  42. )
  43. from .info import (
  44. __descriptionfull__,
  45. __licensefull__,
  46. __projecturl__,
  47. __appname__,
  48. __author__
  49. )
  50. from .version import __version__
  51. class MainFrame(wx.Frame):
  52. """Main window class.
  53. This class is responsible for creating the main app window
  54. and binding the events.
  55. Attributes:
  56. FRAMES_MIN_SIZE (tuple): Tuple that contains the minumum width, height of the frame.
  57. Labels area (strings): Strings for the widgets labels.
  58. STATUSLIST_COLUMNS (dict): Python dictionary which holds informations
  59. about the wxListCtrl columns. For more informations read the
  60. comments above the STATUSLIST_COLUMNS declaration.
  61. Args:
  62. opt_manager (optionsmanager.OptionsManager): Object responsible for
  63. handling the settings.
  64. log_manager (logmanager.LogManager): Object responsible for handling
  65. the log stuff.
  66. parent (wx.Window): Frame parent.
  67. """
  68. FRAMES_MIN_SIZE = (560, 360)
  69. # Labels area
  70. URLS_LABEL = _("Enter URLs below")
  71. UPDATE_LABEL = _("Update")
  72. OPTIONS_LABEL = _("Options")
  73. STOP_LABEL = _("Stop")
  74. INFO_LABEL = _("Info")
  75. WELCOME_MSG = _("Welcome")
  76. WARNING_LABEL = _("Warning")
  77. ADD_LABEL = _("Add")
  78. DOWNLOAD_LIST_LABEL = _("Download list")
  79. DELETE_LABEL = _("Delete")
  80. PLAY_LABEL = _("Play")
  81. UP_LABEL = _("Up")
  82. DOWN_LABEL = _("Down")
  83. RELOAD_LABEL = _("Reload")
  84. PAUSE_LABEL = _("Pause")
  85. START_LABEL = _("Start")
  86. ABOUT_LABEL = _("About")
  87. VIEWLOG_LABEL = _("View Log")
  88. SUCC_REPORT_MSG = _("Successfully downloaded {0} URL(s) in {1} "
  89. "day(s) {2} hour(s) {3} minute(s) {4} second(s)")
  90. DL_COMPLETED_MSG = _("Downloads completed")
  91. URL_REPORT_MSG = _("Total Progress: {0:.1f}% | Queued ({1}) Paused ({2}) Active ({3}) Completed ({4})")
  92. CLOSING_MSG = _("Stopping downloads")
  93. CLOSED_MSG = _("Downloads stopped")
  94. PROVIDE_URL_MSG = _("You need to provide at least one URL")
  95. DOWNLOAD_STARTED = _("Downloads started")
  96. CHOOSE_DIRECTORY = _("Choose Directory")
  97. DOWNLOAD_ACTIVE = _("Download in progress. Please wait for all the downloads to complete")
  98. UPDATE_ACTIVE = _("Update already in progress.")
  99. UPDATING_MSG = _("Downloading latest youtube-dl. Please wait...")
  100. UPDATE_ERR_MSG = _("Youtube-dl download failed [{0}]")
  101. UPDATE_SUCC_MSG = _("Youtube-dl downloaded correctly")
  102. OPEN_DIR_ERR = _("Unable to open directory: '{dir}'. "
  103. "The specified path does not exist")
  104. SHUTDOWN_ERR = _("Error while shutting down. "
  105. "Make sure you typed the correct password")
  106. SHUTDOWN_MSG = _("Shutting down system")
  107. VIDEO_LABEL = _("Title")
  108. EXTENSION_LABEL = _("Extension")
  109. SIZE_LABEL = _("Size")
  110. PERCENT_LABEL = _("Percent")
  111. ETA_LABEL = _("ETA")
  112. SPEED_LABEL = _("Speed")
  113. STATUS_LABEL = _("Status")
  114. #################################
  115. # STATUSLIST_COLUMNS
  116. #
  117. # Dictionary which contains the columns for the wxListCtrl widget.
  118. # Each key represents a column and holds informations about itself.
  119. # Structure informations:
  120. # column_key: (column_number, column_label, minimum_width, is_resizable)
  121. #
  122. STATUSLIST_COLUMNS = {
  123. 'filename': (0, VIDEO_LABEL, 150, True),
  124. 'extension': (1, EXTENSION_LABEL, 60, False),
  125. 'filesize': (2, SIZE_LABEL, 80, False),
  126. 'percent': (3, PERCENT_LABEL, 65, False),
  127. 'eta': (4, ETA_LABEL, 45, False),
  128. 'speed': (5, SPEED_LABEL, 90, False),
  129. 'status': (6, STATUS_LABEL, 160, False)
  130. }
  131. def __init__(self, opt_manager, log_manager, parent=None):
  132. super(MainFrame, self).__init__(parent, wx.ID_ANY, __appname__, size=opt_manager.options["main_win_size"])
  133. self.opt_manager = opt_manager
  134. self.log_manager = log_manager
  135. self.download_manager = None
  136. self.update_thread = None
  137. self.app_icon = None #REFACTOR Get and set on __init__.py
  138. self._download_list = DownloadList()
  139. # Set up youtube-dl options parser
  140. self._options_parser = OptionsParser()
  141. # Get the pixmaps directory
  142. self._pixmaps_path = get_pixmaps_dir()
  143. # Set the Timer
  144. self._app_timer = wx.Timer(self)
  145. # Set the app icon
  146. app_icon_path = get_icon_file()
  147. if app_icon_path is not None:
  148. self.app_icon = wx.Icon(app_icon_path, wx.BITMAP_TYPE_PNG)
  149. self.SetIcon(self.app_icon)
  150. bitmap_data = (
  151. ("down", "arrow_down_32px.png"),
  152. ("up", "arrow_up_32px.png"),
  153. ("play", "camera_32px.png"),
  154. ("start", "cloud_download_32px.png"),
  155. ("delete", "delete_32px.png"),
  156. ("folder", "folder_32px.png"),
  157. ("pause", "pause_32px.png"),
  158. ("resume", "play_arrow_32px.png"),
  159. ("reload", "reload_32px.png"),
  160. ("settings", "settings_20px.png"),
  161. ("stop", "stop_32px.png")
  162. )
  163. self._bitmaps = {}
  164. for item in bitmap_data:
  165. target, name = item
  166. self._bitmaps[target] = wx.Bitmap(os.path.join(self._pixmaps_path, name))
  167. # Set the data for all the wx.Button items
  168. # name, label, size, event_handler
  169. buttons_data = (
  170. ("delete", self.DELETE_LABEL, (-1, -1), self._on_delete, wx.BitmapButton),
  171. ("play", self.PLAY_LABEL, (-1, -1), self._on_play, wx.BitmapButton),
  172. ("up", self.UP_LABEL, (-1, -1), self._on_arrow_up, wx.BitmapButton),
  173. ("down", self.DOWN_LABEL, (-1, -1), self._on_arrow_down, wx.BitmapButton),
  174. ("reload", self.RELOAD_LABEL, (-1, -1), self._on_reload, wx.BitmapButton),
  175. ("pause", self.PAUSE_LABEL, (-1, -1), self._on_pause, wx.BitmapButton),
  176. ("start", self.START_LABEL, (-1, -1), self._on_start, wx.BitmapButton),
  177. ("savepath", "...", (35, -1), self._on_savepath, wx.Button),
  178. ("add", self.ADD_LABEL, (-1, -1), self._on_add, wx.Button)
  179. )
  180. # Set the data for the settings menu item
  181. # label, event_handler
  182. settings_menu_data = (
  183. (self.OPTIONS_LABEL, self._on_options),
  184. (self.UPDATE_LABEL, self._on_update),
  185. (self.VIEWLOG_LABEL, self._on_viewlog),
  186. (self.ABOUT_LABEL, self._on_about)
  187. )
  188. statuslist_menu_data = (
  189. (_("Get URL"), self._on_geturl),
  190. (_("Get command"), self._on_getcmd),
  191. (_("Open destination"), self._on_open_dest)
  192. )
  193. # Create options frame
  194. self._options_frame = OptionsFrame(self)
  195. # Create frame components
  196. self._panel = wx.Panel(self)
  197. self._url_text = self._create_statictext(self.URLS_LABEL)
  198. #REFACTOR Move to buttons_data
  199. self._settings_button = self._create_bitmap_button(self._bitmaps["settings"], (30, 30), self._on_settings)
  200. self._url_list = self._create_textctrl(wx.TE_MULTILINE | wx.TE_DONTWRAP, self._on_urllist_edit)
  201. self._folder_icon = self._create_static_bitmap(self._bitmaps["folder"], self._on_open_path)
  202. self._path_combobox = ExtComboBox(self._panel, 5, style=wx.CB_READONLY)
  203. self._videoformat_combobox = CustomComboBox(self._panel, style=wx.CB_READONLY)
  204. self._download_text = self._create_statictext(self.DOWNLOAD_LIST_LABEL)
  205. self._status_list = ListCtrl(self.STATUSLIST_COLUMNS,
  206. parent=self._panel,
  207. style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES)
  208. # Dictionary to store all the buttons
  209. self._buttons = {}
  210. for item in buttons_data:
  211. name, label, size, evt_handler, parent = item
  212. button = parent(self._panel, size=size)
  213. if parent == wx.Button:
  214. button.SetLabel(label)
  215. elif parent == wx.BitmapButton:
  216. button.SetToolTip(wx.ToolTip(label))
  217. if name in self._bitmaps:
  218. button.SetBitmap(self._bitmaps[name], wx.TOP)
  219. if evt_handler is not None:
  220. button.Bind(wx.EVT_BUTTON, evt_handler)
  221. self._buttons[name] = button
  222. self._status_bar = self.CreateStatusBar()
  223. # Create extra components
  224. self._settings_menu = self._create_menu_item(settings_menu_data)
  225. self._statuslist_menu = self._create_menu_item(statuslist_menu_data)
  226. # Overwrite the menu hover event to avoid changing the statusbar
  227. self.Bind(wx.EVT_MENU_HIGHLIGHT, lambda event: None)
  228. # Bind extra events
  229. self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._on_statuslist_right_click, self._status_list)
  230. self.Bind(wx.EVT_TEXT, self._update_savepath, self._path_combobox)
  231. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._update_pause_button, self._status_list)
  232. self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._update_pause_button, self._status_list)
  233. self.Bind(wx.EVT_CLOSE, self._on_close)
  234. self.Bind(wx.EVT_TIMER, self._on_timer, self._app_timer)
  235. self._videoformat_combobox.Bind(wx.EVT_COMBOBOX, self._update_videoformat)
  236. # Set threads wxCallAfter handlers
  237. self._set_publisher(self._update_handler, UPDATE_PUB_TOPIC)
  238. self._set_publisher(self._download_worker_handler, WORKER_PUB_TOPIC)
  239. self._set_publisher(self._download_manager_handler, MANAGER_PUB_TOPIC)
  240. # Set up extra stuff
  241. self.Center()
  242. self.SetMinSize(self.FRAMES_MIN_SIZE)
  243. self._status_bar_write(self.WELCOME_MSG)
  244. self._update_videoformat_combobox()
  245. self._path_combobox.LoadMultiple(self.opt_manager.options["save_path_dirs"])
  246. self._path_combobox.SetValue(self.opt_manager.options["save_path"])
  247. self._set_layout()
  248. self._url_list.SetFocus()
  249. def _create_menu_item(self, items):
  250. menu = wx.Menu()
  251. for item in items:
  252. label, evt_handler = item
  253. menu_item = menu.Append(-1, label)
  254. menu.Bind(wx.EVT_MENU, evt_handler, menu_item)
  255. return menu
  256. def _on_statuslist_right_click(self, event):
  257. selected = event.GetIndex()
  258. if selected != -1:
  259. self._status_list.deselect_all()
  260. self._status_list.Select(selected, on=1)
  261. self.PopupMenu(self._statuslist_menu)
  262. def _on_open_dest(self, event):
  263. selected = self._status_list.get_selected()
  264. if selected != -1:
  265. object_id = self._status_list.GetItemData(selected)
  266. download_item = self._download_list.get_item(object_id)
  267. if download_item.path:
  268. open_file(download_item.path)
  269. def _on_open_path(self, event):
  270. open_file(self._path_combobox.GetValue())
  271. def _on_geturl(self, event):
  272. selected = self._status_list.get_selected()
  273. if selected != -1:
  274. object_id = self._status_list.GetItemData(selected)
  275. download_item = self._download_list.get_item(object_id)
  276. url = download_item.url
  277. if not wx.TheClipboard.IsOpened():
  278. clipdata = wx.TextDataObject()
  279. clipdata.SetText(url)
  280. wx.TheClipboard.Open()
  281. wx.TheClipboard.SetData(clipdata)
  282. wx.TheClipboard.Close()
  283. def _on_getcmd(self, event):
  284. selected = self._status_list.get_selected()
  285. if selected != -1:
  286. object_id = self._status_list.GetItemData(selected)
  287. download_item = self._download_list.get_item(object_id)
  288. cmd = [YOUTUBEDL_BIN] + download_item.options + [download_item.url]
  289. cmd = " ".join(cmd)
  290. if not wx.TheClipboard.IsOpened():
  291. clipdata = wx.TextDataObject()
  292. clipdata.SetText(cmd)
  293. wx.TheClipboard.Open()
  294. wx.TheClipboard.SetData(clipdata)
  295. wx.TheClipboard.Close()
  296. def _on_timer(self, event):
  297. total_percentage = 0.0
  298. queued = paused = active = completed = 0
  299. for item in self._download_list.get_items():
  300. if item.stage == "Queued":
  301. queued += 1
  302. if item.stage == "Paused":
  303. paused += 1
  304. if item.stage == "Active":
  305. active += 1
  306. total_percentage += float(item.progress_stats["percent"].split('%')[0])
  307. if item.stage == "Completed":
  308. completed += 1
  309. # TODO Store percentage as float in the DownloadItem?
  310. # TODO DownloadList keep track for each item stage?
  311. # TODO Should i count the paused items?
  312. # total_percentage += queued * 0.0% + paused * 0.0% + completed * 100.0%
  313. total_percentage += completed * 100.0
  314. total_percentage /= len(self._download_list)
  315. msg = self.URL_REPORT_MSG.format(total_percentage, queued, paused, active, completed)
  316. self._status_bar_write(msg)
  317. def _update_pause_button(self, event):
  318. selected_rows = self._status_list.get_all_selected()
  319. label = "Pause"
  320. bitmap = self._bitmaps["pause"]
  321. for row in selected_rows:
  322. object_id = self._status_list.GetItemData(row)
  323. download_item = self._download_list.get_item(object_id)
  324. if download_item.stage == "Paused":
  325. # If we find one or more items in Paused
  326. # state set the button functionality to resume
  327. label = "Resume"
  328. bitmap = self._bitmaps["resume"]
  329. break
  330. self._buttons["pause"].SetLabel(label)
  331. self._buttons["pause"].SetToolTip(wx.ToolTip(label))
  332. self._buttons["pause"].SetBitmap(bitmap, wx.TOP)
  333. def _update_videoformat_combobox(self):
  334. self._videoformat_combobox.Clear()
  335. self._videoformat_combobox.add_items(list(DEFAULT_FORMATS.values()), False)
  336. vformats = []
  337. for vformat in self.opt_manager.options["selected_video_formats"]:
  338. vformats.append(FORMATS[vformat])
  339. aformats = []
  340. for aformat in self.opt_manager.options["selected_audio_formats"]:
  341. aformats.append(FORMATS[aformat])
  342. if vformats:
  343. self._videoformat_combobox.add_header("Video")
  344. self._videoformat_combobox.add_items(vformats)
  345. if aformats:
  346. self._videoformat_combobox.add_header("Audio")
  347. self._videoformat_combobox.add_items(aformats)
  348. current_index = self._videoformat_combobox.FindString(FORMATS[self.opt_manager.options["selected_format"]])
  349. if current_index == wx.NOT_FOUND:
  350. self._videoformat_combobox.SetSelection(0)
  351. else:
  352. self._videoformat_combobox.SetSelection(current_index)
  353. self._update_videoformat(None)
  354. def _update_videoformat(self, event):
  355. self.opt_manager.options["selected_format"] = selected_format = FORMATS[self._videoformat_combobox.GetValue()]
  356. if selected_format in VIDEO_FORMATS:
  357. self.opt_manager.options["video_format"] = selected_format
  358. self.opt_manager.options["audio_format"] = "" #NOTE Set to default value, check parsers.py
  359. elif selected_format in AUDIO_FORMATS:
  360. self.opt_manager.options["video_format"] = DEFAULT_FORMATS["default"]
  361. self.opt_manager.options["audio_format"] = selected_format
  362. else:
  363. self.opt_manager.options["video_format"] = DEFAULT_FORMATS["default"]
  364. self.opt_manager.options["audio_format"] = ""
  365. def _update_savepath(self, event):
  366. self.opt_manager.options["save_path"] = self._path_combobox.GetValue()
  367. def _on_delete(self, event):
  368. index = self._status_list.get_next_selected()
  369. if index == -1:
  370. dlg = ButtonsChoiceDialog(self, ["Remove all", "Remove completed"], "No items selected. Please pick an action.", "Delete")
  371. ret_code = dlg.ShowModal()
  372. dlg.Destroy()
  373. #TODO Maybe add this functionality directly to DownloadList?
  374. if ret_code == 1:
  375. for ditem in self._download_list.get_items():
  376. if ditem.stage != "Active":
  377. self._status_list.remove_row(self._download_list.index(ditem.object_id))
  378. self._download_list.remove(ditem.object_id)
  379. if ret_code == 2:
  380. for ditem in self._download_list.get_items():
  381. if ditem.stage == "Completed":
  382. self._status_list.remove_row(self._download_list.index(ditem.object_id))
  383. self._download_list.remove(ditem.object_id)
  384. else:
  385. if self.opt_manager.options["confirm_deletion"]:
  386. dlg = wx.MessageDialog(self, "Are you sure you want to remove selected items?", "Delete", wx.YES_NO | wx.ICON_QUESTION)
  387. result = dlg.ShowModal() == wx.ID_YES
  388. dlg.Destroy()
  389. else:
  390. result = True
  391. if result:
  392. while index >= 0:
  393. object_id = self._status_list.GetItemData(index)
  394. selected_download_item = self._download_list.get_item(object_id)
  395. if selected_download_item.stage == "Active":
  396. self._create_popup("Item is active, cannot remove", self.WARNING_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  397. else:
  398. #if selected_download_item.stage == "Completed":
  399. #dlg = wx.MessageDialog(self, "Do you want to remove the files associated with this item?", "Remove files", wx.YES_NO | wx.ICON_QUESTION)
  400. #result = dlg.ShowModal() == wx.ID_YES
  401. #dlg.Destroy()
  402. #if result:
  403. #for cur_file in selected_download_item.get_files():
  404. #remove_file(cur_file)
  405. self._status_list.remove_row(index)
  406. self._download_list.remove(object_id)
  407. index -= 1
  408. index = self._status_list.get_next_selected(index)
  409. self._update_pause_button(None)
  410. def _on_play(self, event):
  411. selected_rows = self._status_list.get_all_selected()
  412. if selected_rows:
  413. for selected_row in selected_rows:
  414. object_id = self._status_list.GetItemData(selected_row)
  415. selected_download_item = self._download_list.get_item(object_id)
  416. if selected_download_item.stage == "Completed":
  417. if selected_download_item.filenames:
  418. filename = selected_download_item.get_files()[-1]
  419. open_file(filename)
  420. else:
  421. self._create_popup("Item is not completed", self.INFO_LABEL, wx.OK | wx.ICON_INFORMATION)
  422. def _on_arrow_up(self, event):
  423. index = self._status_list.get_next_selected()
  424. if index != -1:
  425. while index >= 0:
  426. object_id = self._status_list.GetItemData(index)
  427. download_item = self._download_list.get_item(object_id)
  428. new_index = index - 1
  429. if new_index < 0:
  430. new_index = 0
  431. if not self._status_list.IsSelected(new_index):
  432. self._download_list.move_up(object_id)
  433. self._status_list.move_item_up(index)
  434. self._status_list._update_from_item(new_index, download_item)
  435. index = self._status_list.get_next_selected(index)
  436. def _on_arrow_down(self, event):
  437. index = self._status_list.get_next_selected(reverse=True)
  438. if index != -1:
  439. while index >= 0:
  440. object_id = self._status_list.GetItemData(index)
  441. download_item = self._download_list.get_item(object_id)
  442. new_index = index + 1
  443. if new_index >= self._status_list.GetItemCount():
  444. new_index = self._status_list.GetItemCount() - 1
  445. if not self._status_list.IsSelected(new_index):
  446. self._download_list.move_down(object_id)
  447. self._status_list.move_item_down(index)
  448. self._status_list._update_from_item(new_index, download_item)
  449. index = self._status_list.get_next_selected(index, True)
  450. def _on_reload(self, event):
  451. selected_rows = self._status_list.get_all_selected()
  452. if not selected_rows:
  453. for index, item in enumerate(self._download_list.get_items()):
  454. if item.stage == "Paused" or item.stage == "Completed":
  455. item.reset()
  456. self._status_list._update_from_item(index, item)
  457. else:
  458. for selected_row in selected_rows:
  459. object_id = self._status_list.GetItemData(selected_row)
  460. item = self._download_list.get_item(object_id)
  461. if item.stage == "Paused" or item.stage == "Completed":
  462. item.reset()
  463. self._status_list._update_from_item(selected_row, item)
  464. self._update_pause_button(None)
  465. def _on_pause(self, event):
  466. selected_rows = self._status_list.get_all_selected()
  467. if selected_rows:
  468. #REFACTOR Use DoubleStageButton for this and check stage
  469. if self._buttons["pause"].GetLabel() == "Pause":
  470. new_state = "Paused"
  471. else:
  472. new_state = "Queued"
  473. for selected_row in selected_rows:
  474. object_id = self._status_list.GetItemData(selected_row)
  475. download_item = self._download_list.get_item(object_id)
  476. if download_item.stage == "Queued" or download_item.stage == "Paused":
  477. self._download_list.change_stage(object_id, new_state)
  478. self._status_list._update_from_item(selected_row, download_item)
  479. self._update_pause_button(None)
  480. def _on_start(self, event):
  481. if self.update_thread is not None and self.update_thread.is_alive():
  482. self._create_popup("Update in progress. Please wait for the update to complete",
  483. self.WARNING_LABEL,
  484. wx.OK | wx.ICON_EXCLAMATION)
  485. else:
  486. if self.download_manager is None:
  487. self._start_download()
  488. else:
  489. self.download_manager.stop_downloads()
  490. def _on_savepath(self, event):
  491. dlg = wx.DirDialog(self, self.CHOOSE_DIRECTORY, self._path_combobox.GetStringSelection(), wx.DD_CHANGE_DIR)
  492. if dlg.ShowModal() == wx.ID_OK:
  493. path = dlg.GetPath()
  494. self._path_combobox.Append(path)
  495. self._path_combobox.SetValue(path)
  496. self._update_savepath(None)
  497. dlg.Destroy()
  498. def _on_add(self, event):
  499. urls = self._get_urls()
  500. if not urls:
  501. self._create_popup(self.PROVIDE_URL_MSG,
  502. self.WARNING_LABEL,
  503. wx.OK | wx.ICON_EXCLAMATION)
  504. else:
  505. self._url_list.Clear()
  506. options = self._options_parser.parse(self.opt_manager.options)
  507. for url in urls:
  508. download_item = DownloadItem(url, options)
  509. download_item.path = self.opt_manager.options["save_path"]
  510. if not self._download_list.has_item(download_item.object_id):
  511. self._status_list.bind_item(download_item)
  512. self._download_list.insert(download_item)
  513. def _on_settings(self, event):
  514. event_object_pos = event.EventObject.GetPosition()
  515. event_object_height = event.EventObject.GetSize()[1]
  516. event_object_pos = (event_object_pos[0], event_object_pos[1] + event_object_height)
  517. self.PopupMenu(self._settings_menu, event_object_pos)
  518. def _on_viewlog(self, event):
  519. log_window = LogGUI(self)
  520. log_window.load(self.log_manager.log_file)
  521. log_window.Show()
  522. def _on_about(self, event):
  523. info = wx.AboutDialogInfo()
  524. if self.app_icon is not None:
  525. info.SetIcon(self.app_icon)
  526. info.SetName(__appname__)
  527. info.SetVersion(__version__)
  528. info.SetDescription(__descriptionfull__)
  529. info.SetWebSite(__projecturl__)
  530. info.SetLicense(__licensefull__)
  531. info.AddDeveloper(__author__)
  532. wx.AboutBox(info)
  533. def _set_publisher(self, handler, topic):
  534. """Sets a handler for the given topic.
  535. Args:
  536. handler (function): Can be any function with one parameter
  537. the message that the caller sends.
  538. topic (string): Can be any string that identifies the caller.
  539. You can bind multiple handlers on the same topic or
  540. multiple topics on the same handler.
  541. """
  542. Publisher.subscribe(handler, topic)
  543. def _create_statictext(self, label):
  544. return wx.StaticText(self._panel, label=label)
  545. def _create_bitmap_button(self, icon, size=(-1, -1), handler=None):
  546. button = wx.BitmapButton(self._panel, bitmap=icon, size=size, style=wx.NO_BORDER)
  547. if handler is not None:
  548. button.Bind(wx.EVT_BUTTON, handler)
  549. return button
  550. def _create_static_bitmap(self, icon, event_handler=None):
  551. static_bitmap = wx.StaticBitmap(self._panel, bitmap=icon)
  552. if event_handler is not None:
  553. static_bitmap.Bind(wx.EVT_LEFT_DCLICK, event_handler)
  554. return static_bitmap
  555. def _create_textctrl(self, style=None, event_handler=None):
  556. if style is None:
  557. textctrl = wx.TextCtrl(self._panel)
  558. else:
  559. textctrl = wx.TextCtrl(self._panel, style=style)
  560. if event_handler is not None:
  561. textctrl.Bind(wx.EVT_TEXT_PASTE, event_handler)
  562. textctrl.Bind(wx.EVT_MIDDLE_DOWN, event_handler)
  563. if os.name == 'nt':
  564. # Enable CTRL+A on Windows
  565. def win_ctrla_eventhandler(event):
  566. if event.GetKeyCode() == wx.WXK_CONTROL_A:
  567. event.GetEventObject().SelectAll()
  568. event.Skip()
  569. textctrl.Bind(wx.EVT_CHAR, win_ctrla_eventhandler)
  570. return textctrl
  571. def _create_popup(self, text, title, style):
  572. wx.MessageBox(text, title, style)
  573. def _set_layout(self):
  574. """Sets the layout of the main window. """
  575. main_sizer = wx.BoxSizer()
  576. panel_sizer = wx.BoxSizer(wx.VERTICAL)
  577. top_sizer = wx.BoxSizer(wx.HORIZONTAL)
  578. top_sizer.Add(self._url_text, 0, wx.ALIGN_BOTTOM | wx.BOTTOM, 5)
  579. top_sizer.AddSpacer((-1, -1), 1)
  580. top_sizer.Add(self._settings_button)
  581. panel_sizer.Add(top_sizer, 0, wx.EXPAND)
  582. panel_sizer.Add(self._url_list, 1, wx.EXPAND)
  583. mid_sizer = wx.BoxSizer(wx.HORIZONTAL)
  584. mid_sizer.Add(self._folder_icon)
  585. mid_sizer.Add(self._path_combobox, 2, wx.ALIGN_CENTER_VERTICAL)
  586. mid_sizer.AddSpacer((5, -1))
  587. mid_sizer.Add(self._buttons["savepath"], flag=wx.ALIGN_CENTER_VERTICAL)
  588. mid_sizer.AddSpacer((10, -1), 1)
  589. mid_sizer.Add(self._videoformat_combobox, 1, wx.ALIGN_CENTER_VERTICAL)
  590. mid_sizer.AddSpacer((5, -1))
  591. mid_sizer.Add(self._buttons["add"], flag=wx.ALIGN_CENTER_VERTICAL)
  592. panel_sizer.Add(mid_sizer, 0, wx.EXPAND | wx.ALL, 10)
  593. panel_sizer.Add(self._download_text, 0, wx.BOTTOM, 5)
  594. panel_sizer.Add(self._status_list, 2, wx.EXPAND)
  595. bottom_sizer = wx.BoxSizer(wx.HORIZONTAL)
  596. bottom_sizer.Add(self._buttons["delete"])
  597. bottom_sizer.AddSpacer((5, -1))
  598. bottom_sizer.Add(self._buttons["play"])
  599. bottom_sizer.AddSpacer((5, -1))
  600. bottom_sizer.Add(self._buttons["up"])
  601. bottom_sizer.AddSpacer((5, -1))
  602. bottom_sizer.Add(self._buttons["down"])
  603. bottom_sizer.AddSpacer((5, -1))
  604. bottom_sizer.Add(self._buttons["reload"])
  605. bottom_sizer.AddSpacer((5, -1))
  606. bottom_sizer.Add(self._buttons["pause"])
  607. bottom_sizer.AddSpacer((10, -1), 1)
  608. bottom_sizer.Add(self._buttons["start"])
  609. panel_sizer.Add(bottom_sizer, 0, wx.EXPAND | wx.TOP, 5)
  610. main_sizer.Add(panel_sizer, 1, wx.ALL | wx.EXPAND, 10)
  611. self._panel.SetSizer(main_sizer)
  612. self._panel.Layout()
  613. def _update_youtubedl(self):
  614. """Update youtube-dl binary to the latest version. """
  615. if self.download_manager is not None and self.download_manager.is_alive():
  616. self._create_popup(self.DOWNLOAD_ACTIVE,
  617. self.WARNING_LABEL,
  618. wx.OK | wx.ICON_EXCLAMATION)
  619. elif self.update_thread is not None and self.update_thread.is_alive():
  620. self._create_popup(self.UPDATE_ACTIVE,
  621. self.INFO_LABEL,
  622. wx.OK | wx.ICON_INFORMATION)
  623. else:
  624. self.update_thread = UpdateThread(self.opt_manager.options['youtubedl_path'])
  625. def _status_bar_write(self, msg):
  626. """Display msg in the status bar. """
  627. self._status_bar.SetStatusText(msg)
  628. def _reset_widgets(self):
  629. """Resets GUI widgets after update or download process. """
  630. self._buttons["start"].SetLabel("Start")
  631. self._buttons["start"].SetToolTip(wx.ToolTip("Start"))
  632. self._buttons["start"].SetBitmap(self._bitmaps["start"], wx.TOP)
  633. def _print_stats(self):
  634. """Display download stats in the status bar. """
  635. suc_downloads = self.download_manager.successful
  636. dtime = get_time(self.download_manager.time_it_took)
  637. msg = self.SUCC_REPORT_MSG.format(suc_downloads,
  638. dtime['days'],
  639. dtime['hours'],
  640. dtime['minutes'],
  641. dtime['seconds'])
  642. self._status_bar_write(msg)
  643. def _after_download(self):
  644. """Run tasks after download process has been completed.
  645. Note:
  646. Here you can add any tasks you want to run after the
  647. download process has been completed.
  648. """
  649. if self.opt_manager.options['shutdown']:
  650. dlg = ShutdownDialog(self, 60, "Shutting down in {0} second(s)", "Shutdown")
  651. result = dlg.ShowModal() == wx.ID_OK
  652. dlg.Destroy()
  653. if result:
  654. self.opt_manager.save_to_file()
  655. success = shutdown_sys(self.opt_manager.options['sudo_password'])
  656. if success:
  657. self._status_bar_write(self.SHUTDOWN_MSG)
  658. else:
  659. self._status_bar_write(self.SHUTDOWN_ERR)
  660. else:
  661. if self.opt_manager.options["show_completion_popup"]:
  662. self._create_popup(self.DL_COMPLETED_MSG, self.INFO_LABEL, wx.OK | wx.ICON_INFORMATION)
  663. def _download_worker_handler(self, msg):
  664. """downloadmanager.Worker thread handler.
  665. Handles messages from the Worker thread.
  666. Args:
  667. See downloadmanager.Worker _talk_to_gui() method.
  668. """
  669. signal, data = msg.data
  670. download_item = self._download_list.get_item(data["index"])
  671. download_item.update_stats(data)
  672. row = self._download_list.index(data["index"])
  673. self._status_list._update_from_item(row, download_item)
  674. def _download_manager_handler(self, msg):
  675. """downloadmanager.DownloadManager thread handler.
  676. Handles messages from the DownloadManager thread.
  677. Args:
  678. See downloadmanager.DownloadManager _talk_to_gui() method.
  679. """
  680. data = msg.data
  681. if data == 'finished':
  682. self._print_stats()
  683. self._reset_widgets()
  684. self.download_manager = None
  685. self._app_timer.Stop()
  686. self._after_download()
  687. elif data == 'closed':
  688. self._status_bar_write(self.CLOSED_MSG)
  689. self._reset_widgets()
  690. self.download_manager = None
  691. self._app_timer.Stop()
  692. elif data == 'closing':
  693. self._status_bar_write(self.CLOSING_MSG)
  694. elif data == 'report_active':
  695. pass
  696. #NOTE Remove from here and downloadmanager
  697. #since now we have the wx.Timer to check progress
  698. def _update_handler(self, msg):
  699. """updatemanager.UpdateThread thread handler.
  700. Handles messages from the UpdateThread thread.
  701. Args:
  702. See updatemanager.UpdateThread _talk_to_gui() method.
  703. """
  704. data = msg.data
  705. if data[0] == 'download':
  706. self._status_bar_write(self.UPDATING_MSG)
  707. elif data[0] == 'error':
  708. self._status_bar_write(self.UPDATE_ERR_MSG.format(data[1]))
  709. elif data[0] == 'correct':
  710. self._status_bar_write(self.UPDATE_SUCC_MSG)
  711. else:
  712. self._reset_widgets()
  713. self.update_thread = None
  714. def _get_urls(self):
  715. """Returns urls list. """
  716. return [line for line in self._url_list.GetValue().split('\n') if line]
  717. def _start_download(self):
  718. if self._status_list.is_empty():
  719. self._create_popup("No items to download",
  720. self.WARNING_LABEL,
  721. wx.OK | wx.ICON_EXCLAMATION)
  722. else:
  723. self._app_timer.Start(100)
  724. self.download_manager = DownloadManager(self._download_list, self.opt_manager, self.log_manager)
  725. self._status_bar_write(self.DOWNLOAD_STARTED)
  726. self._buttons["start"].SetLabel(self.STOP_LABEL)
  727. self._buttons["start"].SetToolTip(wx.ToolTip(self.STOP_LABEL))
  728. self._buttons["start"].SetBitmap(self._bitmaps["stop"], wx.TOP)
  729. def _paste_from_clipboard(self):
  730. """Paste the content of the clipboard to the self._url_list widget.
  731. It also adds a new line at the end of the data if not exist.
  732. """
  733. if not wx.TheClipboard.IsOpened():
  734. if wx.TheClipboard.Open():
  735. if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  736. data = wx.TextDataObject()
  737. wx.TheClipboard.GetData(data)
  738. data = data.GetText()
  739. if data[-1] != '\n':
  740. data += '\n'
  741. self._url_list.WriteText(data)
  742. wx.TheClipboard.Close()
  743. def _on_urllist_edit(self, event):
  744. """Event handler of the self._url_list widget.
  745. This method is triggered when the users pastes text into
  746. the URLs list either by using CTRL+V or by using the middle
  747. click of the mouse.
  748. """
  749. if event.GetEventType() == wx.EVT_TEXT_PASTE.typeId:
  750. self._paste_from_clipboard()
  751. else:
  752. wx.TheClipboard.UsePrimarySelection(True)
  753. self._paste_from_clipboard()
  754. wx.TheClipboard.UsePrimarySelection(False)
  755. def _on_update(self, event):
  756. """Event handler of the self._update_btn widget.
  757. This method is used when the update button is pressed to start
  758. the update process.
  759. Note:
  760. Currently there is not way to stop the update process.
  761. """
  762. self._update_youtubedl()
  763. def _on_options(self, event):
  764. """Event handler of the self._options_btn widget.
  765. This method is used when the options button is pressed to show
  766. the options window.
  767. """
  768. self._options_frame.load_all_options()
  769. self._options_frame.Show()
  770. def _on_close(self, event):
  771. """Event handler for the wx.EVT_CLOSE event.
  772. This method is used when the user tries to close the program
  773. to save the options and make sure that the download & update
  774. processes are not running.
  775. """
  776. if self.opt_manager.options["confirm_exit"]:
  777. dlg = wx.MessageDialog(self, "Are you sure you want to exit?", "Exit", wx.YES_NO | wx.ICON_QUESTION)
  778. result = dlg.ShowModal() == wx.ID_YES
  779. dlg.Destroy()
  780. else:
  781. result = True
  782. if result:
  783. self.close()
  784. def close(self):
  785. if self.download_manager is not None:
  786. self.download_manager.stop_downloads()
  787. self.download_manager.join()
  788. if self.update_thread is not None:
  789. self.update_thread.join()
  790. # Store main-options frame size
  791. self.opt_manager.options['main_win_size'] = self.GetSize()
  792. self.opt_manager.options['opts_win_size'] = self._options_frame.GetSize()
  793. self.opt_manager.options["save_path_dirs"] = self._path_combobox.GetStrings()
  794. self._options_frame.save_all_options()
  795. self.opt_manager.save_to_file()
  796. self.Destroy()
  797. class ListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
  798. """Custom ListCtrl widget.
  799. Args:
  800. columns (dict): See MainFrame class STATUSLIST_COLUMNS attribute.
  801. """
  802. def __init__(self, columns, *args, **kwargs):
  803. super(ListCtrl, self).__init__(*args, **kwargs)
  804. ListCtrlAutoWidthMixin.__init__(self)
  805. self.columns = columns
  806. self._list_index = 0
  807. self._url_list = set()
  808. self._set_columns()
  809. def remove_row(self, row_number):
  810. self.DeleteItem(row_number)
  811. self._list_index -= 1
  812. def move_item_up(self, row_number):
  813. self._move_item(row_number, row_number - 1)
  814. def move_item_down(self, row_number):
  815. self._move_item(row_number, row_number + 1)
  816. def _move_item(self, cur_row, new_row):
  817. self.Freeze()
  818. item = self.GetItem(cur_row)
  819. self.DeleteItem(cur_row)
  820. item.SetId(new_row)
  821. self.InsertItem(item)
  822. self.Select(new_row)
  823. self.Thaw()
  824. def has_url(self, url):
  825. """Returns True if the url is aleady in the ListCtrl else False.
  826. Args:
  827. url (string): URL string.
  828. """
  829. return url in self._url_list
  830. def bind_item(self, download_item):
  831. self.InsertStringItem(self._list_index, download_item.url)
  832. self.SetItemData(self._list_index, download_item.object_id)
  833. self._update_from_item(self._list_index, download_item)
  834. self._list_index += 1
  835. def _update_from_item(self, row, download_item):
  836. progress_stats = download_item.progress_stats
  837. for key in self.columns:
  838. column = self.columns[key][0]
  839. if key == "status" and progress_stats["playlist_index"]:
  840. # Not the best place but we build the playlist status here
  841. status = "{0} {1}/{2}".format(progress_stats["status"],
  842. progress_stats["playlist_index"],
  843. progress_stats["playlist_size"])
  844. self.SetStringItem(row, column, status)
  845. else:
  846. self.SetStringItem(row, column, progress_stats[key])
  847. def clear(self):
  848. """Clear the ListCtrl widget & reset self._list_index and
  849. self._url_list. """
  850. self.DeleteAllItems()
  851. self._list_index = 0
  852. self._url_list = set()
  853. def is_empty(self):
  854. """Returns True if the list is empty else False. """
  855. return self._list_index == 0
  856. def get_selected(self):
  857. return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
  858. def get_all_selected(self):
  859. return [index for index in xrange(self._list_index) if self.IsSelected(index)]
  860. def deselect_all(self):
  861. for index in xrange(self._list_index):
  862. self.Select(index, on=0)
  863. def get_next_selected(self, start=-1, reverse=False):
  864. if start == -1:
  865. start = self._list_index - 1 if reverse else 0
  866. else:
  867. # start from next item
  868. if reverse:
  869. start -= 1
  870. else:
  871. start += 1
  872. end = -1 if reverse else self._list_index
  873. step = -1 if reverse else 1
  874. for index in xrange(start, end, step):
  875. if self.IsSelected(index):
  876. return index
  877. return -1
  878. def _set_columns(self):
  879. """Initializes ListCtrl columns.
  880. See MainFrame STATUSLIST_COLUMNS attribute for more info. """
  881. for column_item in sorted(self.columns.values()):
  882. self.InsertColumn(column_item[0], column_item[1], width=wx.LIST_AUTOSIZE_USEHEADER)
  883. # If the column width obtained from wxLIST_AUTOSIZE_USEHEADER
  884. # is smaller than the minimum allowed column width
  885. # then set the column width to the minumum allowed size
  886. if self.GetColumnWidth(column_item[0]) < column_item[2]:
  887. self.SetColumnWidth(column_item[0], column_item[2])
  888. # Set auto-resize if enabled
  889. if column_item[3]:
  890. self.setResizeColumn(column_item[0])
  891. # REFACTOR Extra widgets below should move to other module with widgets
  892. class ExtComboBox(wx.ComboBox):
  893. def __init__(self, parent, max_items=-1, *args, **kwargs):
  894. super(ExtComboBox, self).__init__(parent, *args, **kwargs)
  895. assert max_items > 0 or max_items == -1
  896. self.max_items = max_items
  897. def Append(self, new_value):
  898. if self.FindString(new_value) == wx.NOT_FOUND:
  899. super(ExtComboBox, self).Append(new_value)
  900. if self.max_items != -1 and self.GetCount() > self.max_items:
  901. self.SetItems(self.GetStrings()[1:])
  902. def SetValue(self, new_value):
  903. if self.FindString(new_value) == wx.NOT_FOUND:
  904. self.Append(new_value)
  905. self.SetSelection(self.FindString(new_value))
  906. def LoadMultiple(self, items_list):
  907. for item in items_list:
  908. self.Append(item)
  909. class DoubleStageButton(wx.Button):
  910. def __init__(self, parent, labels, bitmaps, bitmap_pos=wx.TOP, *args, **kwargs):
  911. super(DoubleStageButton, self).__init__(parent, *args, **kwargs)
  912. assert isinstance(labels, tuple) and isinstance(bitmaps, tuple)
  913. assert len(labels) == 2
  914. assert len(bitmaps) == 0 or len(bitmaps) == 2
  915. self.labels = labels
  916. self.bitmaps = bitmaps
  917. self.bitmap_pos = bitmap_pos
  918. self._stage = 0
  919. self._set_layout()
  920. def _set_layout(self):
  921. self.SetLabel(self.labels[self._stage])
  922. if len(self.bitmaps):
  923. self.SetBitmap(self.bitmaps[self._stage], self.bitmap_pos)
  924. def change_stage(self):
  925. self._stage = 0 if self._stage else 1
  926. self._set_layout()
  927. def set_stage(self, new_stage):
  928. assert new_stage == 0 or new_stage == 1
  929. self._stage = new_stage
  930. self._set_layout()
  931. class ButtonsChoiceDialog(wx.Dialog):
  932. if os.name == "nt":
  933. STYLE = wx.DEFAULT_DIALOG_STYLE
  934. else:
  935. STYLE = wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX
  936. BORDER = 10
  937. def __init__(self, parent, choices, message, *args, **kwargs):
  938. super(ButtonsChoiceDialog, self).__init__(parent, wx.ID_ANY, *args, style=self.STYLE, **kwargs)
  939. buttons = []
  940. # Create components
  941. panel = wx.Panel(self)
  942. info_bmp = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_MESSAGE_BOX)
  943. info_icon = wx.StaticBitmap(panel, wx.ID_ANY, info_bmp)
  944. msg_text = wx.StaticText(panel, wx.ID_ANY, message)
  945. buttons.append(wx.Button(panel, wx.ID_CANCEL, "Cancel"))
  946. for index, label in enumerate(choices):
  947. buttons.append(wx.Button(panel, index + 1, label))
  948. # Get the maximum button width & height
  949. max_width = max_height = -1
  950. for button in buttons:
  951. button_width, button_height = button.GetSize()
  952. if button_width > max_width:
  953. max_width = button_width
  954. if button_height > max_height:
  955. max_height = button_height
  956. max_width += 10
  957. # Set buttons width & bind events
  958. for button in buttons:
  959. if button != buttons[0]:
  960. button.SetMinSize((max_width, max_height))
  961. else:
  962. # On Close button change only the height
  963. button.SetMinSize((-1, max_height))
  964. button.Bind(wx.EVT_BUTTON, self._on_close)
  965. # Set sizers
  966. vertical_sizer = wx.BoxSizer(wx.VERTICAL)
  967. message_sizer = wx.BoxSizer(wx.HORIZONTAL)
  968. message_sizer.Add(info_icon)
  969. message_sizer.AddSpacer((10, 10))
  970. message_sizer.Add(msg_text, flag=wx.EXPAND)
  971. vertical_sizer.Add(message_sizer, 1, wx.ALL, border=self.BORDER)
  972. buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
  973. for button in buttons[1:]:
  974. buttons_sizer.Add(button)
  975. buttons_sizer.AddSpacer((5, -1))
  976. buttons_sizer.AddSpacer((-1, -1), 1)
  977. buttons_sizer.Add(buttons[0], flag=wx.ALIGN_RIGHT)
  978. vertical_sizer.Add(buttons_sizer, flag=wx.EXPAND | wx.ALL, border=self.BORDER)
  979. panel.SetSizer(vertical_sizer)
  980. width, height = panel.GetBestSize()
  981. self.SetSize((width, height * 1.3))
  982. self.Center()
  983. def _on_close(self, event):
  984. self.EndModal(event.GetEventObject().GetId())
  985. class ButtonsGroup(object):
  986. WIDTH = 0
  987. HEIGHT = 1
  988. def __init__(self, buttons_list=None, squared=False):
  989. if buttons_list is None:
  990. self._buttons_list = []
  991. else:
  992. self._buttons_list = buttons_list
  993. self._squared = squared
  994. def set_size(self, size):
  995. assert len(size) == 2
  996. width, height = size
  997. if width == -1:
  998. for button in self._buttons_list:
  999. cur_width = button.GetSize()[self.WIDTH]
  1000. if cur_width > width:
  1001. width = cur_width
  1002. if height == -1:
  1003. for button in self._buttons_list:
  1004. cur_height = button.GetSize()[self.HEIGHT]
  1005. if cur_height > height:
  1006. height = cur_height
  1007. if self._squared:
  1008. width = height = (width if width > height else height)
  1009. for button in self._buttons_list:
  1010. button.SetMinSize((width, height))
  1011. def create_sizer(self, orient=wx.HORIZONTAL, space=-1):
  1012. box_sizer = wx.BoxSizer(orient)
  1013. for button in self._buttons_list:
  1014. box_sizer.Add(button)
  1015. if space != -1:
  1016. box_sizer.AddSpacer((space, space))
  1017. return box_sizer
  1018. def bind_event(self, event, event_handler):
  1019. for button in self._buttons_list:
  1020. button.Bind(event, event_handler)
  1021. def disable_all(self):
  1022. for button in self._buttons_list:
  1023. button.Enable(False)
  1024. def enable_all(self):
  1025. for button in self._buttons_list:
  1026. button.Enable(True)
  1027. def add(self, button):
  1028. self._buttons_list.append(button)
  1029. class ShutdownDialog(wx.Dialog):
  1030. if os.name == "nt":
  1031. STYLE = wx.DEFAULT_DIALOG_STYLE
  1032. else:
  1033. STYLE = wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX
  1034. TIMER_INTERVAL = 1000 # milliseconds
  1035. BORDER = 10
  1036. def __init__(self, parent, timeout, message, *args, **kwargs):
  1037. super(ShutdownDialog, self).__init__(parent, wx.ID_ANY, *args, style=self.STYLE, **kwargs)
  1038. assert timeout > 0
  1039. self.timeout = timeout
  1040. self.message = message
  1041. # Create components
  1042. panel = wx.Panel(self)
  1043. info_bmp = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_MESSAGE_BOX)
  1044. info_icon = wx.StaticBitmap(panel, wx.ID_ANY, info_bmp)
  1045. self.msg_text = msg_text = wx.StaticText(panel, wx.ID_ANY, self._get_message())
  1046. ok_button = wx.Button(panel, wx.ID_OK, "OK")
  1047. cancel_button = wx.Button(panel, wx.ID_CANCEL, "Cancel")
  1048. # Set layout
  1049. vertical_sizer = wx.BoxSizer(wx.VERTICAL)
  1050. message_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1051. message_sizer.Add(info_icon)
  1052. message_sizer.AddSpacer((10, 10))
  1053. message_sizer.Add(msg_text, flag=wx.EXPAND)
  1054. vertical_sizer.Add(message_sizer, 1, wx.ALL, border=self.BORDER)
  1055. buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1056. buttons_sizer.Add(ok_button)
  1057. buttons_sizer.AddSpacer((5, -1))
  1058. buttons_sizer.Add(cancel_button)
  1059. vertical_sizer.Add(buttons_sizer, flag=wx.ALIGN_RIGHT | wx.ALL, border=self.BORDER)
  1060. panel.SetSizer(vertical_sizer)
  1061. width, height = panel.GetBestSize()
  1062. self.SetSize((width * 1.3, height * 1.3))
  1063. self.Center()
  1064. # Set up timer
  1065. self.timer = wx.Timer(self)
  1066. self.Bind(wx.EVT_TIMER, self._on_timer, self.timer)
  1067. self.timer.Start(self.TIMER_INTERVAL)
  1068. def _get_message(self):
  1069. return self.message.format(self.timeout)
  1070. def _on_timer(self, event):
  1071. self.timeout -= 1
  1072. self.msg_text.SetLabel(self._get_message())
  1073. if self.timeout <= 0:
  1074. self.EndModal(wx.ID_OK)
  1075. def Destroy(self):
  1076. self.timer.Stop()
  1077. return super(ShutdownDialog, self).Destroy()