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.

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