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.

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