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.

1192 lines
41 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
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
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
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
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
  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_config_path,
  31. get_icon_file,
  32. shutdown_sys,
  33. read_formats,
  34. remove_file,
  35. json_store,
  36. json_load,
  37. to_string,
  38. open_file,
  39. get_time
  40. )
  41. from .info import (
  42. __descriptionfull__,
  43. __licensefull__,
  44. __projecturl__,
  45. __appname__,
  46. __author__
  47. )
  48. from .version import __version__
  49. class MainFrame(wx.Frame):
  50. """Main window class.
  51. This class is responsible for creating the main app window
  52. and binding the events.
  53. Attributes:
  54. wxEVT_TEXT_PASTE (int): Event type code for the wx.EVT_TEXT_PASTE
  55. BUTTONS_SIZE (tuple): Buttons size (width, height).
  56. BUTTONS_SPACE (tuple): Space between buttons (width, height).
  57. SIZE_20 (int): Constant size number.
  58. SIZE_10 (int): Constant size number.
  59. SIZE_5 (int): Constant size number.
  60. Labels area (strings): Strings for the widgets labels.
  61. STATUSLIST_COLUMNS (dict): Python dictionary which holds informations
  62. about the wxListCtrl columns. For more informations read the
  63. comments above the STATUSLIST_COLUMNS declaration.
  64. Args:
  65. opt_manager (optionsmanager.OptionsManager): Object responsible for
  66. handling the settings.
  67. log_manager (logmanager.LogManager): Object responsible for handling
  68. the log stuff.
  69. parent (wx.Window): Frame parent.
  70. """
  71. wxEVT_TEXT_PASTE = 'wxClipboardTextEvent'
  72. FRAMES_MIN_SIZE = (440, 360)
  73. BUTTONS_SIZE = (-1, 30) # REFACTOR remove not used anymore
  74. BUTTONS_SPACE = (80, -1) # REFACTOR remove not used anymore
  75. SIZE_20 = 20 # REFACTOR write directly
  76. SIZE_10 = 10
  77. SIZE_5 = 5
  78. # Labels area
  79. URLS_LABEL = _("Enter URLs below")
  80. DOWNLOAD_LABEL = _("Download") # REFACTOR remove not used anymore
  81. UPDATE_LABEL = _("Update")
  82. OPTIONS_LABEL = _("Options")
  83. ERROR_LABEL = _("Error")
  84. STOP_LABEL = _("Stop")
  85. INFO_LABEL = _("Info")
  86. WELCOME_MSG = _("Welcome")
  87. ADD_LABEL = _("Add")
  88. DOWNLOAD_LIST_LABEL = _("Download list")
  89. DELETE_LABEL = _("Delete")
  90. PLAY_LABEL = _("Play")
  91. UP_LABEL = _("Up")
  92. DOWN_LABEL = _("Down")
  93. RELOAD_LABEL = _("Reload")
  94. PAUSE_LABEL = _("Pause")
  95. START_LABEL = _("Start")
  96. ABOUT_LABEL = _("About")
  97. VIEWLOG_LABEL = _("View Log")
  98. SUCC_REPORT_MSG = _("Successfully downloaded {0} url(s) in {1} "
  99. "day(s) {2} hour(s) {3} minute(s) {4} second(s)")
  100. DL_COMPLETED_MSG = _("Downloads completed")
  101. URL_REPORT_MSG = _("Total Progress: {0:.1f}% | Queued ({1}) Paused ({2}) Active ({3}) Completed ({4})")
  102. CLOSING_MSG = _("Stopping downloads")
  103. CLOSED_MSG = _("Downloads stopped")
  104. PROVIDE_URL_MSG = _("You need to provide at least one url")
  105. DOWNLOAD_STARTED = _("Downloads started")
  106. CHOOSE_DIRECTORY = _("Choose Directory")
  107. DOWNLOAD_ACTIVE = _("Download in progress. Please wait for all the downloads to complete")
  108. UPDATE_ACTIVE = _("Update already in progress.")
  109. UPDATING_MSG = _("Downloading latest youtube-dl. Please wait...")
  110. UPDATE_ERR_MSG = _("Youtube-dl download failed [{0}]")
  111. UPDATE_SUCC_MSG = _("Youtube-dl downloaded correctly")
  112. OPEN_DIR_ERR = _("Unable to open directory: '{dir}'. "
  113. "The specified path does not exist")
  114. SHUTDOWN_ERR = _("Error while shutting down. "
  115. "Make sure you typed the correct password")
  116. SHUTDOWN_MSG = _("Shutting down system")
  117. VIDEO_LABEL = _("Title")
  118. EXTENSION_LABEL = _("Extension")
  119. SIZE_LABEL = _("Size")
  120. PERCENT_LABEL = _("Percent")
  121. ETA_LABEL = _("ETA")
  122. SPEED_LABEL = _("Speed")
  123. STATUS_LABEL = _("Status")
  124. #################################
  125. # STATUSLIST_COLUMNS
  126. #
  127. # Dictionary which contains the columns for the wxListCtrl widget.
  128. # Each key represents a column and holds informations about itself.
  129. # Structure informations:
  130. # column_key: (column_number, column_label, minimum_width, is_resizable)
  131. #
  132. STATUSLIST_COLUMNS = {
  133. 'filename': (0, VIDEO_LABEL, 150, True),
  134. 'extension': (1, EXTENSION_LABEL, 60, False),
  135. 'filesize': (2, SIZE_LABEL, 80, False),
  136. 'percent': (3, PERCENT_LABEL, 65, False),
  137. 'eta': (4, ETA_LABEL, 45, False),
  138. 'speed': (5, SPEED_LABEL, 90, False),
  139. 'status': (6, STATUS_LABEL, 160, False)
  140. }
  141. def __init__(self, opt_manager, log_manager, parent=None):
  142. wx.Frame.__init__(self, parent, title=__appname__, size=opt_manager.options['main_win_size'])
  143. self.opt_manager = opt_manager
  144. self.log_manager = log_manager
  145. self.download_manager = None
  146. self.update_thread = None
  147. self.app_icon = None
  148. self._download_list = DownloadList()
  149. # Set up youtube-dl options parser
  150. self._options_parser = OptionsParser()
  151. # Get the pixmaps directory
  152. self._pixmaps_path = get_pixmaps_dir()
  153. # Get video formats
  154. self._video_formats = read_formats()
  155. # Set the Timer
  156. self._app_timer = wx.Timer(self)
  157. # Set the app icon
  158. app_icon_path = get_icon_file()
  159. if app_icon_path is not None:
  160. self.app_icon = wx.Icon(app_icon_path, wx.BITMAP_TYPE_PNG)
  161. self.SetIcon(self.app_icon)
  162. # Set the data for all the wx.Button items
  163. # name, label, icon, size, event_handler
  164. buttons_data = (
  165. ("delete", self.DELETE_LABEL, "delete_32px.png", (55, 55), self._on_delete),
  166. ("play", self.PLAY_LABEL, "camera_32px.png", (55, 55), self._on_play),
  167. ("up", self.UP_LABEL, "arrow_up_32px.png", (55, 55), self._on_arrow_up),
  168. ("down", self.DOWN_LABEL, "arrow_down_32px.png", (55, 55), self._on_arrow_down),
  169. ("reload", self.RELOAD_LABEL, "reload_32px.png", (55, 55), self._on_reload),
  170. ("pause", self.PAUSE_LABEL, "pause_32px.png", (55, 55), self._on_pause),
  171. ("start", self.START_LABEL, "cloud_download_32px.png", (55, 55), self._on_start),
  172. ("savepath", "...", None, (40, 27), self._on_savepath),
  173. ("add", self.ADD_LABEL, None, (-1, -1), self._on_add)
  174. )
  175. # Set the data for the settings menu item
  176. # label, event_handler
  177. settings_menu_data = (
  178. (self.OPTIONS_LABEL, self._on_options),
  179. (self.UPDATE_LABEL, self._on_update),
  180. (self.VIEWLOG_LABEL, self._on_viewlog),
  181. (self.ABOUT_LABEL, self._on_about)
  182. )
  183. statuslist_menu_data = (
  184. (_("Get url"), self._on_geturl),
  185. (_("Get command"), self._on_getcmd)
  186. )
  187. # Create options frame
  188. self._options_frame = OptionsFrame(self)
  189. # Create frame components
  190. self._panel = wx.Panel(self)
  191. self._url_text = self._create_statictext(self.URLS_LABEL)
  192. self._settings_button = self._create_bitmap_button("settings_20px.png", (30, 30), self._on_settings)
  193. self._url_list = self._create_textctrl(wx.TE_MULTILINE | wx.TE_DONTWRAP, self._on_urllist_edit)
  194. self._folder_icon = self._create_static_bitmap("folder_32px.png")
  195. self._path_combobox = ExtComboBox(self._panel, 5, style=wx.CB_READONLY)
  196. self._videoformat_combobox = ExtComboBox(self._panel, choices=self._video_formats.values(), style=wx.CB_READONLY)
  197. self._download_text = self._create_statictext(self.DOWNLOAD_LIST_LABEL)
  198. self._status_list = ListCtrl(self.STATUSLIST_COLUMNS,
  199. parent=self._panel,
  200. style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES | wx.LC_SINGLE_SEL)
  201. # Dictionary to store all the buttons
  202. self._buttons = {}
  203. for item in buttons_data:
  204. name, label, icon, size, evt_handler = item
  205. button = wx.Button(self._panel, label=label, size=size)
  206. if icon is not None:
  207. button.SetBitmap(wx.Bitmap(os.path.join(self._pixmaps_path, icon)), wx.TOP)
  208. if evt_handler is not None:
  209. button.Bind(wx.EVT_BUTTON, evt_handler)
  210. self._buttons[name] = button
  211. self._status_bar = self.CreateStatusBar()
  212. # Create extra components
  213. self._settings_menu = self._create_menu_item(settings_menu_data)
  214. self._statuslist_menu = self._create_menu_item(statuslist_menu_data)
  215. # Bind extra events
  216. self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._on_statuslist_right_click, self._status_list)
  217. self.Bind(wx.EVT_TEXT, self._update_videoformat, self._videoformat_combobox)
  218. self.Bind(wx.EVT_TEXT, self._update_savepath, self._path_combobox)
  219. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._update_pause_button, self._status_list)
  220. self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._update_pause_button, self._status_list)
  221. self.Bind(wx.EVT_CLOSE, self._on_close)
  222. self.Bind(wx.EVT_TIMER, self._on_timer, self._app_timer)
  223. # Set threads wxCallAfter handlers
  224. self._set_publisher(self._update_handler, UPDATE_PUB_TOPIC)
  225. self._set_publisher(self._download_worker_handler, WORKER_PUB_TOPIC)
  226. self._set_publisher(self._download_manager_handler, MANAGER_PUB_TOPIC)
  227. # Set up extra stuff
  228. self.Center()
  229. self.SetMinSize(self.FRAMES_MIN_SIZE)
  230. self._videoformat_combobox.SetMaxSize((210 ,-1))
  231. self._set_buttons_width()
  232. self._status_bar_write(self.WELCOME_MSG)
  233. self._videoformat_combobox.SetValue(self._video_formats[self.opt_manager.options["video_format"]])
  234. self._path_combobox.LoadMultiple(self.opt_manager.options["save_path_dirs"])
  235. self._path_combobox.SetValue(self.opt_manager.options["save_path"])
  236. self._set_layout()
  237. def _create_menu_item(self, items):
  238. menu = wx.Menu()
  239. for item in items:
  240. label, evt_handler = item
  241. menu_item = menu.Append(-1, label)
  242. menu.Bind(wx.EVT_MENU, evt_handler, menu_item)
  243. # Overwrite the hover event to avoid changing the statusbar
  244. menu.Bind(wx.EVT_MENU_HIGHLIGHT, lambda event: None)
  245. return menu
  246. def _on_statuslist_right_click(self, event):
  247. selected = self._status_list.get_selected()
  248. if selected != -1:
  249. self.PopupMenu(self._statuslist_menu)
  250. def _on_geturl(self, event):
  251. selected = self._status_list.get_selected()
  252. if selected != -1:
  253. object_id = self._status_list.GetItemData(selected)
  254. download_item = self._download_list.get_item(object_id)
  255. url = download_item.url
  256. if not wx.TheClipboard.IsOpened():
  257. clipdata = wx.TextDataObject()
  258. clipdata.SetText(url)
  259. wx.TheClipboard.Open()
  260. wx.TheClipboard.SetData(clipdata)
  261. wx.TheClipboard.Close()
  262. def _on_getcmd(self, event):
  263. selected = self._status_list.get_selected()
  264. if selected != -1:
  265. object_id = self._status_list.GetItemData(selected)
  266. download_item = self._download_list.get_item(object_id)
  267. cmd = [YOUTUBEDL_BIN] + download_item.options + [download_item.url]
  268. cmd = " ".join(cmd)
  269. if not wx.TheClipboard.IsOpened():
  270. clipdata = wx.TextDataObject()
  271. clipdata.SetText(cmd)
  272. wx.TheClipboard.Open()
  273. wx.TheClipboard.SetData(clipdata)
  274. wx.TheClipboard.Close()
  275. def _on_timer(self, event):
  276. total_percentage = 0.0
  277. queued = paused = active = completed = 0
  278. for item in self._download_list.get_items():
  279. if item.stage == "Queued":
  280. queued += 1
  281. if item.stage == "Paused":
  282. paused += 1
  283. if item.stage == "Active":
  284. active += 1
  285. total_percentage += float(item.progress_stats["percent"].split('%')[0])
  286. if item.stage == "Completed":
  287. completed += 1
  288. # TODO Store percentage as float in the DownloadItem?
  289. # TODO DownloadList keep track for each item stage?
  290. # TODO Should i count the paused items?
  291. # total_percentage += queued * 0.0% + paused * 0.0% + completed * 100.0%
  292. total_percentage += completed * 100.0
  293. total_percentage /= len(self._download_list)
  294. msg = self.URL_REPORT_MSG.format(total_percentage, queued, paused, active, completed)
  295. self._status_bar_write(msg)
  296. def _update_pause_button(self, event):
  297. # REFACTOR keep all icons in a data stracture instead of creating them each time
  298. pause_icon = wx.Bitmap(os.path.join(self._pixmaps_path, "pause_32px.png"))
  299. resume_icon = wx.Bitmap(os.path.join(self._pixmaps_path, "play_arrow_32px.png"))
  300. selected_row = self._status_list.get_selected()
  301. if selected_row != -1:
  302. object_id = self._status_list.GetItemData(selected_row)
  303. download_item = self._download_list.get_item(object_id)
  304. if download_item.stage == "Paused":
  305. self._buttons["pause"].SetLabel("Resume")
  306. self._buttons["pause"].SetBitmap(resume_icon, wx.TOP)
  307. elif download_item.stage == "Queued":
  308. self._buttons["pause"].SetLabel("Pause")
  309. self._buttons["pause"].SetBitmap(pause_icon, wx.TOP)
  310. else:
  311. if self._buttons["pause"].GetLabel() == "Resume":
  312. self._buttons["pause"].SetLabel("Pause")
  313. self._buttons["pause"].SetBitmap(pause_icon, wx.TOP)
  314. def _update_videoformat(self, event):
  315. self.opt_manager.options["video_format"] = self._video_formats[self._videoformat_combobox.GetValue()]
  316. def _update_savepath(self, event):
  317. self.opt_manager.options["save_path"] = self._path_combobox.GetValue()
  318. def _on_delete(self, event):
  319. selected_row = self._status_list.get_selected()
  320. if selected_row == -1:
  321. self._create_popup("No row selected", self.ERROR_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  322. else:
  323. object_id = self._status_list.GetItemData(selected_row)
  324. selected_download_item = self._download_list.get_item(object_id)
  325. if selected_download_item.stage == "Active":
  326. self._create_popup("Selected item is active. Cannot remove", self.ERROR_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  327. else:
  328. if selected_download_item.stage == "Completed":
  329. dlg = wx.MessageDialog(self, "Do you want to remove the files associated with this item?", "Remove files", wx.YES_NO | wx.ICON_QUESTION)
  330. result = dlg.ShowModal() == wx.ID_YES
  331. dlg.Destroy()
  332. if result:
  333. for cur_file in selected_download_item.get_files():
  334. remove_file(cur_file)
  335. self._status_list.remove_row(selected_row)
  336. self._download_list.remove(object_id)
  337. def _on_play(self, event):
  338. selected_row = self._status_list.get_selected()
  339. if selected_row == -1:
  340. self._create_popup("No row selected", self.ERROR_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  341. else:
  342. object_id = self._status_list.GetItemData(selected_row)
  343. selected_download_item = self._download_list.get_item(object_id)
  344. if selected_download_item.stage == "Completed":
  345. if selected_download_item.filenames:
  346. filename = selected_download_item.get_files()[-1]
  347. open_file(filename)
  348. else:
  349. self._create_popup("Item is not completed", self.INFO_LABEL, wx.OK | wx.ICON_INFORMATION)
  350. def _on_arrow_up(self, event):
  351. selected_row = self._status_list.get_selected()
  352. if selected_row == -1:
  353. self._create_popup("No row selected", self.ERROR_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  354. else:
  355. object_id = self._status_list.GetItemData(selected_row)
  356. download_item = self._download_list.get_item(object_id)
  357. if self._download_list.move_up(object_id):
  358. self._status_list.move_item_up(selected_row)
  359. self._status_list._update_from_item(selected_row - 1, download_item)
  360. print self._download_list._items_list
  361. def _on_arrow_down(self, event):
  362. selected_row = self._status_list.get_selected()
  363. if selected_row == -1:
  364. self._create_popup("No row selected", self.ERROR_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  365. else:
  366. object_id = self._status_list.GetItemData(selected_row)
  367. download_item = self._download_list.get_item(object_id)
  368. if self._download_list.move_down(object_id):
  369. self._status_list.move_item_down(selected_row)
  370. self._status_list._update_from_item(selected_row + 1, download_item)
  371. print self._download_list._items_list
  372. def _on_reload(self, event):
  373. for index, item in enumerate(self._download_list.get_items()):
  374. if item.stage == "Paused" or item.stage == "Completed":
  375. item.reset()
  376. self._status_list._update_from_item(index, item)
  377. # Create deselect event to reset Pause button
  378. selected_row = self._status_list.get_selected()
  379. if selected_row != -1:
  380. self._status_list.Select(selected_row, 0)
  381. def _on_pause(self, event):
  382. selected_row = self._status_list.get_selected()
  383. if selected_row == -1:
  384. self._create_popup("No row selected", self.ERROR_LABEL, wx.OK | wx.ICON_EXCLAMATION)
  385. else:
  386. object_id = self._status_list.GetItemData(selected_row)
  387. download_item = self._download_list.get_item(object_id)
  388. if download_item.stage == "Queued":
  389. self._download_list.change_stage(object_id, "Paused")
  390. elif download_item.stage == "Paused":
  391. self._download_list.change_stage(object_id, "Queued")
  392. self._update_pause_button(None)
  393. self._status_list._update_from_item(selected_row, download_item)
  394. def _on_start(self, event):
  395. if self.download_manager is None:
  396. self._start_download()
  397. else:
  398. self.download_manager.stop_downloads()
  399. def _on_savepath(self, event):
  400. dlg = wx.DirDialog(self, self.CHOOSE_DIRECTORY, self._path_combobox.GetStringSelection(), wx.DD_CHANGE_DIR)
  401. if dlg.ShowModal() == wx.ID_OK:
  402. path = dlg.GetPath()
  403. self._path_combobox.Append(path)
  404. self._path_combobox.SetValue(path)
  405. self._update_savepath(None)
  406. dlg.Destroy()
  407. def _on_add(self, event):
  408. urls = self._get_urls()
  409. if not urls:
  410. self._create_popup(self.PROVIDE_URL_MSG,
  411. self.ERROR_LABEL,
  412. wx.OK | wx.ICON_EXCLAMATION)
  413. else:
  414. self._url_list.Clear()
  415. options = self._options_parser.parse(self.opt_manager.options)
  416. for url in urls:
  417. download_item = DownloadItem(url, options)
  418. if not self._download_list.has_item(download_item.object_id):
  419. self._status_list.bind_item(download_item)
  420. self._download_list.insert(download_item)
  421. def _on_settings(self, event):
  422. event_object_pos = event.EventObject.GetPosition()
  423. # Update the object +30 on Y axis to make the menu look like it belongs to the button
  424. event_object_pos = (event_object_pos[0], event_object_pos[1] + 30)
  425. self.PopupMenu(self._settings_menu, event_object_pos)
  426. def _on_viewlog(self, event):
  427. log_window = LogGUI(self)
  428. log_window.load(self.log_manager.log_file)
  429. log_window.Show()
  430. def _on_about(self, event):
  431. info = wx.AboutDialogInfo()
  432. if self.app_icon is not None:
  433. info.SetIcon(self.app_icon)
  434. info.SetName(__appname__)
  435. info.SetVersion(__version__)
  436. info.SetDescription(__descriptionfull__)
  437. info.SetWebSite(__projecturl__)
  438. info.SetLicense(__licensefull__)
  439. info.AddDeveloper(__author__)
  440. wx.AboutBox(info)
  441. def _set_publisher(self, handler, topic):
  442. """Sets a handler for the given topic.
  443. Args:
  444. handler (function): Can be any function with one parameter
  445. the message that the caller sends.
  446. topic (string): Can be any string that identifies the caller.
  447. You can bind multiple handlers on the same topic or
  448. multiple topics on the same handler.
  449. """
  450. Publisher.subscribe(handler, topic)
  451. def _set_buttons_width(self):
  452. """Re-adjust buttons size on runtime so that all buttons
  453. look the same. """
  454. widths = [
  455. #self._download_btn.GetSize()[0],
  456. #self._update_btn.GetSize()[0],
  457. #self._options_btn.GetSize()[0],
  458. ]
  459. max_width = -1
  460. for item in widths:
  461. if item > max_width:
  462. max_width = item
  463. #self._download_btn.SetMinSize((max_width, self.BUTTONS_SIZE[1]))
  464. #self._update_btn.SetMinSize((max_width, self.BUTTONS_SIZE[1]))
  465. #self._options_btn.SetMinSize((max_width, self.BUTTONS_SIZE[1]))
  466. self._panel.Layout()
  467. def _create_statictext(self, label):
  468. return wx.StaticText(self._panel, label=label)
  469. def _create_bitmap_button(self, icon, size=(-1, -1), handler=None):
  470. bitmap = wx.Bitmap(os.path.join(self._pixmaps_path, icon))
  471. button = wx.BitmapButton(self._panel, bitmap=bitmap, size=size, style=wx.NO_BORDER)
  472. if handler is not None:
  473. button.Bind(wx.EVT_BUTTON, handler)
  474. return button
  475. def _create_static_bitmap(self, icon):
  476. bitmap = wx.Bitmap(os.path.join(self._pixmaps_path, icon))
  477. return wx.StaticBitmap(self._panel, bitmap=bitmap)
  478. def _create_textctrl(self, style=None, event_handler=None):
  479. if style is None:
  480. textctrl = wx.TextCtrl(self._panel)
  481. else:
  482. textctrl = wx.TextCtrl(self._panel, style=style)
  483. if event_handler is not None:
  484. textctrl.Bind(wx.EVT_TEXT_PASTE, event_handler)
  485. textctrl.Bind(wx.EVT_MIDDLE_DOWN, event_handler)
  486. if os.name == 'nt':
  487. # Enable CTRL+A on Windows
  488. def win_ctrla_eventhandler(event):
  489. if event.GetKeyCode() == wx.WXK_CONTROL_A:
  490. event.GetEventObject().SelectAll()
  491. event.Skip()
  492. textctrl.Bind(wx.EVT_CHAR, win_ctrla_eventhandler)
  493. return textctrl
  494. def _create_button(self, label, event_handler=None):
  495. # REFACTOR remove not used anymore
  496. btn = wx.Button(self._panel, label=label, size=self.BUTTONS_SIZE)
  497. if event_handler is not None:
  498. btn.Bind(wx.EVT_BUTTON, event_handler)
  499. return btn
  500. def _create_popup(self, text, title, style):
  501. wx.MessageBox(text, title, style)
  502. def _set_layout(self):
  503. """Sets the layout of the main window. """
  504. main_sizer = wx.BoxSizer(wx.VERTICAL)
  505. panel_sizer = wx.BoxSizer(wx.VERTICAL)
  506. top_sizer = wx.BoxSizer(wx.HORIZONTAL)
  507. top_sizer.Add(self._url_text, 0, wx.ALIGN_BOTTOM | wx.BOTTOM, 5)
  508. top_sizer.AddSpacer((100, 20), 1)
  509. top_sizer.Add(self._settings_button, flag=wx.ALIGN_RIGHT)
  510. panel_sizer.Add(top_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
  511. panel_sizer.Add(self._url_list, 1, wx.EXPAND)
  512. mid_sizer = wx.BoxSizer(wx.HORIZONTAL)
  513. mid_sizer.Add(self._folder_icon)
  514. mid_sizer.Add(self._path_combobox, 2, wx.ALIGN_CENTER_VERTICAL)
  515. mid_sizer.Add(self._buttons["savepath"], flag=wx.ALIGN_CENTER_VERTICAL)
  516. mid_sizer.AddSpacer((10, 20), 1)
  517. mid_sizer.Add(self._videoformat_combobox, 1, wx.ALIGN_CENTER_VERTICAL)
  518. mid_sizer.Add(self._buttons["add"], flag=wx.ALIGN_CENTER_VERTICAL)
  519. panel_sizer.Add(mid_sizer, 0, wx.EXPAND | wx.ALL, 10)
  520. panel_sizer.Add(self._download_text, 0, wx.BOTTOM | wx.LEFT, 5)
  521. panel_sizer.Add(self._status_list, 2, wx.EXPAND)
  522. bottom_sizer = wx.BoxSizer(wx.HORIZONTAL)
  523. bottom_sizer.Add(self._buttons["delete"])
  524. bottom_sizer.Add(self._buttons["play"])
  525. bottom_sizer.Add(self._buttons["up"])
  526. bottom_sizer.Add(self._buttons["down"])
  527. bottom_sizer.Add(self._buttons["reload"])
  528. bottom_sizer.Add(self._buttons["pause"])
  529. bottom_sizer.AddSpacer((100, 20), 1)
  530. bottom_sizer.Add(self._buttons["start"])
  531. panel_sizer.Add(bottom_sizer, 0, wx.EXPAND | wx.TOP, 10)
  532. self._panel.SetSizer(panel_sizer)
  533. main_sizer.Add(self._panel, 1, wx.ALL | wx.EXPAND, 10)
  534. self.SetSizer(main_sizer)
  535. def _update_youtubedl(self):
  536. """Update youtube-dl binary to the latest version. """
  537. #self._update_btn.Disable()
  538. #self._download_btn.Disable()
  539. if self.download_manager is not None and self.download_manager.is_alive():
  540. self._create_popup(self.DOWNLOAD_ACTIVE,
  541. self.ERROR_LABEL,
  542. wx.OK | wx.ICON_EXCLAMATION)
  543. elif self.update_thread is not None and self.update_thread.is_alive():
  544. self._create_popup(self.UPDATE_ACTIVE,
  545. self.INFO_LABEL,
  546. wx.OK | wx.ICON_INFORMATION)
  547. else:
  548. self.update_thread = UpdateThread(self.opt_manager.options['youtubedl_path'])
  549. def _status_bar_write(self, msg):
  550. """Display msg in the status bar. """
  551. self._status_bar.SetStatusText(msg)
  552. def _reset_widgets(self):
  553. """Resets GUI widgets after update or download process. """
  554. self._buttons["start"].SetLabel("Start")
  555. icon = wx.Bitmap(os.path.join(self._pixmaps_path, "cloud_download_32px.png"))
  556. self._buttons["start"].SetBitmap(icon, wx.TOP)
  557. #self._download_btn.SetLabel(self.DOWNLOAD_LABEL)
  558. #self._download_btn.Enable()
  559. #self._update_btn.Enable()
  560. def _print_stats(self):
  561. """Display download stats in the status bar. """
  562. suc_downloads = self.download_manager.successful
  563. dtime = get_time(self.download_manager.time_it_took)
  564. msg = self.SUCC_REPORT_MSG.format(suc_downloads,
  565. dtime['days'],
  566. dtime['hours'],
  567. dtime['minutes'],
  568. dtime['seconds'])
  569. self._status_bar_write(msg)
  570. def _after_download(self):
  571. """Run tasks after download process has been completed.
  572. Note:
  573. Here you can add any tasks you want to run after the
  574. download process has been completed.
  575. """
  576. if self.opt_manager.options['shutdown']:
  577. self.opt_manager.save_to_file()
  578. success = shutdown_sys(self.opt_manager.options['sudo_password'])
  579. if success:
  580. self._status_bar_write(self.SHUTDOWN_MSG)
  581. else:
  582. self._status_bar_write(self.SHUTDOWN_ERR)
  583. else:
  584. self._create_popup(self.DL_COMPLETED_MSG, self.INFO_LABEL, wx.OK | wx.ICON_INFORMATION)
  585. if self.opt_manager.options['open_dl_dir']:
  586. success = open_file(self.opt_manager.options['save_path'])
  587. if not success:
  588. self._status_bar_write(self.OPEN_DIR_ERR.format(dir=self.opt_manager.options['save_path']))
  589. def _download_worker_handler(self, msg):
  590. """downloadmanager.Worker thread handler.
  591. Handles messages from the Worker thread.
  592. Args:
  593. See downloadmanager.Worker _talk_to_gui() method.
  594. """
  595. signal, data = msg.data
  596. download_item = self._download_list.get_item(data["index"])
  597. download_item.update_stats(data)
  598. row = self._download_list.index(data["index"])
  599. self._status_list._update_from_item(row, download_item)
  600. #if signal == 'send':
  601. #self._status_list.write(data)
  602. #if signal == 'receive':
  603. #self.download_manager.send_to_worker(self._status_list.get(data))
  604. def _download_manager_handler(self, msg):
  605. """downloadmanager.DownloadManager thread handler.
  606. Handles messages from the DownloadManager thread.
  607. Args:
  608. See downloadmanager.DownloadManager _talk_to_gui() method.
  609. """
  610. data = msg.data
  611. if data == 'finished':
  612. self._print_stats()
  613. self._reset_widgets()
  614. self.download_manager = None
  615. self._app_timer.Stop()
  616. self._after_download()
  617. elif data == 'closed':
  618. self._status_bar_write(self.CLOSED_MSG)
  619. self._reset_widgets()
  620. self.download_manager = None
  621. self._app_timer.Stop()
  622. elif data == 'closing':
  623. self._status_bar_write(self.CLOSING_MSG)
  624. elif data == 'report_active':
  625. pass
  626. def _update_handler(self, msg):
  627. """updatemanager.UpdateThread thread handler.
  628. Handles messages from the UpdateThread thread.
  629. Args:
  630. See updatemanager.UpdateThread _talk_to_gui() method.
  631. """
  632. data = msg.data
  633. if data[0] == 'download':
  634. self._status_bar_write(self.UPDATING_MSG)
  635. elif data[0] == 'error':
  636. self._status_bar_write(self.UPDATE_ERR_MSG.format(data[1]))
  637. elif data[0] == 'correct':
  638. self._status_bar_write(self.UPDATE_SUCC_MSG)
  639. else:
  640. self._reset_widgets()
  641. self.update_thread = None
  642. def _get_urls(self):
  643. """Returns urls list. """
  644. return [line for line in self._url_list.GetValue().split('\n') if line]
  645. def _start_download(self):
  646. if self._status_list.is_empty():
  647. self._create_popup("No items to download",
  648. self.ERROR_LABEL,
  649. wx.OK | wx.ICON_EXCLAMATION)
  650. else:
  651. self._app_timer.Start(100)
  652. self.download_manager = DownloadManager(self._download_list, self.opt_manager, self.log_manager)
  653. self._status_bar_write(self.DOWNLOAD_STARTED)
  654. self._buttons["start"].SetLabel(self.STOP_LABEL)
  655. icon = wx.Bitmap(os.path.join(self._pixmaps_path, "stop_32px.png"))
  656. self._buttons["start"].SetBitmap(icon, wx.TOP)
  657. def _paste_from_clipboard(self):
  658. """Paste the content of the clipboard to the self._url_list widget.
  659. It also adds a new line at the end of the data if not exist.
  660. """
  661. if not wx.TheClipboard.IsOpened():
  662. if wx.TheClipboard.Open():
  663. if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  664. data = wx.TextDataObject()
  665. wx.TheClipboard.GetData(data)
  666. data = data.GetText()
  667. if data[-1] != '\n':
  668. data += '\n'
  669. self._url_list.WriteText(data)
  670. wx.TheClipboard.Close()
  671. def _on_urllist_edit(self, event):
  672. """Event handler of the self._url_list widget.
  673. This method is triggered when the users pastes text into
  674. the URLs list either by using CTRL+V or by using the middle
  675. click of the mouse.
  676. """
  677. # REFACTOR Remove not used anymore
  678. if event.ClassName == self.wxEVT_TEXT_PASTE:
  679. self._paste_from_clipboard()
  680. else:
  681. wx.TheClipboard.UsePrimarySelection(True)
  682. self._paste_from_clipboard()
  683. wx.TheClipboard.UsePrimarySelection(False)
  684. # Dynamically add urls after download process has started
  685. if self.download_manager is not None:
  686. self._status_list.load_urls(self._get_urls(), self.download_manager.add_url)
  687. def _on_download(self, event):
  688. """Event handler of the self._download_btn widget.
  689. This method is used when the download-stop button is pressed to
  690. start or stop the download process.
  691. """
  692. if self.download_manager is None:
  693. self._start_download()
  694. else:
  695. self.download_manager.stop_downloads()
  696. def _on_update(self, event):
  697. """Event handler of the self._update_btn widget.
  698. This method is used when the update button is pressed to start
  699. the update process.
  700. Note:
  701. Currently there is not way to stop the update process.
  702. """
  703. self._update_youtubedl()
  704. def _on_options(self, event):
  705. """Event handler of the self._options_btn widget.
  706. This method is used when the options button is pressed to show
  707. the options window.
  708. """
  709. print "Have to adjust the options window first!!"
  710. #self._options_frame.load_all_options()
  711. #self._options_frame.Show()
  712. def _on_close(self, event):
  713. """Event handler for the wx.EVT_CLOSE event.
  714. This method is used when the user tries to close the program
  715. to save the options and make sure that the download & update
  716. processes are not running.
  717. """
  718. if self.download_manager is not None:
  719. self.download_manager.stop_downloads()
  720. self.download_manager.join()
  721. if self.update_thread is not None:
  722. self.update_thread.join()
  723. # Store main-options frame size
  724. self.opt_manager.options['main_win_size'] = self.GetSize()
  725. self.opt_manager.options['opts_win_size'] = self._options_frame.GetSize()
  726. self.opt_manager.options["save_path_dirs"] = self._path_combobox.GetStrings()
  727. #self._options_frame.save_all_options()
  728. self.opt_manager.save_to_file()
  729. self.Destroy()
  730. class ListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
  731. """Custom ListCtrl widget.
  732. Args:
  733. columns (dict): See MainFrame class STATUSLIST_COLUMNS attribute.
  734. """
  735. def __init__(self, columns, *args, **kwargs):
  736. wx.ListCtrl.__init__(self, *args, **kwargs)
  737. ListCtrlAutoWidthMixin.__init__(self)
  738. self.columns = columns
  739. self._list_index = 0
  740. self._url_list = set()
  741. self._set_columns()
  742. def get(self, data):
  743. """Return data from ListCtrl.
  744. Args:
  745. data (dict): Dictionary which contains three keys. The 'index'
  746. that identifies the current row, the 'source' which identifies
  747. a column in the wxListCtrl and the 'dest' which tells
  748. wxListCtrl under which key to store the retrieved value. For
  749. more informations see the _talk_to_gui() method under
  750. downloadmanager.py Worker class.
  751. Returns:
  752. A dictionary which holds the 'index' (row) and the data from the
  753. given row-column combination.
  754. Example:
  755. args: data = {'index': 0, 'source': 'filename', 'dest': 'new_filename'}
  756. The wxListCtrl will store the value from the 'filename' column
  757. into a new dictionary with a key value 'new_filename'.
  758. return: {'index': 0, 'new_filename': 'The filename retrieved'}
  759. """
  760. value = None
  761. # If the source column exists
  762. if data['source'] in self.columns:
  763. value = self.GetItemText(data['index'], self.columns[data['source']][0])
  764. return {'index': data['index'], data['dest']: value}
  765. def remove_row(self, row_number):
  766. self.DeleteItem(row_number)
  767. self._list_index -= 1
  768. def move_item_up(self, row_number):
  769. self._move_item(row_number, row_number - 1)
  770. def move_item_down(self, row_number):
  771. self._move_item(row_number, row_number + 1)
  772. def _move_item(self, cur_row, new_row):
  773. self.Freeze()
  774. item = self.GetItem(cur_row)
  775. self.DeleteItem(cur_row)
  776. item.SetId(new_row)
  777. self.InsertItem(item)
  778. self.Select(new_row)
  779. self.Thaw()
  780. def write(self, data):
  781. """Write data on ListCtrl row-column.
  782. Args:
  783. data (dict): Dictionary that contains the data to be
  784. written on the ListCtrl. In order for this method to
  785. write the given data there must be an 'index' key that
  786. identifies the current row. For a valid data dictionary see
  787. Worker class __init__() method under downloadmanager.py module.
  788. """
  789. for key in data:
  790. if key in self.columns:
  791. self._write_data(data['index'], self.columns[key][0], data[key])
  792. def load_urls(self, url_list, func=None):
  793. """Load URLs from the url_list on the ListCtrl widget.
  794. Args:
  795. url_list (list): List of strings that contains the URLs to add.
  796. func (function): Callback function. It's used to add the URLs
  797. on the download_manager.
  798. """
  799. for url in url_list:
  800. url = url.replace(' ', '')
  801. if url and not self.has_url(url):
  802. self.add_url(url)
  803. if func is not None:
  804. # Custom hack to add url into download_manager
  805. item = self._get_item(self._list_index - 1)
  806. func(item)
  807. def has_url(self, url):
  808. """Returns True if the url is aleady in the ListCtrl else False.
  809. Args:
  810. url (string): URL string.
  811. """
  812. return url in self._url_list
  813. def bind_item(self, download_item):
  814. self.InsertStringItem(self._list_index, download_item.url)
  815. self.SetItemData(self._list_index, download_item.object_id)
  816. self._update_from_item(self._list_index, download_item)
  817. self._list_index += 1
  818. def _update_from_item(self, row, download_item):
  819. for key in download_item.progress_stats:
  820. column = self.columns[key][0]
  821. self.SetStringItem(row, column, download_item.progress_stats[key])
  822. def add_url(self, url):
  823. """Adds the given url in the ListCtrl.
  824. Args:
  825. url (string): URL string.
  826. """
  827. self.InsertStringItem(self._list_index, url)
  828. self._url_list.add(url)
  829. self._list_index += 1
  830. def clear(self):
  831. """Clear the ListCtrl widget & reset self._list_index and
  832. self._url_list. """
  833. self.DeleteAllItems()
  834. self._list_index = 0
  835. self._url_list = set()
  836. def is_empty(self):
  837. """Returns True if the list is empty else False. """
  838. return self._list_index == 0
  839. def get_selected(self):
  840. return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
  841. def get_items(self):
  842. """Returns a list of items inside the ListCtrl.
  843. Returns:
  844. List of dictionaries that contains the 'url' and the
  845. 'index'(row) for each item of the ListCtrl.
  846. """
  847. items = []
  848. for row in xrange(self._list_index):
  849. item = self._get_item(row)
  850. items.append(item)
  851. return items
  852. def _write_data(self, row, column, data):
  853. """Write data on row-column. """
  854. if isinstance(data, basestring):
  855. self.SetStringItem(row, column, data)
  856. def _get_item(self, index):
  857. """Returns the corresponding ListCtrl item for the given index.
  858. Args:
  859. index (int): Index that identifies the row of the item.
  860. Index must be smaller than the self._list_index.
  861. Returns:
  862. Dictionary that contains the URL string of the row and the
  863. row number(index).
  864. """
  865. item = self.GetItem(itemId=index, col=0)
  866. data = dict(url=item.GetText(), index=index)
  867. return data
  868. def _set_columns(self):
  869. """Initializes ListCtrl columns.
  870. See MainFrame STATUSLIST_COLUMNS attribute for more info. """
  871. for column_item in sorted(self.columns.values()):
  872. self.InsertColumn(column_item[0], column_item[1], width=wx.LIST_AUTOSIZE_USEHEADER)
  873. # If the column width obtained from wxLIST_AUTOSIZE_USEHEADER
  874. # is smaller than the minimum allowed column width
  875. # then set the column width to the minumum allowed size
  876. if self.GetColumnWidth(column_item[0]) < column_item[2]:
  877. self.SetColumnWidth(column_item[0], column_item[2])
  878. # Set auto-resize if enabled
  879. if column_item[3]:
  880. self.setResizeColumn(column_item[0])
  881. # REFACTOR Extra widgets below should move to other module with widgets
  882. class ExtComboBox(wx.ComboBox):
  883. def __init__(self, parent, max_items=-1, *args, **kwargs):
  884. super(ExtComboBox, self).__init__(parent, *args, **kwargs)
  885. assert max_items > 0 or max_items == -1
  886. self.max_items = max_items
  887. def Append(self, new_value):
  888. if self.FindString(new_value) == wx.NOT_FOUND:
  889. super(ExtComboBox, self).Append(new_value)
  890. if self.max_items != -1 and self.GetCount() > self.max_items:
  891. self.SetItems(self.GetStrings()[1:])
  892. def SetValue(self, new_value):
  893. if self.FindString(new_value) == wx.NOT_FOUND:
  894. self.Append(new_value)
  895. self.SetSelection(self.FindString(new_value))
  896. def LoadMultiple(self, items_list):
  897. for item in items_list:
  898. self.Append(item)