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.

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