perf & fix: comprehensive UI fluidity and anti-freeze optimization patch (v3.1.0)

This commit is contained in:
LilDosto 2026-10-28 03:48:04 +03:00
parent 9bf6f52c02
commit 067466566b
10 changed files with 155 additions and 25 deletions

View file

@ -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. **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.

View file

@ -89,7 +89,6 @@ class ConfigManager:
with open(temp_path, "w", encoding="utf-8") as f: with open(temp_path, "w", encoding="utf-8") as f:
json.dump(self.config, f, indent=4, ensure_ascii=False) json.dump(self.config, f, indent=4, ensure_ascii=False)
f.flush() f.flush()
os.fsync(f.fileno())
os.replace(temp_path, self.config_path) os.replace(temp_path, self.config_path)
except OSError: except OSError:
logger.exception("Could not save configuration to %s", self.config_path) logger.exception("Could not save configuration to %s", self.config_path)

View file

@ -5,6 +5,7 @@ import zipfile
import subprocess import subprocess
import configparser import configparser
import requests import requests
import time
from core.config import get_bin_dir, get_app_dir, get_data_dir 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 # 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 downloaded = 0
total = int(total_length) if total_length else None total = int(total_length) if total_length else None
last_callback_time = 0.0
with open(dest_path, "wb") as f: with open(dest_path, "wb") as f:
for chunk in response.iter_content(chunk_size=1024 * 64): 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) f.write(chunk)
downloaded += len(chunk) downloaded += len(chunk)
if progress_callback and total: if progress_callback and total:
now = time.monotonic()
pct = (downloaded / total) * 100 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): def install_ytdlp(progress_callback=None):

View file

@ -35,24 +35,29 @@ class DownloadEngine:
return self._running return self._running
def cancel(self): 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: with self._lock:
if not self._running or not self._proc: if not self._running or not self._proc:
return return
self._cancelled = True self._cancelled = True
proc = self._proc
def _do_kill():
try: try:
if sys.platform == "win32": if sys.platform == "win32":
subprocess.run( subprocess.run(
["taskkill", "/F", "/T", "/PID", str(self._proc.pid)], ["taskkill", "/F", "/T", "/PID", str(proc.pid)],
creationflags=subprocess.CREATE_NO_WINDOW, creationflags=subprocess.CREATE_NO_WINDOW,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL stderr=subprocess.DEVNULL
) )
else: else:
self._proc.kill() proc.kill()
except Exception: except Exception:
pass pass
threading.Thread(target=_do_kill, daemon=True).start()
def start_download(self, cmd_args, callbacks): def start_download(self, cmd_args, callbacks):
""" """
İndirmeyi arka planda başlatır. İ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ı # Kararlı ilerleme şablonu ve nihai dosya yolu çıktısı
# NOT: yt-dlp'de --print bayrağı varsayılan olarak --quiet ve --no-progress modunu tetikler. # 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. # 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 += [ cmd += [
"--print", "--print",
"after_move:[FINAL_PATH] %(filepath)s", "after_move:[FINAL_PATH] %(filepath)s",
"--progress", "--progress",
"--no-quiet", "--no-quiet",
"--progress-delta",
"0.15",
"--progress-template", "--progress-template",
"download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s" "download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s"
] ]

View file

@ -36,7 +36,6 @@ class HistoryManager:
with open(temp_path, "w", encoding="utf-8") as f: with open(temp_path, "w", encoding="utf-8") as f:
json.dump(self.items, f, indent=2, ensure_ascii=False) json.dump(self.items, f, indent=2, ensure_ascii=False)
f.flush() f.flush()
os.fsync(f.fileno())
os.replace(temp_path, self.history_file) os.replace(temp_path, self.history_file)
except (OSError, TypeError): except (OSError, TypeError):
logger.exception("Could not save download history to %s", self.history_file) logger.exception("Could not save download history to %s", self.history_file)

View file

@ -5,6 +5,10 @@ import requests
from PIL import Image, ImageTk from PIL import Image, ImageTk
from core.dependencies import find_executable from core.dependencies import find_executable
_METADATA_CACHE = {}
_CACHE_LOCK = threading.Lock()
_MAX_CACHE_SIZE = 64
def format_duration(seconds): def format_duration(seconds):
"""Saniyeyi ss:dd veya saat:ss:dd formatına dönüştürür.""" """Saniyeyi ss:dd veya saat:ss:dd formatına dönüştürür."""
if not seconds: 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): 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(): def _worker():
try: try:
import yt_dlp 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] ydl_opts['cookiefile'] = cookies_args[i + 1]
with yt_dlp.YoutubeDL(ydl_opts) as ydl: 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: if not info:
raise ValueError("Medya bilgileri alınamadı.") 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 "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: if callback:
callback(metadata) callback(metadata)

View file

@ -137,6 +137,7 @@ class BuildCommandTests(unittest.TestCase):
) )
self.assertIn("--progress", cmd) self.assertIn("--progress", cmd)
self.assertIn("--no-quiet", cmd) self.assertIn("--no-quiet", cmd)
self.assertIn("--progress-delta", cmd)
self.assertIn("--progress-template", cmd) self.assertIn("--progress-template", cmd)
self.assertIn("--print", cmd) self.assertIn("--print", cmd)

View file

@ -27,7 +27,7 @@ from core.dependencies import get_ytdlp_status, get_ffmpeg_status, get_js_status
class LDownloaderApp(tk.Tk): class LDownloaderApp(tk.Tk):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.title("LDownloader v3.1") self.title("LDownloader v3.1.0")
self.geometry("980x660") self.geometry("980x660")
self.minsize(880, 580) self.minsize(880, 580)
self.configure(bg=BG) self.configure(bg=BG)
@ -110,7 +110,7 @@ class LDownloaderApp(tk.Tk):
if self.logo_img: 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, 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 # Orta: Sekmeler
self.nav_buttons = {} self.nav_buttons = {}

