#!/usr/bin/env python3 # ----------------------------------------------------------------------------- # Script_Launcher.py — DaVinci Resolve # One window to find and run all your scripts. # # ADD A SCRIPT # 1. Click "Open folder" in the launcher. # 2. Drop the .py file in it. # 3. Click "Refresh". Done. # Files starting with "_" or "." are ignored. # # DESCRIPTION (optional) # The launcher reads it from the script header. Either add this line # near the top of the script: # # @desc: Copies the cuts of a reference track onto other tracks # or keep the usual header ("# Name.py — DaVinci Resolve" followed by a # description line), which is detected automatically. # # VERSION (optional) # End the file name with _v + number: "My_Script_v2.py" shows as # "My Script" in the Script column and "2" in the Version column. # # Install : put THIS file in .../Fusion/Scripts/Edit/ # Run : Workspace > Scripts > Script_Launcher # Log : Workspace > Console (Py3 tab) # ----------------------------------------------------------------------------- # ====== SETTINGS ====== SITE_URL = "https://www.brucemangeard.com/editing-toolbox" # <- your website (download page) SITE_LABEL = "Get more scripts" WINDOW_TITLE = "SUKR Launcher v1" REOPEN_AFTER_RUN = True # reopen the launcher when a script ends # ====================== import os import re import sys import platform import subprocess import traceback # ------------------------------------------------------------------ folders def scripts_dir(): """Folder holding the launcher's scripts (not shown in Resolve's menu).""" system = platform.system() if system == "Darwin": base = os.path.expanduser( "~/Library/Application Support/Blackmagic Design/" "DaVinci Resolve/Fusion/Scripts") elif system == "Windows": base = os.path.join(os.environ.get("APPDATA", ""), "Blackmagic Design", "DaVinci Resolve", "Support", "Fusion", "Scripts") else: base = os.path.expanduser("~/.local/share/DaVinciResolve/Fusion/Scripts") return os.path.join(base, "Launcher") def open_path(target): """Open a folder or a URL with the system's default app.""" system = platform.system() try: if system == "Darwin": subprocess.Popen(["open", target]) elif system == "Windows": os.startfile(target) # noqa else: subprocess.Popen(["xdg-open", target]) except Exception as e: try: import webbrowser webbrowser.open(target) except Exception: print("Could not open %s (%s)" % (target, e)) # ------------------------------------------------------------------ scanning def read_desc(path): """'# @desc: ...' line, or the line following '— DaVinci Resolve'.""" try: with open(path, encoding="utf-8", errors="ignore") as f: lines = [f.readline() for _ in range(40)] except OSError: return "" comments = [l.strip() for l in lines if l.strip().startswith("#")] for l in comments: if l.lower().startswith("# @desc:"): return l.split(":", 1)[1].strip() for i, l in enumerate(comments): if "DaVinci Resolve" in l and i + 1 < len(comments): nxt = comments[i + 1].lstrip("#").strip() if nxt and not set(nxt) <= set("-=_ "): return nxt return "" VERSION_RE = re.compile(r"_v(\d+(?:\.\d+)*)$", re.I) def split_name(filename): """'Copy_Master_Cuts_v2.py' -> ('Copy Master Cuts', '2').""" base = os.path.splitext(filename)[0] version = "" m = VERSION_RE.search(base) if m: version = "v" + m.group(1) base = base[:m.start()] return base.replace("_", " ").strip(), version def scan(): folder = scripts_dir() try: os.makedirs(folder, exist_ok=True) names = os.listdir(folder) except OSError as e: print("Cannot read %s (%s)" % (folder, e)) return [] out = [] for fn in sorted(names, key=str.lower): if fn.lower().endswith(".py") and not fn.startswith((".", "_")): path = os.path.join(folder, fn) name, version = split_name(fn) out.append({"name": name, "path": path, "desc": read_desc(path), "version": version}) return out # ------------------------------------------------------------------- running def run_script(script, ctx): print("\n========== %s ==========" % script["name"]) env = dict(ctx) env.update({"__name__": "__main__", "__file__": script["path"]}) folder = os.path.dirname(script["path"]) sys.path.insert(0, folder) try: with open(script["path"], encoding="utf-8") as f: code = f.read() exec(compile(code, script["path"], "exec"), env) except SystemExit: pass except Exception: print("ERROR while running %s:" % script["name"]) traceback.print_exc() finally: if folder in sys.path: sys.path.remove(folder) print("========== end of %s ==========\n" % script["name"]) # ------------------------------------------------------------------------ UI def show_launcher(fu, bmd): """Shows the window. Returns the script to run, or None.""" ui = fu.UIManager disp = bmd.UIDispatcher(ui) win = disp.AddWindow( {"ID": "LauncherWin", "WindowTitle": WINDOW_TITLE, "Geometry": [200, 200, 680, 480]}, ui.VGroup({"Spacing": 6}, [ ui.LineEdit({"ID": "Search", "PlaceholderText": "Search…", "Weight": 0}), ui.Tree({"ID": "List", "Weight": 1, "SortingEnabled": False, "Events": {"ItemDoubleClicked": True}}), ui.Label({"ID": "Info", "Text": "", "WordWrap": True, "Weight": 0}), ui.HGroup({"Weight": 0}, [ ui.Button({"ID": "Run", "Text": "▶ Run"}), ui.Button({"ID": "Refresh", "Text": "Refresh"}), ui.Button({"ID": "Folder", "Text": "Open folder"}), ]), ui.Button({"ID": "Site", "Text": SITE_LABEL, "Weight": 0}), ])) items = win.GetItems() tree = items["List"] hdr = tree.NewItem() hdr.Text[0] = "Script" hdr.Text[1] = "Description" hdr.Text[2] = "Version" tree.SetHeaderItem(hdr) tree.ColumnCount = 3 tree.ColumnWidth[0] = 200 tree.ColumnWidth[1] = 320 tree.ColumnWidth[2] = 60 state = {"scripts": scan(), "choice": None} def fill(ev=None): tree.Clear() q = items["Search"].Text.strip().lower() for s in state["scripts"]: if q and q not in (s["name"] + " " + s["desc"]).lower(): continue it = tree.NewItem() it.Text[0] = s["name"] it.Text[1] = s["desc"] it.Text[2] = s["version"] tree.AddTopLevelItem(it) if state["scripts"]: items["Info"].Text = ("%d script(s). Double-click to run." % len(state["scripts"])) else: items["Info"].Text = ("No script yet. Click 'Open folder', drop " "your .py files in it, then 'Refresh'.") def refresh(ev): state["scripts"] = scan() fill() def run(ev): cur = tree.CurrentItem() if not cur: items["Info"].Text = "Select a script first." return for s in state["scripts"]: if s["name"] == cur.Text[0] and s["version"] == cur.Text[2]: state["choice"] = s disp.ExitLoop() return win.On.Run.Clicked = run win.On.List.ItemDoubleClicked = run win.On.Search.TextChanged = fill win.On.Refresh.Clicked = refresh win.On.Folder.Clicked = lambda ev: open_path(scripts_dir()) win.On.Site.Clicked = lambda ev: open_path(SITE_URL) win.On.LauncherWin.Close = lambda ev: disp.ExitLoop() fill() win.Show() disp.RunLoop() win.Hide() return state["choice"] # ---------------------------------------------------------------------- main def main(): g = globals() ctx = {k: g[k] for k in ("resolve", "fusion", "fu", "bmd", "app", "comp") if k in g} if "resolve" not in ctx: try: ctx["resolve"] = ctx["app"].GetResolve() except Exception: pass fu = ctx.get("fusion") or ctx.get("fu") if fu is None and ctx.get("resolve"): fu = ctx["resolve"].Fusion() ctx["fusion"] = fu bmd_ = ctx.get("bmd") if fu is None or bmd_ is None: print("ERROR: run this from Workspace > Scripts inside DaVinci Resolve.") return while True: choice = show_launcher(fu, bmd_) if choice is None: break run_script(choice, ctx) if not REOPEN_AFTER_RUN: break main()