Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

29.8 KB
Raw Blame
#!/usr/bin/env python3
"""Drag selected files to a native GTK peer or a real browser upload target."""
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time

from PIL import Image, ImageChops

from files_browser import wait_for
from ipc_client import IPCClient, spawn_compositor, stop_process

ROOT = Path(__file__).resolve().parents[1]


def run(browser=False, select=False, list_view=False):
    with tempfile.TemporaryDirectory(prefix="rediwm-files-drag-") as directory:
        tmp = Path(directory)
        home = tmp / "home"
        home.mkdir()
        names = ["a space #.txt", "b-雪.txt"]
        for name in names:
            (home / name).write_text("drag upload payload")
        comp, log = spawn_compositor(tmp, config_content="[compositor]\nxwayland = false\n",
                                     renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
                                     env_extra={"HOME": str(home)})
        peers = []
        try:
            with IPCClient(tmp).connect() as ipc:
                display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
                env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),
                           XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),
                           REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,
                           GDK_BACKEND="wayland", DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent",
                           REDIWM_FILES_DEVICES="0")
                for key in ("DISPLAY", "REDIWM_SOCKET", "WAYLAND_DEBUG"):
                    env.pop(key, None)
                def launch(argv, name):
                    with (tmp / name).open("w") as out:
                        peer = subprocess.Popen(argv, env=env, stdin=subprocess.PIPE, stdout=out, stderr=out)
                    peers.append(peer)
                    return peer

                files = launch([str(ROOT / "zig-out/bin/rediwm-files"), str(home)], "files.log")
                src = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None), "Files did not map")
                ipc.action('set_window_size', {"id": src["id"], "width": 600, "height": 500})
                ipc.action('move_window_to', {"id": src["id"], "x": 10, "y": 30})
                if browser:
                    page = tmp / "upload.html"
                    page.write_text('<title>drop-ready</title><body style="margin:0;background:white">'
                                    '<div id="target" style="position:absolute;left:100px;top:100px;'
                                    'width:400px;height:300px;outline:2px solid gray">Drop files here</div>'
                                    '<script>const t=document.getElementById("target");'
                                    't.ondragover=e=>{e.preventDefault();e.dataTransfer.dropEffect="copy";'
                                    't.style.outlineColor="green";document.title="drop-hover";};'
                                    't.ondragleave=()=>{t.style.outlineColor="gray";document.title="drop-left";};'
                                    't.ondrop=async e=>{e.preventDefault();'
                                    'const fs=[...e.dataTransfer.files];const texts=await Promise.all(fs.map(f=>f.text()));'
                                    'document.title="received:"+fs.length+":"+texts.join("|");};</script>')
                    executable = os.environ.get("REDIWM_TEST_BRAVE") or shutil.which("brave")
                    assert executable, "Brave required for --browser"
                    launch([executable, "--ozone-platform=wayland", f"--user-data-dir={tmp / 'profile'}",
                            "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
                            "--disable-gpu", page.as_uri()], "dest.log")
                else:
                    launch([sys.executable, str(ROOT / "tests/dnd_gtk_client.py"), "dest"], "dest.log")
                dst = wait_for(lambda: next((w for w in ipc.get_windows() if "drop-ready" in w["title"] or "GTK DnD Fixture" in w["title"]), None), "destination did not map", 30)
                ipc.action('set_window_size', {"id": dst["id"], "width": 600, "height": 500})
                ipc.action('move_window_to', {"id": dst["id"], "x": 680, "y": 30})
                ipc.action('focus_window', {"id": src["id"]})
                time.sleep(.5)
                box = ipc.get_window_debug(src["id"])["client_box"]
                dest = ipc.get_window_debug(dst["id"])["client_box"]
                def move(x, y):
                    ipc.action('move_cursor', {"x": round(x), "y": round(y)})
                def button(pressed):
                    ipc.action('pointer_button', {"button": 272, "pressed": pressed})
                if list_view:
                    move(box["x"] + 367, box["y"] + 80)
                    button(True)
                    button(False)
                    time.sleep(.2)
                if select:
                    # Start in the gutter, cover both items and release. The
                    # external drop below proves exactly which paths selected.
                    top = 157 if list_view else 127
                    move(box["x"] + 165, box["y"] + top)
                    time.sleep(.08)
                    button(True)
                    time.sleep(.08)
                    for step in range(1, 11):
                        move(box["x"] + 165 + 395 * step / 10,
                             box["y"] + top + (70 if list_view else 210) * step / 10)
                        if step == 3:
                            # A watcher refresh during a gesture must not
                            # cancel the band or reorder the selected items.
                            (home / ".refresh-probe").write_text("refresh")
                        time.sleep(.03)
                    preview = os.environ.get("REDIWM_FILES_SELECTION_PREVIEW")
                    if preview:
                        ipc.screenshot(path=preview)
                    button(False)
                    time.sleep(.1)
                else:
                    for key, pressed in ((29, True), (30, True), (30, False), (29, False)):
                        ipc.action('key', {"keycode": key, "pressed": pressed})
                x, y = box["x"] + 250, box["y"] + (178 if list_view else 158)
                tx, ty = dest["x"] + 250, dest["y"] + 300
                def icon_pixels():
                    path = tmp / "drag.png"
                    path.unlink(missing_ok=True)
                    ipc.screenshot(path=str(path))
                    with Image.open(path) as image:
                        return image.convert("RGB").crop((round(tx + 8), round(ty + 16),
                                                          round(tx + 40), round(ty + 48)))
                before_icon = icon_pixels() if browser else None
                move(x, y)
                ipc.action('pointer_button', {"button": 272, "pressed": True})
                time.sleep(.08)
                for step in range(1, 17):
                    move(x + (tx-x)*step/16, y + (ty-y)*step/16)
                    time.sleep(.05)
                time.sleep(.3)
                if browser:
                    def title_is(title):
                        return any(title in w["title"] for w in ipc.get_windows())
                    wait_for(lambda: title_is("drop-hover"), "upload target did not highlight")
                    # Cross out of the page target, then out of the browser,
                    # and re-enter. The icon must not intercept target motion.
                    move(dest["x"] + 40, ty)
                    wait_for(lambda: title_is("drop-left"), "upload target did not receive leave")
                    move(x, y)
                    time.sleep(.1)
                    for step in range(1, 9):
                        move(x + (tx-x)*step/8, y + (ty-y)*step/8)
                        time.sleep(.05)
                    wait_for(lambda: title_is("drop-hover"), "upload target did not highlight on re-entry")
                    wait_for(lambda: ImageChops.difference(before_icon, icon_pixels()).getbbox(),
                             "file drag icon was not rendered below the cursor")
                ipc.action('pointer_button', {"button": 272, "pressed": False})
                if browser:
                    expected = "received:2:drag upload payload|drag upload payload"
                    wait_for(lambda: any(expected in w["title"] for w in ipc.get_windows()), "browser did not read both dropped files")
                    wait_for(lambda: ImageChops.difference(before_icon, icon_pixels()).getbbox() is None,
                             "file drag icon remained after drop")
                else:
                    wait_for(lambda: "drag-data-received" in (tmp / "dest.log").read_text(), "GTK did not receive drag")
                    received = (tmp / "dest.log").read_text()
                    for name in names:
                        assert (home / name).as_uri() in received, received
                assert files.poll() is None
                assert all((home / name).exists() for name in names)
                print("PASS Files " + ("list " if list_view else "grid ") + ("drag-selection and " if select else "") + "multi-file drag to " + ("browser upload" if browser else "GTK"))
        except Exception:
            for name in ("files.log", "dest.log", "compositor.log"):
                if (tmp / name).exists():
                    print(name, (tmp / name).read_text()[-5000:])
            raise
        finally:
            for peer in reversed(peers):
                stop_process(peer)
            stop_process(comp)
            log.close()


