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.

1400 lines
47 KiB

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