View file

@ -1,3 +1,4 @@
import time
import tkinter as tk import tkinter as tk
from tkinter import ttk from tkinter import ttk
from PIL import Image, ImageTk from PIL import Image, ImageTk
@ -248,7 +249,7 @@ class ModernEntry(tk.Entry):
class ScrollableFrame(tk.Frame): 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): def __init__(self, parent, **kwargs):
super().__init__(parent, bg=BG, **kwargs) super().__init__(parent, bg=BG, **kwargs)
self.canvas = tk.Canvas(self, bg=BG, bd=0, highlightthickness=0) 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.canvas.pack(side="left", fill="both", expand=True)
self._configure_after_id = None
self.inner.bind("<Configure>", self._on_inner_configure) self.inner.bind("<Configure>", self._on_inner_configure)
self.canvas.bind("<Configure>", self._on_canvas_configure) self.canvas.bind("<Configure>", self._on_canvas_configure)
self.canvas.bind("<Enter>", self._bind_wheel) self.canvas.bind("<Enter>", self._bind_wheel)
@ -275,22 +277,42 @@ class ScrollableFrame(tk.Frame):
self.scrollbar.set(first, last) self.scrollbar.set(first, last)
def _on_inner_configure(self, event=None): 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): 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): def _bind_wheel(self, event=None):
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel) self.canvas.bind_all("<MouseWheel>", self._on_mousewheel, add="+")
def _unbind_wheel(self, event=None): def _unbind_wheel(self, event=None):
self.canvas.unbind_all("<MouseWheel>") pass
def _on_mousewheel(self, event): def _on_mousewheel(self, event):
first, last = self.canvas.yview() if not self.canvas.winfo_exists() or not self.winfo_ismapped():
if first <= 0.0 and last >= 1.0:
return 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): class TabButton(tk.Frame):
@ -525,6 +547,12 @@ class ContextualDownloadDrawer(tk.Frame):
self.on_cancel = on_cancel self.on_cancel = on_cancel
self.on_open_file = on_open_file self.on_open_file = on_open_file
self.console_open = False 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ı # Üst Bilgi Satırı
top_row = tk.Frame(self, bg=SURFACE) top_row = tk.Frame(self, bg=SURFACE)
@ -613,6 +641,16 @@ class ContextualDownloadDrawer(tk.Frame):
self.speed_var.set("⚡ —") self.speed_var.set("⚡ —")
self.dl_var.set("📥 —") self.dl_var.set("📥 —")
self.eta_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: if clear_logs:
self.log_text.config(state="normal") self.log_text.config(state="normal")
self.log_text.delete("1.0", "end") self.log_text.delete("1.0", "end")
@ -627,11 +665,12 @@ class ContextualDownloadDrawer(tk.Frame):
self.pack(fill="x", side="bottom") self.pack(fill="x", side="bottom")
def set_phase(self, phase_text): def set_phase(self, phase_text):
if not self.winfo_exists():
return
base = getattr(self, "_base_title", None) base = getattr(self, "_base_title", None)
if base: new_text = f"⏳ {base} · {phase_text}" if base else f"⏳ {phase_text}"
self.lbl_title.config(text=f"⏳ {base} · {phase_text}") if self.lbl_title.cget("text") != new_text:
else: self.lbl_title.config(text=new_text)
self.lbl_title.config(text=f"⏳ {phase_text}")
def hide(self): def hide(self):
self.pack_forget() self.pack_forget()
@ -639,6 +678,35 @@ class ContextualDownloadDrawer(tk.Frame):
self._toggle_console() self._toggle_console()
def update_stats(self, pct, speed, total, eta): 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.pbar["value"] = pct
self.pct_var.set(f"{pct:.1f}%") self.pct_var.set(f"{pct:.1f}%")
self.speed_var.set(f"⚡ {speed}") self.speed_var.set(f"⚡ {speed}")
@ -646,6 +714,15 @@ class ContextualDownloadDrawer(tk.Frame):
self.eta_var.set(f"⏱ {eta}") self.eta_var.set(f"⏱ {eta}")
def on_complete_status(self, success, output_path=None, error_msg=None, cancelled=False): 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() self.btn_cancel.pack_forget()
if cancelled: if cancelled:
self.lbl_title.config(text="⛔ İndirme kullanıcı tarafından iptal edildi.") 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)) self.btn_close.pack(side="left", padx=(6, 0))
def log_line(self, line, tag="info"): 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.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: try:
num = int(self.log_text.index("end-1c").split(".")[0]) num = int(self.log_text.index("end-1c").split(".")[0])
if num > 1000: if num > 1000:

View file

@ -12,6 +12,7 @@ class HistoryTab(tk.Frame):
def __init__(self, parent, **kwargs): def __init__(self, parent, **kwargs):
super().__init__(parent, bg=BG, **kwargs) super().__init__(parent, bg=BG, **kwargs)
self.search_query = "" self.search_query = ""
self._search_after_id = None
self._build_ui() self._build_ui()
self.refresh() self.refresh()
@ -75,7 +76,12 @@ class HistoryTab(tk.Frame):
def _on_search_typed(self, text): def _on_search_typed(self, text):
self.search_query = text.lower().strip() 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): def refresh(self):
for item in self.tree.get_children(): for item in self.tree.get_children():