def run_pin():
    """Drag folders and a file onto PLACES: a line marks the gap, a release pins there."""
    with tempfile.TemporaryDirectory(prefix="rediwm-files-pin-") as directory:
        tmp = Path(directory)
        home = tmp / "home"
        home.mkdir()
        for name in ("pinned folder", "second folder"):
            (home / name).mkdir()
        (home / "note.txt").write_text("pin me")
        state = tmp / "state/rediwm/files-places"
        comp, log = spawn_compositor(tmp, config_content="[compositor]\nxwayland = false\n",
                                     renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
                                     env_extra={"HOME": str(home)})
        files = None
        try:
            with IPCClient(tmp).connect() as ipc:
                display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
                env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),
                           XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),
                           REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,
                           DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0")
                for key in ("DISPLAY", "REDIWM_SOCKET", "WAYLAND_DEBUG"):
                    env.pop(key, None)
                with (tmp / "files.log").open("w") as out:
                    files = subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(home)], env=env, stdout=out, stderr=out)
                win = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None), "Files did not map")
                ipc.action('set_window_size', {"id": win["id"], "width": 1000, "height": 588})
                ipc.action('move_window_to', {"id": win["id"], "x": 10, "y": 30})
                ipc.action('focus_window', {"id": win["id"]})
                time.sleep(.6)
                box = ipc.get_window_debug(win["id"])["client_box"]

                # Window coordinates: three grid cards 252 px apart, the sidebar 208 px
                # wide with rows 32 px apart. Row n of the pins is centred at
                # 494 + 32n, and the gap above it is at 478 + 32n.
                def move(x, y):
                    ipc.action('move_cursor', {"x": round(box["x"] + x), "y": round(box["y"] + y)})
                def button(pressed, code=272):
                    ipc.action('pointer_button', {"button": code, "pressed": pressed})
                def click(x, y, code=272):
                    move(x, y)
                    button(True, code)
                    button(False, code)
                    time.sleep(.15)
                def pins():
                    return state.read_text().splitlines() if state.exists() else []
                def accent_at(y):
                    # The insertion line is accent red; the sidebar there is grey.
                    path = tmp / "hover.png"
                    path.unlink(missing_ok=True)
                    ipc.screenshot(path=str(path))
                    with Image.open(path) as image:
                        pixels = [image.convert("RGB").getpixel((round(box["x"] + 100), round(box["y"] + y + d))) for d in range(-3, 4)]
                    return any(r > 180 and g < 90 and b < 110 for r, g, b in pixels)
                def drag(card, x, y, line_at=None):
                    sx = 250 + 252 * card
                    # A click on an icon opens it (single-click open): the
                    # press alone selects the card the drag carries.
                    move(sx, 158)
                    button(True)
                    time.sleep(.1)
                    for step in range(1, 11):
                        move(sx + (x - sx) * step / 10, 158 + (y - 158) * step / 10)
                        time.sleep(.04)
                    time.sleep(.25)
                    if line_at is not None:
                        wait_for(lambda: accent_at(line_at), f"no insertion line at {line_at} while hovering PLACES")
                    button(False)
                    time.sleep(.5)

                names = [home / "pinned folder", home / "second folder", home / "note.txt"]
                # A file onto the section pins it, even aimed far from the gap.
                drag(2, 80, 270, line_at=478)
                wait_for(lambda: pins() == [str(names[2])], "the dropped file was not pinned")
                # Above the first pin, then between the two.
                drag(0, 80, 270, line_at=478)
                wait_for(lambda: pins() == [str(names[0]), str(names[2])], "folder did not land above the first pin")
                drag(1, 80, 512, line_at=510)
                wait_for(lambda: pins() == [str(n) for n in names], "folder did not land between the pins")
                # Off PLACES nothing is accepted, and a listed folder is not added twice.
                drag(0, 600, 400)
                drag(0, 80, 270)
                time.sleep(.3)
                assert pins() == [str(n) for n in names], pins()
                # A folder pin can open a separate window without navigating this one.
                click(80, 526, 273)
                for code in (108, 28):
                    ipc.action('key', {"keycode": code, "pressed": True})
                    ipc.action('key', {"keycode": code, "pressed": False})
                new = wait_for(lambda: next((w for w in ipc.get_windows()
                                            if w["app_id"] == "rediwm-files" and w["id"] != win["id"]), None),
                               "folder pin did not open a new window")
                assert new["title"] == "second folder — RediWM Files", new
                assert next(w for w in ipc.get_windows() if w["id"] == win["id"])["title"] == win["title"]
                ipc.close_window(new["id"])
                wait_for(lambda: all(w["id"] != new["id"] for w in ipc.get_windows()), "new pin window did not close")
                ipc.action('focus_window', {"id": win["id"]})
                time.sleep(.3)
                box = ipc.get_window_debug(win["id"])["client_box"]
                # A click opens a folder pin.
                click(80, 526)
                wait_for(lambda: any(w["title"].startswith("second folder") for w in ipc.get_windows()), "pin did not open its folder")
                # Removing one keeps the others in order.
                click(80, 558, 273)
                time.sleep(.2)
                for key in (108, 28):
                    ipc.action('key', {"keycode": key, "pressed": True})
                    ipc.action('key', {"keycode": key, "pressed": False})
                wait_for(lambda: pins() == [str(names[0]), str(names[1])], "Remove from Places did not remove the pin")
                assert files.poll() is None
                assert all(n.exists() for n in names)
                print("PASS Files drag onto PLACES pins in order, ignores other drops, opens and removes pins")
        except Exception:
            for name in ("files.log", "compositor.log"):
                if (tmp / name).exists():
                    print(name, (tmp / name).read_text()[-5000:])
            raise
        finally:
            if files:
                stop_process(files)
            stop_process(comp)
            log.close()


