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.

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