diff options
| author | Melody Horn <melody@boringcactus.com> | 2020-12-24 04:56:55 -0700 | 
|---|---|---|
| committer | Melody Horn <melody@boringcactus.com> | 2020-12-24 04:56:55 -0700 | 
| commit | 3364694f14f8a0b92ce70ca608a73966c4043256 (patch) | |
| tree | de2a073ad2660b094fdf5152cfae353578eb488e /sources.py | |
| parent | 940e8754bc13f9f601c5f3db58e4a1ab7d05e2ea (diff) | |
| download | vidslice-3364694f14f8a0b92ce70ca608a73966c4043256.tar.gz vidslice-3364694f14f8a0b92ce70ca608a73966c4043256.zip | |
switch from wxpython to tkinter
Diffstat (limited to 'sources.py')
| -rw-r--r-- | sources.py | 133 | 
1 files changed, 64 insertions, 69 deletions
| @@ -4,8 +4,10 @@ import os  import subprocess  import tempfile  import threading - -import wx +from tkinter import * +from tkinter import filedialog +from tkinter import messagebox +from tkinter import ttk  def has_ytdl(): @@ -17,7 +19,7 @@ def has_ytdl():          return False -def update_ytdl(parent_win): +def update_ytdl(root):      try:          youtube_dl_found = subprocess.run(['where', 'youtube-dl'], stdout=subprocess.PIPE, text=True,                                            creationflags=subprocess.CREATE_NO_WINDOW) @@ -25,115 +27,108 @@ def update_ytdl(parent_win):          youtube_dl_found = subprocess.run(['which', 'youtube-dl'], stdout=subprocess.PIPE, text=True,                                            creationflags=subprocess.CREATE_NO_WINDOW)      if youtube_dl_found.returncode != 0: -        def poll(): -            answer = wx.MessageBox("Could not find youtube-dl. Open vidslice README?", "Error", wx.YES_NO, parent_win) -            if answer == wx.YES: -                import webbrowser -                webbrowser.open("https://github.com/boringcactus/vidslice/blob/master/README.md") -            return - -        wx.CallAfter(poll) +        answer = messagebox.askyesno(message="Could not find youtube-dl. Open vidslice README?", title="Error", +                                     icon='error', parent=root) +        if answer: +            import webbrowser +            webbrowser.open("https://github.com/boringcactus/vidslice/blob/master/README.md")      youtube_dl_path = youtube_dl_found.stdout.split("\n")[0]      old_mtime = os.stat(youtube_dl_path).st_mtime -    proc = subprocess.run(["youtube-dl", "-U"], stdout=subprocess.PIPE, text=True, +    proc = subprocess.run(["youtube-dl", "-U"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,                            creationflags=subprocess.CREATE_NO_WINDOW) -    if not proc.stdout.startswith("youtube-dl is up-to-date"): +    if not proc.stdout.startswith("youtube-dl is up-to-date") and not proc.stdout.startswith("ERROR"):          while os.stat(youtube_dl_path).st_mtime == old_mtime:              from time import sleep              sleep(0.25) -    wx.CallAfter(lambda: wx.MessageBox("Updated youtube-dl successfully", "Complete", wx.OK, parent_win)) +    messagebox.showinfo(message="Updated youtube-dl successfully", title="Complete", parent=root) -class SourcesPanel(wx.Panel): +class SourcesPanel(ttk.LabelFrame):      """      A Panel representing source info      """      def __init__(self, *args, **kw): -        super(SourcesPanel, self).__init__(*args, **kw) +        super(SourcesPanel, self).__init__(*args, text='Sources', **kw)          self.update_listeners = [] -        root_sizer = wx.StaticBoxSizer(wx.VERTICAL, self, label="Sources") -        self.SetSizer(root_sizer) -        main = wx.Panel(self) -        root_sizer.Add(main, proportion=1, flag=wx.EXPAND, border=5) -        main_sizer = wx.GridBagSizer(5, 5) -        main.SetSizer(main_sizer) -          if has_ytdl(): -            main_sizer.Add(wx.StaticText(main, label="URL"), wx.GBPosition(0, 0), flag=wx.EXPAND) -            self.url_text = wx.TextCtrl(main) -            main_sizer.Add(self.url_text, wx.GBPosition(0, 1), flag=wx.EXPAND) -            self.url_download_button = wx.Button(main, label="Download") -            self.url_download_button.Bind(wx.EVT_BUTTON, self.handle_url_download_pressed) -            main_sizer.Add(self.url_download_button, wx.GBPosition(0, 2), flag=wx.EXPAND) +            ttk.Label(self, text="URL").grid(column=0, row=0, sticky=(E, W)) +            self.url_text = StringVar(self) +            ttk.Entry(self, textvariable=self.url_text).grid(column=1, row=0, sticky=(E, W)) +            ttk.Button(self, text="Download", command=self.handle_url_download_pressed +                       ).grid(column=2, row=0, sticky=(E, W))          else: -            no_ytdl_label = wx.StaticText(main, label="Could not find youtube-dl, can't download videos automatically") -            main_sizer.Add(no_ytdl_label, wx.GBPosition(0, 0), wx.GBSpan(1, 3), flag=wx.EXPAND) +            ttk.Label(self, text="Could not find youtube-dl, can't download videos automatically" +                      ).grid(column=0, row=0, columnspan=3, sticky=(E, W)) +            self.url_text = None -        main_sizer.Add(wx.StaticText(main, label="File"), wx.GBPosition(1, 0), flag=wx.EXPAND) -        self.file_text = wx.TextCtrl(main) -        self.file_text.Bind(wx.EVT_TEXT, self.handle_file_changed) -        main_sizer.Add(self.file_text, wx.GBPosition(1, 1), flag=wx.EXPAND) -        self.file_browse_button = wx.Button(main, label="Browse") -        self.file_browse_button.Bind(wx.EVT_BUTTON, self.handle_file_browse_pressed) -        main_sizer.Add(self.file_browse_button, wx.GBPosition(1, 2), flag=wx.EXPAND) +        ttk.Label(self, text="File").grid(column=0, row=1, sticky=(E, W)) +        self.file_text = StringVar(self) +        self.file_text.trace_add("write", self.handle_file_changed) +        ttk.Entry(self, textvariable=self.file_text).grid(column=1, row=1, sticky=(E, W)) +        self.columnconfigure(1, weight=1) +        ttk.Button(self, text="Browse", command=self.handle_file_browse_pressed).grid(column=2, row=1, sticky=(E, W)) -        self.status_label = wx.StaticText(main, label="Status: Select a file") -        main_sizer.Add(self.status_label, wx.GBPosition(2, 0), wx.GBSpan(1, 3)) +        self.status_label = StringVar(self, "Status: Select a file") +        ttk.Label(self, textvariable=self.status_label).grid(column=0, row=2, columnspan=3, sticky=(E, W)) -        main_sizer.AddGrowableCol(1, proportion=1) +        for child in self.winfo_children(): +            child.grid_configure(padx=2, pady=2)      def set_status(self, text): -        self.status_label.SetLabel("Status: " + text) +        self.status_label.set("Status: " + text) -    def handle_url_download_pressed(self, _): +    def handle_url_download_pressed(self, *args):          self.set_status("Downloading...")          def download():              file = tempfile.NamedTemporaryFile(delete=False)              # noinspection PyArgumentList              proc = subprocess.Popen([ -                'youtube-dl', '-o', file.name + '.%(ext)s', self.url_text.GetValue() +                'youtube-dl', '-o', file.name + '.%(ext)s', self.url_text.get()              ], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,                  creationflags=subprocess.CREATE_NO_WINDOW)              while proc.poll() is None:                  out_data = proc.stdout.readline()                  if out_data != '': -                    wx.CallAfter(lambda: self.set_status("Downloading: " + out_data.strip())) +                    self.set_status("Downloading: " + out_data.strip())              if proc.returncode == 0:                  output_file = glob.glob(glob.escape(file.name) + '.*')[0] -                wx.CallAfter(lambda: self.set_status("Downloaded!")) -                wx.CallAfter(lambda: self.file_text.SetValue(output_file)) +                self.set_status("Downloaded!") +                self.file_text.set(output_file)              else:                  error = ''.join(proc.stderr.readlines()).strip() -                wx.CallAfter(lambda: self.set_status("Couldn't download: " + error)) +                self.set_status("Couldn't download: " + error)          threading.Thread(target=download).start() -    def handle_file_browse_pressed(self, _): -        dialog = wx.FileDialog(self, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) -        if dialog.ShowModal() == wx.ID_OK: -            self.file_text.SetValue(dialog.GetPath()) - -    def handle_file_changed(self, _event): -        result = subprocess.run([ -            'ffprobe', '-v', 'error', '-of', 'json', -            '-show_entries', 'format=start_time,duration:stream=index,codec_type,avg_frame_rate,width,height', -            self.file_text.GetValue() -        ], capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW) -        if result.returncode == 0: -            ffprobe_data = json.loads(result.stdout) -            self.set_status("Successfully loaded media info") -            for listener in self.update_listeners: -                listener(ffprobe_data) -        else: -            self.set_status("Failed to load media info: " + result.stderr) -            for listener in self.update_listeners: -                listener(None) +    def handle_file_browse_pressed(self, *args): +        filename = filedialog.askopenfilename(parent=self) +        if filename != '': +            self.file_text.set(filename) + +    def handle_file_changed(self, *args): +        def probe(): +            result = subprocess.run([ +                'ffprobe', '-v', 'error', '-of', 'json', +                '-show_entries', 'format=start_time,duration:stream=index,codec_type,avg_frame_rate,width,height', +                self.file_text.get() +            ], capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW) +            if result.returncode == 0: +                ffprobe_data = json.loads(result.stdout) +                self.set_status("Successfully loaded media info") +                for listener in self.update_listeners: +                    listener(ffprobe_data) +            else: +                self.set_status("Failed to load media info: " + result.stderr) +                for listener in self.update_listeners: +                    listener(None) + +        threading.Thread(target=probe).start()      def on_update(self, callback):          self.update_listeners.append(callback)      def get_file(self): -        return self.file_text.GetValue() +        return self.file_text.get() |