def run_trash():
    """Drag files onto the sidebar's Trash row: an outline marks it, a release trashes at once."""
    with tempfile.TemporaryDirectory(prefix="rediwm-files-trash-drop-") as directory:
        tmp = Path(directory)
        home = tmp / "home"
        home.mkdir()
        for name in ("keep folder", "trash folder"):
            (home / name).mkdir()
        (home / "note.txt").write_text("trash me")
        trash = tmp / "data/Trash/files"
        calls = tmp / "gio-calls"
        helpers = tmp / "bin"
        helpers.mkdir()
        # A stand-in for gio: real trashing refuses the tmpfs this test lives on.
        gio = helpers / "gio"
        gio.write_text("#!/usr/bin/python3\n"
                       "import pathlib, shutil, sys\n"
                       f"pathlib.Path({str(calls)!r}).open('a').write(repr(sys.argv[1:]) + '\\n')\n"
                       "assert sys.argv[1:3] == ['trash', '--'], sys.argv\n"
                       f"dest = pathlib.Path({str(trash)!r})\n"
                       "dest.mkdir(parents=True, exist_ok=True)\n"
                       "for path in sys.argv[3:]: shutil.move(path, dest / pathlib.Path(path).name)\n")
        gio.chmod(0o755)
        comp, log = spawn_compositor(tmp, config_content="[compositor]\nxwayland = false\n",
                                     renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
                                     env_extra={"HOME": str(home)})
        files = None
        try:
            with IPCClient(tmp).connect() as ipc:
                display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
                env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),
                           XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),
                           REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,
                           DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0",
                           PATH=f"{helpers}:{os.environ['PATH']}")
                for key in ("DISPLAY", "REDIWM_SOCKET", "WAYLAND_DEBUG"):
                    env.pop(key, None)
                with (tmp / "files.log").open("w") as out:
                    files = subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(home)], env=env, stdout=out, stderr=out)
                win = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None), "Files did not map")
                ipc.action('set_window_size', {"id": win["id"], "width": 1000, "height": 588})
                ipc.action('move_window_to', {"id": win["id"], "x": 10, "y": 30})
                ipc.action('focus_window', {"id": win["id"]})
                time.sleep(.6)
                box = ipc.get_window_debug(win["id"])["client_box"]

                # Window coordinates as in run_pin: Home is centred at 142,
                # Trash at 174 (its outline's top edge at 158).
                def move(x, y):
                    ipc.action('move_cursor', {"x": round(box["x"] + x), "y": round(box["y"] + y)})
                def button(pressed):
                    ipc.action('pointer_button', {"button": 272, "pressed": pressed})
                def accent_at(y):
                    path = tmp / "hover.png"
                    path.unlink(missing_ok=True)
                    ipc.screenshot(path=str(path))
                    with Image.open(path) as image:
                        pixels = [image.convert("RGB").getpixel((round(box["x"] + 100), round(box["y"] + y + d))) for d in range(-3, 4)]
                    return any(r > 180 and g < 90 and b < 110 for r, g, b in pixels)
                def drag(card, x, y, outline=False):
                    sx = 250 + 252 * card
                    # A click on an icon opens it (single-click open): the
                    # press alone selects the card the drag carries.
                    move(sx, 158)
                    button(True)
                    time.sleep(.1)
                    for step in range(1, 11):
                        move(sx + (x - sx) * step / 10, 158 + (y - 158) * step / 10)
                        time.sleep(.04)
                    time.sleep(.25)
                    if outline:
                        wait_for(lambda: accent_at(158), "no outline on the Trash row while hovering it")
                    button(False)
                    time.sleep(.5)
                def gio_calls():
                    return calls.read_text().splitlines() if calls.exists() else []

                # Cards: keep folder, trash folder, note.txt.
                drag(2, 80, 174, outline=True)
                wait_for(lambda: (trash / "note.txt").exists(), "the dropped file was not trashed")
                assert not (home / "note.txt").exists()
                assert gio_calls() == [repr(["trash", "--", str(home / "note.txt")])], gio_calls()
                assert not accent_at(158), "the Trash outline outlived the drop"
                drag(1, 80, 174)
                wait_for(lambda: (trash / "trash folder").is_dir(), "the dropped folder was not trashed")
                # Home is not a target: nothing more is trashed.
                drag(0, 80, 142)
                time.sleep(.3)
                assert len(gio_calls()) == 2, gio_calls()
                assert (home / "keep folder").is_dir()
                assert files.poll() is None
                print("PASS Files drag onto the Trash row trashes without a dialog; other rows do not")
        except Exception:
            for name in ("files.log", "compositor.log"):
                if (tmp / name).exists():
                    print(name, (tmp / name).read_text()[-5000:])
            raise
        finally:
            if files:
                stop_process(files)
            stop_process(comp)
            log.close()


