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.

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