diff --git a/README.md b/README.md index 78e994f..f43eaca 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# LDownloader v3.1 🎬🎵 +# LDownloader v3.1.0 🎬🎵 **LDownloader**, Python, Tkinter ve `yt-dlp` tabanlı, koyu temalı bir Windows masaüstü video ve ses indirme uygulamasıdır. Kullanılabilir platformlar ve formatlar, kaynak içeriğe ve `yt-dlp` desteğine bağlıdır. diff --git a/core/config.py b/core/config.py index f829025..28ff331 100644 --- a/core/config.py +++ b/core/config.py @@ -89,7 +89,6 @@ class ConfigManager: with open(temp_path, "w", encoding="utf-8") as f: json.dump(self.config, f, indent=4, ensure_ascii=False) f.flush() - os.fsync(f.fileno()) os.replace(temp_path, self.config_path) except OSError: logger.exception("Could not save configuration to %s", self.config_path) diff --git a/core/dependencies.py b/core/dependencies.py index f9295bb..29ca0b1 100644 --- a/core/dependencies.py +++ b/core/dependencies.py @@ -5,6 +5,7 @@ import zipfile import subprocess import configparser import requests +import time from core.config import get_bin_dir, get_app_dir, get_data_dir # bin/ dizinini çalışma zamanı PATH değişkeninin başına ekle @@ -141,6 +142,7 @@ def download_file_with_progress(url: str, dest_path: str, progress_callback=None downloaded = 0 total = int(total_length) if total_length else None + last_callback_time = 0.0 with open(dest_path, "wb") as f: for chunk in response.iter_content(chunk_size=1024 * 64): @@ -148,8 +150,11 @@ def download_file_with_progress(url: str, dest_path: str, progress_callback=None f.write(chunk) downloaded += len(chunk) if progress_callback and total: + now = time.monotonic() pct = (downloaded / total) * 100 - progress_callback(pct, downloaded, total) + if (now - last_callback_time >= 0.08) or pct >= 100: + last_callback_time = now + progress_callback(pct, downloaded, total) def install_ytdlp(progress_callback=None): diff --git a/core/downloader.py b/core/downloader.py index a219acd..1f3f9e6 100644 --- a/core/downloader.py +++ b/core/downloader.py @@ -35,24 +35,29 @@ class DownloadEngine: return self._running def cancel(self): - """Devam eden indirmeyi ve tüm alt süreç ağacını güvenle sonlandırır.""" + """Devam eden indirmeyi ve tüm alt süreç ağacını güvenle ve arayüzü dondurmadan sonlandırır.""" with self._lock: if not self._running or not self._proc: return self._cancelled = True + proc = self._proc + + def _do_kill(): try: if sys.platform == "win32": subprocess.run( - ["taskkill", "/F", "/T", "/PID", str(self._proc.pid)], + ["taskkill", "/F", "/T", "/PID", str(proc.pid)], creationflags=subprocess.CREATE_NO_WINDOW, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) else: - self._proc.kill() + proc.kill() except Exception: pass + threading.Thread(target=_do_kill, daemon=True).start() + def start_download(self, cmd_args, callbacks): """ İndirmeyi arka planda başlatır. @@ -358,11 +363,14 @@ def build_command(url, output_dir, options): # Kararlı ilerleme şablonu ve nihai dosya yolu çıktısı # NOT: yt-dlp'de --print bayrağı varsayılan olarak --quiet ve --no-progress modunu tetikler. # Bu yüzden --progress ve --no-quiet açıkça eklenmelidir ki konsol ve ilerleme çubuğu çalışsın. + # --progress-delta 0.15 ile ilerleme güncellemeleri optimize edilir, UI donması ve CPU aşırı yükü engellenir. cmd += [ "--print", "after_move:[FINAL_PATH] %(filepath)s", "--progress", "--no-quiet", + "--progress-delta", + "0.15", "--progress-template", "download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s" ] diff --git a/core/history.py b/core/history.py index 22e6999..66b048e 100644 --- a/core/history.py +++ b/core/history.py @@ -36,7 +36,6 @@ class HistoryManager: with open(temp_path, "w", encoding="utf-8") as f: json.dump(self.items, f, indent=2, ensure_ascii=False) f.flush() - os.fsync(f.fileno()) os.replace(temp_path, self.history_file) except (OSError, TypeError): logger.exception("Could not save download history to %s", self.history_file) diff --git a/core/metadata.py b/core/metadata.py index 79c2557..cd712ce 100644 --- a/core/metadata.py +++ b/core/metadata.py @@ -5,6 +5,10 @@ import requests from PIL import Image, ImageTk from core.dependencies import find_executable +_METADATA_CACHE = {} +_CACHE_LOCK = threading.Lock() +_MAX_CACHE_SIZE = 64 + def format_duration(seconds): """Saniyeyi ss:dd veya saat:ss:dd formatına dönüştürür.""" if not seconds: @@ -65,7 +69,16 @@ def fetch_thumbnail_image(url, size=(160, 90)): def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None, callback=None, error_callback=None): - """Videonun temel bilgilerini arka planda çeker.""" + """Videonun temel bilgilerini arka planda çeker (önbellek destekli).""" + clean_url = (url or "").strip() + with _CACHE_LOCK: + if clean_url in _METADATA_CACHE: + cached = _METADATA_CACHE[clean_url] + if callback: + # Önbellekteki veriyi anında döndür + threading.Thread(target=lambda: callback(cached), daemon=True).start() + return + def _worker(): try: import yt_dlp @@ -93,7 +106,7 @@ def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None, ydl_opts['cookiefile'] = cookies_args[i + 1] with yt_dlp.YoutubeDL(ydl_opts) as ydl: - info = ydl.extract_info(url, download=False) + info = ydl.extract_info(clean_url, download=False) if not info: raise ValueError("Medya bilgileri alınamadı.") @@ -131,6 +144,12 @@ def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None, "raw_info": first_entry } + with _CACHE_LOCK: + if len(_METADATA_CACHE) >= _MAX_CACHE_SIZE: + # En eski kaydı temizle + _METADATA_CACHE.pop(next(iter(_METADATA_CACHE))) + _METADATA_CACHE[clean_url] = metadata + if callback: callback(metadata) diff --git a/tests/test_downloader.py b/tests/test_downloader.py index 9a84019..71df337 100644 --- a/tests/test_downloader.py +++ b/tests/test_downloader.py @@ -137,6 +137,7 @@ class BuildCommandTests(unittest.TestCase): ) self.assertIn("--progress", cmd) self.assertIn("--no-quiet", cmd) + self.assertIn("--progress-delta", cmd) self.assertIn("--progress-template", cmd) self.assertIn("--print", cmd) diff --git a/ui/app.py b/ui/app.py index 6a9eb80..3d5c928 100644 --- a/ui/app.py +++ b/ui/app.py @@ -27,7 +27,7 @@ from core.dependencies import get_ytdlp_status, get_ffmpeg_status, get_js_status class LDownloaderApp(tk.Tk): def __init__(self): super().__init__() - self.title("LDownloader v3.1") + self.title("LDownloader v3.1.0") self.geometry("980x660") self.minsize(880, 580) self.configure(bg=BG) @@ -110,7 +110,7 @@ class LDownloaderApp(tk.Tk): if self.logo_img: tk.Label(brand_frame, image=self.logo_img, bg=TAB_BG).pack(side="left", padx=(0, 8)) - tk.Label(brand_frame, text="LDownloader v3.1", font=FONT_TITLE, bg=TAB_BG, fg=TEXT).pack(side="left") + tk.Label(brand_frame, text="LDownloader v3.1.0", font=FONT_TITLE, bg=TAB_BG, fg=TEXT).pack(side="left") # Orta: Sekmeler self.nav_buttons = {} diff --git a/ui/components.py b/ui/components.py index c3d71fa..062f775 100644 --- a/ui/components.py +++ b/ui/components.py @@ -1,3 +1,4 @@ +import time import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk @@ -248,7 +249,7 @@ class ModernEntry(tk.Entry): class ScrollableFrame(tk.Frame): - """Dikey kaydırma (fare tekerleği destekli) sağlayan modern kapsayıcı çerçeve.""" + """Dikey kaydırma (fare tekerleği destekli) sağlayan akıcı ve optimize modern kapsayıcı çerçeve.""" def __init__(self, parent, **kwargs): super().__init__(parent, bg=BG, **kwargs) self.canvas = tk.Canvas(self, bg=BG, bd=0, highlightthickness=0) @@ -260,6 +261,7 @@ class ScrollableFrame(tk.Frame): self.canvas.pack(side="left", fill="both", expand=True) + self._configure_after_id = None self.inner.bind("", self._on_inner_configure) self.canvas.bind("", self._on_canvas_configure) self.canvas.bind("", self._bind_wheel) @@ -275,22 +277,42 @@ class ScrollableFrame(tk.Frame): self.scrollbar.set(first, last) def _on_inner_configure(self, event=None): - self.canvas.configure(scrollregion=self.canvas.bbox("all")) + if self._configure_after_id: + self.after_cancel(self._configure_after_id) + self._configure_after_id = self.after(20, self._update_scroll_region) + + def _update_scroll_region(self): + self._configure_after_id = None + if self.canvas.winfo_exists(): + self.canvas.configure(scrollregion=self.canvas.bbox("all")) def _on_canvas_configure(self, event): - self.canvas.itemconfig(self._win_id, width=event.width) + if self.canvas.winfo_exists(): + self.canvas.itemconfig(self._win_id, width=event.width) def _bind_wheel(self, event=None): - self.canvas.bind_all("", self._on_mousewheel) + self.canvas.bind_all("", self._on_mousewheel, add="+") def _unbind_wheel(self, event=None): - self.canvas.unbind_all("") + pass def _on_mousewheel(self, event): - first, last = self.canvas.yview() - if first <= 0.0 and last >= 1.0: + if not self.canvas.winfo_exists() or not self.winfo_ismapped(): return - self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") + try: + x, y = self.winfo_pointerxy() + wx = self.winfo_rootx() + wy = self.winfo_rooty() + ww = self.winfo_width() + wh = self.winfo_height() + if not (wx <= x <= wx + ww and wy <= y <= wy + wh): + return + first, last = self.canvas.yview() + if float(first) <= 0.0 and float(last) >= 1.0: + return + self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") + except Exception: + pass class TabButton(tk.Frame): @@ -525,6 +547,12 @@ class ContextualDownloadDrawer(tk.Frame): self.on_cancel = on_cancel self.on_open_file = on_open_file self.console_open = False + self._log_buffer = [] + self._log_flush_pending = False + self._last_stats_update = 0.0 + self._pending_stats = None + self._stats_after_id = None + self._base_title = "İndirme" # Üst Bilgi Satırı top_row = tk.Frame(self, bg=SURFACE) @@ -613,6 +641,16 @@ class ContextualDownloadDrawer(tk.Frame): self.speed_var.set("⚡ —") self.dl_var.set("📥 —") self.eta_var.set("⏱ —") + self._last_stats_update = 0.0 + self._pending_stats = None + if self._stats_after_id: + try: + self.after_cancel(self._stats_after_id) + except Exception: + pass + self._stats_after_id = None + self._log_buffer.clear() + self._log_flush_pending = False if clear_logs: self.log_text.config(state="normal") self.log_text.delete("1.0", "end") @@ -627,11 +665,12 @@ class ContextualDownloadDrawer(tk.Frame): self.pack(fill="x", side="bottom") def set_phase(self, phase_text): + if not self.winfo_exists(): + return base = getattr(self, "_base_title", None) - if base: - self.lbl_title.config(text=f"⏳ {base} · {phase_text}") - else: - self.lbl_title.config(text=f"⏳ {phase_text}") + new_text = f"⏳ {base} · {phase_text}" if base else f"⏳ {phase_text}" + if self.lbl_title.cget("text") != new_text: + self.lbl_title.config(text=new_text) def hide(self): self.pack_forget() @@ -639,6 +678,35 @@ class ContextualDownloadDrawer(tk.Frame): self._toggle_console() def update_stats(self, pct, speed, total, eta): + # 0% ve 100% gibi kritik sınırları hemen göster + if pct <= 0 or pct >= 100: + self._apply_stats(pct, speed, total, eta) + return + + now = time.monotonic() + # 50ms (~20 FPS) altındaki sık çağrıları akıllıca kuyrukla (UI kilitlenmesini önler) + if now - self._last_stats_update >= 0.05: + self._last_stats_update = now + self._apply_stats(pct, speed, total, eta) + else: + self._pending_stats = (pct, speed, total, eta) + if not self._stats_after_id: + try: + self._stats_after_id = self.after(50, self._apply_pending_stats) + except Exception: + self._apply_stats(pct, speed, total, eta) + + def _apply_pending_stats(self): + self._stats_after_id = None + if self._pending_stats: + p, s, t, e = self._pending_stats + self._pending_stats = None + self._last_stats_update = time.monotonic() + self._apply_stats(p, s, t, e) + + def _apply_stats(self, pct, speed, total, eta): + if not self.winfo_exists(): + return self.pbar["value"] = pct self.pct_var.set(f"{pct:.1f}%") self.speed_var.set(f"⚡ {speed}") @@ -646,6 +714,15 @@ class ContextualDownloadDrawer(tk.Frame): self.eta_var.set(f"⏱ {eta}") def on_complete_status(self, success, output_path=None, error_msg=None, cancelled=False): + if self._stats_after_id: + try: + self.after_cancel(self._stats_after_id) + except Exception: + pass + self._stats_after_id = None + if self._log_flush_pending: + self._flush_logs() + self.btn_cancel.pack_forget() if cancelled: self.lbl_title.config(text="⛔ İndirme kullanıcı tarafından iptal edildi.") @@ -663,8 +740,24 @@ class ContextualDownloadDrawer(tk.Frame): self.btn_close.pack(side="left", padx=(6, 0)) def log_line(self, line, tag="info"): + self._log_buffer.append((line, tag)) + if not self._log_flush_pending: + self._log_flush_pending = True + try: + self.after_idle(self._flush_logs) + except Exception: + self._flush_logs() + + def _flush_logs(self): + self._log_flush_pending = False + if not self._log_buffer or not self.log_text.winfo_exists(): + return + buffer = self._log_buffer + self._log_buffer = [] + self.log_text.config(state="normal") - self.log_text.insert("end", line + "\n", tag) + for line, tag in buffer: + self.log_text.insert("end", line + "\n", tag) try: num = int(self.log_text.index("end-1c").split(".")[0]) if num > 1000: diff --git a/ui/tabs/history_tab.py b/ui/tabs/history_tab.py index f546c3e..1f67754 100644 --- a/ui/tabs/history_tab.py +++ b/ui/tabs/history_tab.py @@ -12,6 +12,7 @@ class HistoryTab(tk.Frame): def __init__(self, parent, **kwargs): super().__init__(parent, bg=BG, **kwargs) self.search_query = "" + self._search_after_id = None self._build_ui() self.refresh() @@ -75,7 +76,12 @@ class HistoryTab(tk.Frame): def _on_search_typed(self, text): self.search_query = text.lower().strip() - self.refresh() + if self._search_after_id: + try: + self.after_cancel(self._search_after_id) + except Exception: + pass + self._search_after_id = self.after(120, self.refresh) def refresh(self): for item in self.tree.get_children():