def run_transfer(same_window=False, copy=False, list_view=False, folder=True, ctrl_changes=()):
    expected_copy = ctrl_changes[-1] if ctrl_changes else copy
    with tempfile.TemporaryDirectory(prefix="rediwm-files-transfer-") as directory:
        tmp = Path(directory)
        home = tmp / "home"
        home.mkdir()
        source = home / "source"
        source.mkdir()
        target = source / "destination" if same_window else home / "target"
        target.mkdir()
        if folder and not same_window:
            target = target / "destination"
            target.mkdir()
        name = "a space # 雪.txt"
        (source / name).write_text("transfer payload")
        if not same_window:
            (source / "bundle").mkdir()
            (source / "bundle" / "child.txt").write_text("nested payload")
        comp, log = spawn_compositor(tmp, scale=os.environ.get("REDIWM_TEST_SCALE", "1"),
                                     config_content="[compositor]\nxwayland = false\ndodge_file_drags = false\n",
                                     env_extra={"HOME": str(home)})
        peers = []
        try:
            with IPCClient(tmp).connect() as ipc:
                display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
                env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),
                           XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),
                           XDG_CACHE_HOME=str(tmp / "cache"),
                           REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,
                           DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0")
                env.pop("DISPLAY", None)
                def launch(path, x):
                    known = {w["id"] for w in ipc.get_windows()}
                    out = (tmp / f"files-{x}.log").open("w")
                    try:
                        peers.append(subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(path)], env=env, stdout=out, stderr=out))
                    finally:
                        out.close()
                    window = wait_for(lambda: next((w for w in ipc.get_windows() if w["id"] not in known), None), "Files did not map")
                    ipc.action('set_window_size', {"id": window["id"], "width": 600, "height": 500})
                    ipc.action('move_window_to', {"id": window["id"], "x": x, "y": 30})
                    return window
                src = launch(source, 10)
                dst = src if same_window else launch(target.parent if folder else target, 680)
                ipc.action('focus_window', {"id": src["id"]})
                for window in ([src] if same_window else [src, dst]):
                    ipc.wait_for("window_geometry_settled", window_id=window["id"])
                time.sleep(.5)
                box = ipc.get_window_debug(src["id"])["client_box"]
                dest = ipc.get_window_debug(dst["id"])["client_box"]
                def move(x, y):
                    ipc.action('move_cursor', {"x": round(x), "y": round(y)})
                def button(pressed):
                    ipc.action('pointer_button', {"button": 272, "pressed": pressed})
                if list_view:
                    for rect in ([box] if same_window else [box, dest]):
                        move(rect["x"] + 367, rect["y"] + 80)
                        button(True)
                        button(False)
                    time.sleep(.3)
                # Folders sort first: the source file is second in a shared window.
                sx = box["x"] + 250
                sy = box["y"] + ((216 if same_window else 178) if list_view else (302 if same_window else 158))
                tx = dest["x"] + 250
                ty = dest["y"] + ((178 if list_view else 158) if folder else 350)
                move(sx, sy)
                button(True)
                button(False)
                time.sleep(.7)
                if not same_window:
                    for key, pressed in ((29, True), (30, True), (30, False), (29, False)):
                        ipc.action('key', {"keycode": key, "pressed": pressed})
                if copy:
                    ipc.action('key', {"keycode": 29, "pressed": True})
                button(True)
                time.sleep(.08)
                for step in range(1, 17):
                    move(sx + (tx-sx)*step/16, sy + (ty-sy)*step/16)
                    time.sleep(.04)
                time.sleep(.2)
                # Change Ctrl while stationary over the target: action updates
                # must not depend on another pointer motion or drag enter.
                for pressed in ctrl_changes:
                    ipc.action('key', {"keycode": 29, "pressed": pressed})
                    time.sleep(.2)
                button(False)
                if expected_copy:
                    ipc.action('key', {"keycode": 29, "pressed": False})
                wait_for(lambda: (target / name).exists(), "file did not arrive at drop destination")
                assert (target / name).read_text() == "transfer payload"
                if expected_copy:
                    assert (source / name).read_text() == "transfer payload"
                else:
                    wait_for(lambda: not (source / name).exists(), "move left the source behind")
                if not same_window:
                    wait_for(lambda: (target / "bundle" / "child.txt").exists(), "nested folder did not arrive")
                    assert (target / "bundle" / "child.txt").read_text() == "nested payload"
                    if expected_copy:
                        assert (source / "bundle" / "child.txt").read_text() == "nested payload"
                    else:
                        wait_for(lambda: not (source / "bundle").exists(), "folder move left the source behind")
                assert all(peer.poll() is None for peer in peers), "Files exited during transfer"
                changes = f" Ctrl changes={ctrl_changes}" if ctrl_changes else ""
                print(f"PASS Files {'copy' if expected_copy else 'move'} {'within window' if same_window else 'between windows'} {'folder' if folder else 'background'} {'list' if list_view else 'grid'}{changes}")
        finally:
            for peer in peers:
                stop_process(peer)
            stop_process(comp)
            log.close()


if __name__ == "__main__":
    if "--transfer" in sys.argv:
        run_transfer(same_window=True)
        run_transfer(same_window=True, copy=True, list_view=True)
        run_transfer(folder=False)
        run_transfer(copy=True)
        run_transfer(list_view=True)
        run_transfer(same_window=True, ctrl_changes=(True,))
        run_transfer(same_window=True, copy=True, ctrl_changes=(False,))
        run_transfer(ctrl_changes=(True,))
        run_transfer(copy=True, ctrl_changes=(False,))
        sys.exit(0)
    if "--pin" in sys.argv:
        run_pin()
        sys.exit(0)
    if "--trash" in sys.argv:
        run_trash()
        sys.exit(0)
    run("--browser" in sys.argv, "--select" in sys.argv, "--list" in sys.argv)