Explorar el Código

Merge remote-tracking branch 'origin/wip/startup2190hd' into wip/rollup028

# Conflicts:
#	src/Main.cpp
Ka1-S hace 3 semanas
padre
commit
2d7c65a5dd

+ 20 - 0
cmake/LynxPatchJuce.cmake

@@ -171,6 +171,17 @@
 #    to its windows (all messages while the driver's control panel is open). LYNX can then make and open its device
 #    on a worker while the main window is built (engine/DllAsioDevice.h, prewarmAsioDevice). The audio callbacks still
 #    come from the driver's own thread. LYNX_ASIO_THREAD=0: as before (the caller's thread; no prewarm either).
+# 30. Windows only, juce_graphics/native/juce_Direct2DImage_windows.cpp (round 190hd, 28 in its branch; start-up): a thread can ask for
+#    software images (`juce::lynxSoftwareImagesOnThisThread (true)`): every image it makes after that, a decoded PNG
+#    included, is a plain software image instead of a Direct2D one. The splash card draws on a thread of its own with the
+#    CPU (ui/Splash.cpp); before, its logo was the process's first Direct2D image, so the Direct3D 11 + Direct2D device
+#    (~0.35-0.4 s) was made before the card could show. Other threads: as before.
+# 31. Windows only, juce_audio_devices/native/juce_ASIO_windows.cpp (round 190hd, 29 in its branch; start-up): JUCE starts an ASIO driver,
+#    sleeps 80 ms and stops it while it initialises the device ("because Cubase does it"); for "FL Studio ASIO" that is
+#    ~0.27 s of the start-up's critical path (its stop ends a Windows Audio stream). The ASIO protocol does not ask for
+#    it (init, channels, buffer sizes, createBuffers, start). `juce::lynxAsioQuickInit` (set by LYNX's prewarm for the
+#    one device it makes ahead, engine/DllAsioDevice.cpp) skips it for that device only; a device that then fails to
+#    open is made again the usual way (AudioEngine::openAudioDevice). Every other open: as JUCE does.
 #
 # Used by CMake (lynx_patch_juce on the fetched JUCE) and by scripts/build-windows-zig.sh, which runs this file with
 # `cmake -DJUCE_DIR=<a copy of JUCE's juce_gui_basics module> -P cmake/LynxPatchJuce.cmake`.
@@ -270,6 +281,9 @@ function(lynx_patch_juce_file file)
         lynx_juce_fix("image readback put off (one image)" "LYNX patch (round 190bm): for one image"
             "        const bool skipReadback = lynxSkipImageReadback; // LYNX patch (round 174e2): the flag when made|NL|"
             "        // LYNX patch (round 174e2): the flag when made|NL|        // LYNX patch (round 190bm): for one image only (a Graphics made on another image meanwhile reads back as ever)|NL|        const bool skipReadback = lynxSkipImageReadback && lynxNoReadbackImage == self.get();|NL|")
+        lynx_juce_fix("software images on a thread that asks for them" "LYNX patch (round 190hd): software images"
+            "ImagePixelData::Ptr NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const|NL|{|NL|    SharedResourcePointer<DirectX> directX;|NL|"
+            "// LYNX patch (round 190hd): software images on a thread that asks for them (cmake/LynxPatchJuce.cmake, fix 30)|NL|static thread_local bool lynxSoftwareImages = false;|NL|void lynxSoftwareImagesOnThisThread (bool on) { lynxSoftwareImages = on; }|NL||NL|ImagePixelData::Ptr NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const|NL|{|NL|    if (lynxSoftwareImages) // LYNX patch (round 190hd): this thread draws with the CPU (no Direct2D device made for it)|NL|        return new SoftwarePixelData { format, width, height, clearImage };|NL||NL|    SharedResourcePointer<DirectX> directX;|NL|")
     elseif(file MATCHES "juce_Windowing_linux.cpp$")
         lynx_juce_fix("no X focus for menu windows" "LYNX patch (issue #45): never takes the X focus"
             "    void grabFocus() override|NL|    {|NL|"
@@ -338,6 +352,12 @@ function(lynx_patch_juce_file file)
         lynx_juce_fix("ASIO channel names after a reset on the ASIO thread" "LYNX patch (round 190go): the channel names"
             "                  currentSampleRate, currentBlockSizeSamples);|NL||NL|            reloadChannelNames();|NL|"
             "                  currentSampleRate, currentBlockSizeSamples);|NL||NL|            // LYNX patch (round 190go): the channel names from the ASIO thread|NL|            lynxAsioCall ([this] { reloadChannelNames(); });|NL|")
+        lynx_juce_fix("ASIO quick init for the start-up's device" "LYNX patch (round 190hd): no start / stop at init"
+            "                        // start and stop because cubase does it..|NL|                        err = asioObject->start();|NL|                        // ignore an error here, as it might start later after setting other stuff up|NL|                        JUCE_ASIO_LOG_ERROR (\"start\", err);|NL||NL|                        Thread::sleep (80);|NL|                        asioObject->stop();|NL|"
+            "                        // LYNX patch (round 190hd): no start / stop at init for the device the start-up makes ahead|NL|                        // (fix 31: lynxAsioQuickInit, set by LYNX's prewarm for its one device); every other open as JUCE does|NL|                        if (! lynxAsioQuickInit.exchange (false))|NL|                        {|NL|                        // start and stop because cubase does it..|NL|                        err = asioObject->start();|NL|                        // ignore an error here, as it might start later after setting other stuff up|NL|                        JUCE_ASIO_LOG_ERROR (\"start\", err);|NL||NL|                        Thread::sleep (80);|NL|                        asioObject->stop();|NL|                        }|NL|")
+        lynx_juce_fix("ASIO quick init flag" "LYNX patch (round 190hd): the quick init flag"
+            "static void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType*);|NL|"
+            "static void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType*);|NL||NL|// LYNX patch (round 190hd): the quick init flag (cmake/LynxPatchJuce.cmake, fix 31)|NL|std::atomic<bool> lynxAsioQuickInit { false };|NL|")
     elseif(file MATCHES "juce_WASAPI_windows.cpp$")
         lynx_juce_fix("shared mode keeps the mix format's channels" "LYNX patch (issue #134): shared mode"
             "        if (fallbackNumChannels >= maxNumChannelsToQuery)|NL|            return fallbackNumChannels;|NL|"

+ 138 - 11
src/Main.cpp

@@ -243,6 +243,7 @@ struct StartupTrace
 {
     using clock = std::chrono::steady_clock;
     const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
+    const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
     // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
     // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
     const bool on = true;
@@ -957,6 +958,24 @@ public:
             lynx::crashguard::exitNow (0);
         }
 
+        if (args.contains ("--splashshot"))
+        {
+            // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
+            // thread is (ui/Splash.h), side by side; no window
+            const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
+            setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
+            quit();
+            return;
+        }
+
+        if (args.contains ("--browser-indexer"))
+        {
+            // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
+            // no session, no audio; it ends with its parent
+            lynx::crashguard::quietCrashReports();
+            lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
+        }
+
         if (args.contains ("--packageinfo"))
         {
             // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
@@ -2640,6 +2659,17 @@ public:
             lynx::crashguard::startMainProfiler (profile.toStdString());
 
         startupTrace.mark ("initialise (normal start)");
+        // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
+        // relocations) and the static initialisers that ran before this file's
+        if (const auto created = lynx::crashguard::processStartTime(); created != 0)
+        {
+            const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
+                            + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
+            if (t0 > created)
+                startupTrace.mark (("  (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
+                                    + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
+        }
+        prepareGraphicsDevice();
         if (startupTrace.on)
             lynx::startupMark = startupMarkHook;
         juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
@@ -2712,10 +2742,17 @@ public:
         // it during the drop would stop the animation, both run on the message thread), then the audio device opens
         // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
         // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
-        splash = std::make_unique<lynx::SplashScreen>();
+        // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
+        // (startOnItsOwnThread below).
+        splash = lynx::makeStartupSplash();
         startupTrace.mark ("splash made");
         splash->showOnDesktop();
         startupTrace.mark ("splash on the desktop");
+        if (splash->drawsOnItsOwnThread())
+        {
+            startWithThreadedSplash();
+            return;
+        }
 
         // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
         // after 40 ms
@@ -2738,29 +2775,81 @@ public:
         juce::Timer::callAfterDelay (40, goOn);
     }
 
+    // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
+    // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
+    // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
+    // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
+    // the logo drops and shown as soon as it is built, behind the card (the drop and its sound go on above it); the card
+    // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
+    // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
+    void startWithThreadedSplash()
+    {
+        splash->onFirstFrame = [this] {
+            if (splash != nullptr && startupTrace.on)
+                startupTrace.mark (("  splash: first frame on the screen at "
+                                    + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
+                                       .toRawUTF8());
+        };
+        juce::MessageManager::callAsync ([this] {
+            if (splash == nullptr) // (quit meanwhile)
+                return;
+            startEngine();
+            if (splash == nullptr)
+                return;
+            if (startupOptions.sound)
+                openAudioDevice (false); // (else after the splash: nothing waits for it)
+            startDrop();
+            // the main window while the logo drops (one more message, so the drop's start is not held by it)
+            juce::MessageManager::callAsync ([this] {
+                if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
+                    return;
+                createMainWindow();
+                // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
+                // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
+                if (mainWindow != nullptr && splash != nullptr
+                    && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
+                {
+                    mainWindow->reveal();
+                    windowRevealed = true;
+                    startupTrace.mark ("window revealed (behind the card, while the logo drops)");
+                    splash->raise();
+                }
+            });
+        });
+    }
+
     // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
     void startDrop()
     {
-        if (splash == nullptr || mainWindow == nullptr || engine == nullptr)
+        const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
+        if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
             return;
         if (startupOptions.sound)
             playStartupSound();
         splash->setStatus (lynx::tr ("Loading the workspace..."));
         splash->startClock();
-        // the minimum counts from the process start (the window and the audio device took part of it already)
-        splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
+        // the minimum counts from the process start (the window and the audio device took part of it already); a card
+        // on its own thread stays for the drop (round 190hd)
+        splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
         splash->setBarDuration (splashDuration);
 
-        juce::Timer::callAfterDelay (juce::roundToInt (splashDuration * 1000.0), [this] {
+        splash->whenLanded (splashDuration, [this] {
             if (splash == nullptr || mainWindow == nullptr)
                 return;
 
             if (startupTrace.on)
                 startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
-                                    + juce::String (splash->getLongestDropGapMs(), 1) + " ms").toRawUTF8());
-            mainWindow->reveal();
-            startupTrace.mark ("window revealed (after the splash)");
-            splash->toFront (false);
+                                    + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
+                                    + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
+                                                                                  + splash->getLongestDropGapDetail() + ")"
+                                                                            : juce::String()))
+                                       .toRawUTF8());
+            if (! std::exchange (windowRevealed, true))
+            {
+                mainWindow->reveal();
+                startupTrace.mark ("window revealed (after the splash)");
+            }
+            splash->raise();
             const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
             splash->finish ([this, deviceOpen] {
                 splash = nullptr;
@@ -2828,9 +2917,37 @@ public:
         juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
     }
 
+    // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
+    // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
+    // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
+    // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
+    // at its next use). Other systems: nothing to do.
+    void prepareGraphicsDevice()
+    {
+       #if JUCE_WINDOWS
+        if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
+            return;
+        graphicsDeviceJob = std::async (std::launch::async, [] {
+            const auto from = std::chrono::steady_clock::now();
+            juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
+            return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
+        });
+       #endif
+    }
+
+    void markGraphicsDevice()
+    {
+        if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
+            return;
+        const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
+        startupTrace.mark (ready ? ("  graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
+                                 : "  graphics device: still being made on its worker");
+    }
+
     void startEngine()
     {
         startupTrace.mark ("before the audio engine");
+        lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
         // (round 190go) ready to play, no device open yet: see openAudioDevice
         engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
         lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
@@ -2907,6 +3024,7 @@ public:
                 });
             lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
         });
+        markGraphicsDevice();
     }
 
     // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
@@ -3141,6 +3259,7 @@ public:
         lynx::remoteui::shutdown();
         remoteControl = nullptr; // cancels queued control work before its engine and UI go
         mainWindow = nullptr; // the UI goes before the engine
+        graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
         lynx::updater::shutdown(); // (a check or download in flight stops)
         crashEngine = nullptr;
         engine = nullptr;
@@ -26714,12 +26833,17 @@ private:
     {
     public:
         MainWindow (const juce::String& name, lynx::AudioEngine& engine)
-            : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
+            : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
         {
+            // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
+            // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
             setUsingNativeTitleBar (true);
+            addToDesktop();
             setIcon (lynx::logoImage());
+            startupTrace.mark ("  window: its desktop window (native title bar), icon");
             content = new lynx::MainComponent (engine);
             setContentOwned (content, true);
+            startupTrace.mark ("  window: content set");
             setResizable (true, true);
             setResizeLimits (800, 400, 10000, 10000);
             // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
@@ -26882,7 +27006,10 @@ private:
     }
     std::unique_ptr<MainWindow> mainWindow;
     std::unique_ptr<juce::Timer> perf; // --uiperf
-    std::unique_ptr<lynx::SplashScreen> splash;
+    std::unique_ptr<lynx::StartupSplash> splash;
+    static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
+    std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
+    bool graphicsDeviceMarked = false, windowRevealed = false;
     std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
     bool startedAfterWindow = false, startupSoundPlayed = false;
     double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)

+ 27 - 0
src/core/SearchIndex.cpp

@@ -274,6 +274,33 @@ bool Index::isComplete (const std::string& folder) const
     return std::any_of (complete.begin(), complete.end(), [this, &folder] (const std::string& r) { return isUnder (folder, r) && folders.count (r) > 0; });
 }
 
+void Index::adopt (const Index& newer)
+{
+    const auto completeInNewer = [&newer] (const std::string& folder) { return newer.isComplete (folder); };
+    for (auto f = folders.begin(); f != folders.end();)
+    {
+        if (completeInNewer (f->first) && newer.folders.count (f->first) == 0)
+            f = folders.erase (f); // (the other process found it gone)
+        else
+            ++f;
+    }
+    std::vector<const std::pair<const std::string, Folder>*> taken; // (decided before anything changes here)
+    for (const auto& entry : newer.folders)
+        if (completeInNewer (entry.first) || ! isComplete (entry.first))
+            taken.push_back (&entry);
+    for (const auto* entry : taken)
+    {
+        auto& mine = folders[entry->first];
+        const auto listedIn = mine.listedIn, seenIn = mine.seenIn; // (this index's own rebuild marks)
+        mine = entry->second;
+        mine.listedIn = listedIn;
+        mine.seenIn = seenIn;
+    }
+    for (const auto& r : newer.complete)
+        complete.insert (r);
+    ++gen;
+}
+
 std::size_t Index::fileCount() const noexcept
 {
     std::size_t n = 0;

+ 5 - 0
src/core/SearchIndex.h

@@ -112,6 +112,11 @@ public:
 
     static bool isUnder (const std::string& path, const std::string& root);
 
+    // The index another process wrote (round 190hd: the Browser's indexer process): its folder trees replace these
+    // where it walked them to the end (folders it found gone are dropped), the rest of its folders come in where
+    // this index has no complete tree of its own; trees only this index walked to the end stay as they are.
+    void adopt (const Index& newer);
+
     // Text form for the index file: one "D\t<time>\t<folder>" line per folder followed by "F\t<name>" / "S\t<name>";
     // "R\t<folder>" lines name the complete trees.
     std::string toText() const;

+ 59 - 3
src/core/SearchService.cpp

@@ -78,6 +78,27 @@ void Service::refresh (std::vector<std::string> roots, bool rebuild)
     wake.notify_all();
 }
 
+void Service::setExternalIndexer (bool on)
+{
+    const std::lock_guard<std::mutex> guard (lock);
+    external = on;
+}
+
+bool Service::hasExternalIndexer() const
+{
+    const std::lock_guard<std::mutex> guard (lock);
+    return external;
+}
+
+void Service::reload()
+{
+    {
+        const std::lock_guard<std::mutex> guard (lock);
+        reloadAsked = true;
+    }
+    wake.notify_all();
+}
+
 IndexStatus Service::status() const
 {
     const std::lock_guard<std::mutex> guard (lock);
@@ -87,7 +108,7 @@ IndexStatus Service::status() const
 bool Service::waitIdle (int timeoutMs)
 {
     std::unique_lock<std::mutex> guard (lock);
-    return idleWake.wait_for (guard, std::chrono::milliseconds (timeoutMs), [this] { return ! working && ! pendingSearch && passes.empty(); });
+    return idleWake.wait_for (guard, std::chrono::milliseconds (timeoutMs), [this] { return ! working && ! pendingSearch && passes.empty() && ! reloadAsked; });
 }
 
 bool Service::superseded (std::uint64_t id) const
@@ -122,11 +143,12 @@ void Service::run()
     {
         std::optional<SearchJob> job;
         std::optional<Pass> pass;
+        bool reloadNow = false;
         {
             std::unique_lock<std::mutex> guard (lock);
             working = false;
             idleWake.notify_all();
-            wake.wait (guard, [this] { return stopping || pendingSearch.has_value() || ! passes.empty(); });
+            wake.wait (guard, [this] { return stopping || pendingSearch.has_value() || ! passes.empty() || reloadAsked; });
             if (stopping)
                 break;
             working = true;
@@ -135,6 +157,11 @@ void Service::run()
                 job = std::move (pendingSearch);
                 pendingSearch.reset();
             }
+            else if (reloadAsked)
+            {
+                reloadAsked = false;
+                reloadNow = true;
+            }
             else
             {
                 pass = std::move (passes.front());
@@ -146,6 +173,8 @@ void Service::run()
         {
             if (job)
                 runSearch (*job);
+            else if (reloadNow)
+                reloadIndex();
             else if (pass && ! runPass (*pass))
             {
                 // interrupted by a search: carries on after it (the work done so far is kept)
@@ -189,6 +218,31 @@ void Service::loadIndex()
     setStatus ([] (IndexStatus& s) { s.loaded = true; });
 }
 
+void Service::reloadIndex()
+{
+    std::string text;
+    try
+    {
+        if (callbacks.load)
+            text = callbacks.load();
+    }
+    catch (const std::exception& e)
+    {
+        std::fprintf (stderr, "browser index: %s\n", e.what());
+        return;
+    }
+    Index newer;
+    if (text.empty() || ! newer.fromText (text)) // (no file, or one being replaced: the next reload reads it)
+        return;
+    {
+        const std::lock_guard<std::mutex> guard (indexLock);
+        index.adopt (newer);
+    }
+    setStatus ([this] (IndexStatus& s) { s.checkedAt = now(); });
+    if (callbacks.indexChanged)
+        callbacks.indexChanged();
+}
+
 std::shared_ptr<const FolderMatches> Service::folderMatches (int key, const std::function<bool (const std::string&)>& accept)
 {
     auto& cached = matchCache[key];
@@ -202,7 +256,7 @@ std::shared_ptr<const FolderMatches> Service::folderMatches (int key, const std:
 
 void Service::saveIndex()
 {
-    if (! callbacks.save)
+    if (! callbacks.save || hasExternalIndexer()) // (round 190hd: the indexer process writes the file)
         return;
     std::string text;
     {
@@ -328,6 +382,8 @@ void Service::runSearch (SearchJob& job)
             return;
         if (job.done)
             job.done (result);
+        if (external) // (round 190hd: the indexer process hears of the folders' changes itself)
+            return;
 
         // then the folders searched are checked again in the background (FL's "dirty folders"), unless that was just done
         std::vector<std::string> stale;

+ 10 - 0
src/core/SearchService.h

@@ -77,6 +77,14 @@ public:
     // A background pass over these folders: only changed folders are listed again; rebuild = forget the index first.
     void refresh (std::vector<std::string> roots, bool rebuild = false);
 
+    // Round 190hd: another process (the Browser's indexer, a low-priority child woken by file-system changes) keeps
+    // the index file up to date. While it does, this service saves nothing and runs no re-check pass after a search;
+    // reload() reads the file it wrote (on the worker, after the search in hand) and takes it in (Index::adopt), then
+    // indexChanged follows. Off again (the process ended): as before.
+    void setExternalIndexer (bool on);
+    bool hasExternalIndexer() const;
+    void reload();
+
     IndexStatus status() const;
 
     // Which folders hold a file `accept` takes (round 164: the Browser's content filter), worked out from the index
@@ -109,6 +117,7 @@ private:
 
     void run();
     void loadIndex();
+    void reloadIndex();
     void runSearch (SearchJob& job);
     bool runPass (Pass& pass); // false: interrupted (a search came in, or closing)
     void saveIndex();
@@ -129,6 +138,7 @@ private:
     mutable std::mutex lock; // guards everything below
     std::condition_variable wake;
     bool stopping = false, working = true; // working: the worker has a job (or is reading the index file)
+    bool external = false, reloadAsked = false; // (round 190hd)
     std::optional<SearchJob> pendingSearch;
     std::uint64_t latestSearch = 0;
     std::deque<Pass> passes;

+ 7 - 4
src/engine/AudioEngine.cpp

@@ -481,11 +481,10 @@ void AudioEngine::openAudioDevice()
     const auto mark = [] (const char* step) { if (startupMark != nullptr) startupMark (step); };
 
     // LYNX ASIO without installation: lynx-asio.dll next to LYNX.exe, when it is not registered (REA round 106)
+    deviceManager.getAvailableDeviceTypes(); // the standard types first (round 190hd: its own trace line)
+    mark ("  engine: standard device types (the prewarmed ASIO device handed over)");
     if (auto lynxAsio = makeBuiltInLynxAsioType())
-    {
-        deviceManager.getAvailableDeviceTypes(); // the standard types first
         deviceManager.addAudioDeviceType (std::move (lynxAsio));
-    }
     // LYNX's own PipeWire client on Linux (round 161), listed when a PipeWire daemon answers
     if (auto pipeWire = makePipeWireDeviceType())
     {
@@ -506,7 +505,11 @@ void AudioEngine::openAudioDevice()
         saved->deleteAllChildElementsWithTagName ("MIDIINPUT");
     }
     auto fresh = saved == nullptr;
-    if (deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty() && saved != nullptr)
+    auto failed = deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty();
+    // (round 190hd) a device made ahead without JUCE's start / stop at init that then failed: once more the usual way
+    if (failed && saved != nullptr && asioPrewarmQuickInit())
+        failed = deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty();
+    if (failed && saved != nullptr)
     {
         deviceManager.initialise (0, 2, nullptr, true);
         fresh = true;

+ 74 - 2
src/engine/DllAsioDevice.cpp

@@ -422,13 +422,22 @@ std::unique_ptr<juce::AudioIODeviceType> makeBuiltInLynxAsioType()
     return makeDllAsioDeviceType (dll.getFullPathName(), lynxAsioTypeName, lynxAsioTypeName);
 }
 
+} // namespace lynx
+
+namespace juce
+{
+extern std::atomic<bool> lynxAsioQuickInit; // cmake/LynxPatchJuce.cmake fix 31
+}
+
+namespace lynx
+{
 namespace
 {
 // The device prewarmAsioDevice makes on its worker, and the JUCE ASIO type that made it (already scanned)
 struct Prewarm
 {
     std::mutex lock;
-    bool started = false, done = false, taken = false;
+    bool started = false, done = false, taken = false, quickInit = false;
     juce::String name, report;
     double startMs = 0.0, doneMs = 0.0;
     std::unique_ptr<juce::AudioIODeviceType> type;
@@ -482,6 +491,41 @@ private:
     juce::String deviceName;
     bool scanned = true;
 };
+// Round 190hd: a device type whose device list was read while the start-up waited for the prewarmed ASIO device (the
+// Windows Audio and DirectSound lists, ~0.1 s, came after that wait, on the start-up's critical path): its first scan
+// is that one; later scans as ever
+class ScannedAheadType final : public juce::AudioIODeviceType,
+                               private juce::AudioIODeviceType::Listener
+{
+public:
+    explicit ScannedAheadType (std::unique_ptr<juce::AudioIODeviceType> inner)
+        : juce::AudioIODeviceType (inner->getTypeName()), type (std::move (inner))
+    {
+        type->scanForDevices();
+        type->addListener (this);
+    }
+    ~ScannedAheadType() override { type->removeListener (this); }
+
+    void scanForDevices() override
+    {
+        if (! std::exchange (scanned, false))
+            type->scanForDevices();
+    }
+    juce::StringArray getDeviceNames (bool wantInputNames) const override { return type->getDeviceNames (wantInputNames); }
+    int getDefaultDeviceIndex (bool forInput) const override { return type->getDefaultDeviceIndex (forInput); }
+    int getIndexOfDevice (juce::AudioIODevice* d, bool asInput) const override { return type->getIndexOfDevice (d, asInput); }
+    bool hasSeparateInputsAndOutputs() const override { return type->hasSeparateInputsAndOutputs(); }
+    juce::AudioIODevice* createDevice (const juce::String& outputDeviceName, const juce::String& inputDeviceName) override
+    {
+        return type->createDevice (outputDeviceName, inputDeviceName);
+    }
+
+private:
+    void audioDeviceListChanged() override { callDeviceChangeListeners(); }
+
+    std::unique_ptr<juce::AudioIODeviceType> type;
+    bool scanned = true;
+};
 } // namespace
 
 void prewarmAsioDevice (const juce::File& savedSetup)
@@ -512,7 +556,15 @@ void prewarmAsioDevice (const juce::File& savedSetup)
         {
             type->scanForDevices();
             if (type->getDeviceNames().contains (name))
+            {
+                // (round 190hd) without JUCE's start / sleep 80 ms / stop at init: ~0.27 s with "FL Studio ASIO"
+                const auto quick = juce::SystemStats::getEnvironmentVariable ("LYNX_ASIO_QUICK_INIT", {}) != "0";
+                juce::lynxAsioQuickInit = quick;
                 device.reset (type->createDevice (name, name)); // (the driver is made and opened on the ASIO thread)
+                juce::lynxAsioQuickInit = false;
+                const std::lock_guard<std::mutex> l (w.lock);
+                w.quickInit = quick && device != nullptr;
+            }
         }
         const std::lock_guard<std::mutex> l (w.lock);
         w.type = std::move (type);
@@ -529,6 +581,13 @@ juce::String asioPrewarmReport()
     return p.report;
 }
 
+bool asioPrewarmQuickInit()
+{
+    auto& p = prewarm();
+    const std::lock_guard<std::mutex> l (p.lock);
+    return p.quickInit && p.taken;
+}
+
 void LynxDeviceManager::createAudioDeviceTypes (juce::OwnedArray<juce::AudioIODeviceType>& types)
 {
     juce::AudioDeviceManager::createAudioDeviceTypes (types);
@@ -536,6 +595,18 @@ void LynxDeviceManager::createAudioDeviceTypes (juce::OwnedArray<juce::AudioIODe
     std::unique_lock<std::mutex> l (p.lock);
     if (! p.started || std::exchange (p.taken, true))
         return;
+    // (round 190hd) the other types' device lists while the ASIO device is still being made (else after it, below)
+    if (! p.done && juce::SystemStats::getEnvironmentVariable ("LYNX_SCAN_AHEAD", {}) != "0")
+    {
+        l.unlock();
+        for (int i = 0; i < types.size(); ++i)
+            if (types[i]->getTypeName() != "ASIO")
+            {
+                std::unique_ptr<juce::AudioIODeviceType> inner (types.removeAndReturn (i)); // (not deleted: handed over)
+                types.insert (i, new ScannedAheadType (std::move (inner)));
+            }
+        l.lock();
+    }
     const auto waitFrom = juce::Time::getMillisecondCounterHiRes();
     // (normally long done: the window was built meanwhile). Messages sent to this thread's windows are answered
     // while it waits: a driver being made on the ASIO thread may send one to JUCE's message window (its init gets it)
@@ -547,7 +618,7 @@ void LynxDeviceManager::createAudioDeviceTypes (juce::OwnedArray<juce::AudioIODe
         PeekMessageW (&m, nullptr, 0, 0, PM_NOREMOVE | PM_QS_SENDMESSAGE);
         l.lock();
     }
-    p.report = "ASIO prewarm: " + p.name + (p.device != nullptr ? " made and opened in " : " not made, ") + juce::String (p.doneMs - p.startMs, 0)
+    p.report = "ASIO prewarm: " + p.name + (p.device != nullptr ? (p.quickInit ? " made (quick init) and opened in " : " made and opened in ") : " not made, ") + juce::String (p.doneMs - p.startMs, 0)
                + " ms, waited " + juce::String (juce::jmax (0.0, juce::Time::getMillisecondCounterHiRes() - waitFrom), 0) + " ms";
     if (p.type == nullptr)
         return;
@@ -568,6 +639,7 @@ std::unique_ptr<juce::AudioIODeviceType> makeDllAsioDeviceType (const juce::Stri
 std::unique_ptr<juce::AudioIODeviceType> makeBuiltInLynxAsioType() { return nullptr; }
 void prewarmAsioDevice (const juce::File&) {}
 juce::String asioPrewarmReport() { return {}; }
+bool asioPrewarmQuickInit() { return false; }
 void LynxDeviceManager::createAudioDeviceTypes (juce::OwnedArray<juce::AudioIODeviceType>& types) { juce::AudioDeviceManager::createAudioDeviceTypes (types); }
 } // namespace lynx
 

+ 3 - 0
src/engine/DllAsioDevice.h

@@ -32,6 +32,9 @@ void prewarmAsioDevice (const juce::File& savedSetup);
 
 // For the start-up trace: what the prewarm gave ("" when there was none)
 juce::String asioPrewarmReport();
+// Round 190hd: the prewarmed device was made without JUCE's start / stop at init (JUCE patch 31; LYNX_ASIO_QUICK_INIT=0:
+// with it). Should it then fail to open, the engine makes it again the usual way.
+bool asioPrewarmQuickInit();
 
 // The device manager of the engine: JUCE's, whose ASIO type hands over the device prewarmAsioDevice made (its first
 // scan is the prewarm's too) and otherwise does what JUCE's does.

+ 288 - 16
src/ui/BrowserComponent.cpp

@@ -29,6 +29,29 @@
 #include "core/ValueMath.h"
 #include "core/Vfx.h"
 #include "platform/Paths.h"
+#include "platform/CrashGuard.h"
+#include "core/FolderWatcher.h"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <thread>
+
+#if JUCE_WINDOWS
+ #ifndef NOMINMAX
+  #define NOMINMAX
+ #endif
+ #ifndef WIN32_LEAN_AND_MEAN
+  #define WIN32_LEAN_AND_MEAN
+ #endif
+ #include <windows.h>
+#else
+ #include <sys/resource.h>
+ #include <unistd.h>
+ #if JUCE_LINUX
+  #include <sys/syscall.h>
+ #endif
+#endif
 
 #include <mutex>
 #include "engine/PluginHost.h"
@@ -256,6 +279,235 @@ DraggedPlugin& draggedPlugin()
 
 // --- search: the process's search worker ------------------------------------------------------------
 
+// Round 190hd: the indexer process (REA 190hc action 5, parts 2-3, after Live's Indexer: "StartIndex" runs the library
+// indexer as a separate process at a low priority and rescans on file-system events). The Browser's index of its
+// folders (core/SearchIndex.h) is kept up to date by `LYNX --browser-indexer <pid> <roots file>`: a child at the
+// lowest priority (Windows: idle class + background mode, so its disk reads are low priority too; elsewhere nice 19
+// and, on Linux, the idle I/O class) that walks the folders whose times changed, writes the index file, tells this
+// process, and then sleeps on the system's change notifications for those trees (core/FolderWatcher.h) until the
+// next change. It never shares a thread, a lock or a frame with the UI; it ends with its parent. This process then
+// saves nothing and only takes in what the child wrote (search::Service::setExternalIndexer / reload). A child that
+// cannot start or ends: the in-process pass as before.
+namespace
+{
+juce::File indexFile() { return platform::settingsFile ("browser-index.txt"); }
+juce::File indexRootsFile() { return platform::settingsFile ("browser-index-roots.txt"); }
+
+std::string loadIndexText()
+{
+    const auto f = indexFile();
+    juce::MemoryBlock data;
+    if (! f.existsAsFile() || f.getSize() > 256 * 1024 * 1024 || ! f.loadFileAsData (data))
+        return std::string();
+    return std::string (static_cast<const char*> (data.getData()), data.getSize());
+}
+
+void saveIndexText (const std::string& text)
+{
+    const auto f = indexFile();
+    const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
+    if (temp.replaceWithData (text.data(), text.size()))
+        temp.moveFileTo (f);
+}
+
+#if JUCE_WINDOWS
+juce::String indexerSignalName (juce::int64 parentPid) { return "Local\\LYNX-browser-index-" + juce::String (parentPid); }
+#endif
+
+juce::int64 thisProcessId()
+{
+#if JUCE_WINDOWS
+    return (juce::int64) GetCurrentProcessId();
+#else
+    return (juce::int64) getpid();
+#endif
+}
+
+class IndexerProcess
+{
+public:
+    explicit IndexerProcess (search::Service& s) : service (s) {}
+    ~IndexerProcess() { stop(); }
+
+    // starts the child for these folders (once; again when they change); false: it could not start
+    bool start (const std::vector<std::string>& folders)
+    {
+        if (watcher.joinable() && folders == roots && child.isRunning())
+            return true;
+        stop();
+        roots = folders;
+        juce::StringArray lines;
+        for (const auto& r : roots)
+            lines.add (juce::String::fromUTF8 (r.c_str()));
+        if (! indexRootsFile().replaceWithText (lines.joinIntoString ("\n") + "\n"))
+            return false;
+       #if JUCE_WINDOWS
+        signal = CreateEventW (nullptr, FALSE, FALSE, indexerSignalName (thisProcessId()).toWideCharPointer());
+        if (signal == nullptr)
+            return false;
+       #endif
+        const juce::StringArray args { juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName(), "--browser-indexer",
+                                       juce::String (thisProcessId()), indexRootsFile().getFullPathName() };
+       #if JUCE_WINDOWS
+        const auto started = child.start (args, 0);
+       #else
+        const auto started = child.start (args, juce::ChildProcess::wantStdOut);
+       #endif
+        if (! started)
+        {
+            closeSignal();
+            return false;
+        }
+        service.setExternalIndexer (true);
+        stopping = false;
+        watcher = std::thread ([this] { watch(); });
+        return true;
+    }
+
+    void stop()
+    {
+        stopping = true;
+        if (child.isRunning())
+            child.kill(); // (our own child; a write it was making is a temporary file, replaced by the next)
+       #if JUCE_WINDOWS
+        if (signal != nullptr)
+            SetEvent (signal);
+       #endif
+        if (watcher.joinable())
+            watcher.join();
+        closeSignal();
+        service.setExternalIndexer (false);
+    }
+
+private:
+    // (its own thread) the child's news: the index file was written
+    void watch()
+    {
+        for (;;)
+        {
+           #if JUCE_WINDOWS
+            const auto woken = WaitForSingleObject (signal, 2000) == WAIT_OBJECT_0;
+            if (stopping)
+                return;
+            if (woken)
+                service.reload();
+            if (child.isRunning())
+                continue;
+           #else
+            char c = 0;
+            if (child.readProcessOutput (&c, 1) == 1) // (blocks; one byte at a time: a line is a write)
+            {
+                if (c == '\n')
+                    service.reload();
+                continue;
+            }
+            if (stopping)
+                return;
+           #endif
+            // the child ended on its own (a crash): this process indexes again, as before
+            service.setExternalIndexer (false);
+            service.refresh (roots);
+            return;
+        }
+    }
+
+    void closeSignal()
+    {
+       #if JUCE_WINDOWS
+        if (signal != nullptr)
+            CloseHandle (signal);
+        signal = nullptr;
+       #endif
+    }
+
+    search::Service& service;
+    juce::ChildProcess child;
+    std::vector<std::string> roots;
+    std::atomic<bool> stopping { false };
+   #if JUCE_WINDOWS
+    HANDLE signal = nullptr;
+   #endif
+    std::thread watcher;
+};
+
+// (the child) the lowest priority for the CPU and the disk
+void lowerIndexerPriority()
+{
+#if JUCE_WINDOWS
+    // background mode first (low disk and memory priority), then the idle class (the order: setting background mode
+    // left the class at Normal, measured)
+    SetPriorityClass (GetCurrentProcess(), PROCESS_MODE_BACKGROUND_BEGIN);
+    SetPriorityClass (GetCurrentProcess(), IDLE_PRIORITY_CLASS);
+#else
+    setpriority (PRIO_PROCESS, 0, 19);
+ #if JUCE_LINUX
+    syscall (SYS_ioprio_set, 1 /* IOPRIO_WHO_PROCESS */, 0, 3 << 13 /* IOPRIO_CLASS_IDLE */);
+ #endif
+#endif
+}
+
+// (the child) returns when the parent process has ended
+void waitForParentEnd (juce::int64 parentPid)
+{
+#if JUCE_WINDOWS
+    if (const auto parent = OpenProcess (SYNCHRONIZE, FALSE, (DWORD) parentPid))
+    {
+        WaitForSingleObject (parent, INFINITE);
+        CloseHandle (parent);
+    }
+#else
+    while (getppid() == (pid_t) parentPid)
+        std::this_thread::sleep_for (std::chrono::seconds (2));
+#endif
+}
+} // namespace
+
+int BrowserComponent::runIndexerProcess (const juce::StringArray& args)
+{
+    const auto i = args.indexOf ("--browser-indexer");
+    const auto parentPid = args[i + 1].getLargeIntValue();
+    const juce::File rootsFile (args[i + 2].unquoted());
+    lowerIndexerPriority();
+    std::thread ([parentPid] {
+        waitForParentEnd (parentPid);
+        crashguard::exitNow (0);
+    }).detach();
+
+    std::vector<std::string> roots;
+    juce::StringArray lines;
+    lines.addLines (rootsFile.loadFileAsString());
+    for (const auto& line : lines)
+        if (line.isNotEmpty() && juce::File::isAbsolutePath (line) && juce::File (line).isDirectory())
+            roots.push_back (line.toStdString());
+
+#if JUCE_WINDOWS
+    const auto signal = OpenEventW (EVENT_MODIFY_STATE, FALSE, indexerSignalName (parentPid).toWideCharPointer());
+#endif
+    search::Service::Callbacks cb;
+    cb.load = loadIndexText;
+    cb.save = saveIndexText;
+    cb.indexChanged = [&] { // (the file is written by then)
+#if JUCE_WINDOWS
+        if (signal != nullptr)
+            SetEvent (signal);
+#else
+        std::fputs ("changed\n", stdout);
+        std::fflush (stdout);
+#endif
+    };
+    search::Service service (diskFileSystem(), std::move (cb));
+    if (! roots.empty())
+        service.refresh (roots);
+    // then a pass after each change in those trees (a copy of a whole library: once it has been quiet for 2 s)
+    folderwatch::Options options;
+    options.quietMs = 2000;
+    options.maxDelayMs = 10000;
+    options.pollMs = 30000; // (where there are no notifications: a tree's folder times, every 30 s)
+    folderwatch::Watcher watcher (roots, [&service, roots] { service.refresh (roots); }, options);
+    for (;;)
+        std::this_thread::sleep_for (std::chrono::hours (1)); // (ends with the parent: waitForParentEnd)
+}
+
 // The Browser's search index and its worker (core/SearchService.h, round 162): one per process while a Browser exists,
 // the index kept in the settings folder between sessions. Its news reach the Browsers through two broadcasters (they
 // are thread-safe and coalesce); the worker is joined (never killed) before they go.
@@ -263,10 +515,28 @@ struct BrowserComponent::SearchShared
 {
     juce::ChangeBroadcaster statusChanged, indexChanged;
     std::unique_ptr<search::Service> service; // (last: goes first)
+    std::unique_ptr<IndexerProcess> indexer;  // (round 190hd; before the service)
 
-    ~SearchShared() { service.reset(); }
+    ~SearchShared()
+    {
+        indexer.reset();
+        service.reset();
+    }
 
-    static juce::File file() { return platform::settingsFile ("browser-index.txt"); }
+    static juce::File file() { return indexFile(); }
+
+    // the background pass over these folders: by the indexer process where it may run, else here (round 190hd)
+    void refreshInBackground (std::vector<std::string> roots)
+    {
+        if (allowIndexerProcess && juce::SystemStats::getEnvironmentVariable ("LYNX_INDEXER_PROCESS", {}) != "0")
+        {
+            if (indexer == nullptr)
+                indexer = std::make_unique<IndexerProcess> (*service);
+            if (indexer->start (roots))
+                return;
+        }
+        service->refresh (std::move (roots));
+    }
 
     static std::shared_ptr<SearchShared> get()
     {
@@ -275,19 +545,8 @@ struct BrowserComponent::SearchShared
             return s;
         auto s = std::make_shared<SearchShared>();
         search::Service::Callbacks cb;
-        cb.load = [] {
-            const auto f = file();
-            juce::MemoryBlock data;
-            if (! f.existsAsFile() || f.getSize() > 256 * 1024 * 1024 || ! f.loadFileAsData (data))
-                return std::string();
-            return std::string (static_cast<const char*> (data.getData()), data.getSize());
-        };
-        cb.save = [] (const std::string& text) {
-            const auto f = file();
-            const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
-            if (temp.replaceWithData (text.data(), text.size()))
-                temp.moveFileTo (f);
-        };
+        cb.load = loadIndexText;
+        cb.save = saveIndexText;
         cb.statusChanged = [raw = s.get()] { raw->statusChanged.sendChangeMessage(); };
         cb.indexChanged = [raw = s.get()] { raw->indexChanged.sendChangeMessage(); };
         s->service = std::make_unique<search::Service> (diskFileSystem(), std::move (cb));
@@ -2852,7 +3111,7 @@ BrowserComponent::BrowserComponent (AudioEngine& e, Role r)
     searcher->indexChanged.addChangeListener (this);
     juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
         if (safe != nullptr && safe->role == Role::main && ! safe->allRoots.isEmpty())
-            safe->searcher->service->refresh (toPaths (safe->withMerged (safe->allRoots)));
+            safe->searcher->refreshInBackground (toPaths (safe->withMerged (safe->allRoots))); // (round 190hd: the indexer process)
     });
     // "Find similar samples" (round 190as): once it was used (its index file exists), the folders are checked for new
     // samples in the background a while after start; before that nothing is analysed
@@ -2928,8 +3187,17 @@ BrowserComponent::BrowserComponent (AudioEngine& e, Role r)
     details = std::make_unique<DetailsBox>();
     addChildComponent (*details);
 
+    browserStartupMark ("  browser: search index, widgets");
     rebuildRoots();
+    browserStartupMark ("  browser: roots and tree");
     engine.addChangeListener (this);
+    constructing = false;
+}
+
+void BrowserComponent::browserStartupMark (const char* step) const
+{
+    if (constructing && role == Role::main && startupMark != nullptr)
+        startupMark (step);
 }
 
 juce::File BrowserComponent::userFoldersFile()
@@ -4126,7 +4394,11 @@ void BrowserComponent::rebuildTree()
     // FL's Plugin database, under the project (round 142); always while hot-swap is on (round 190ce: it is what the
     // linked device is replaced from, also when the user's view leaves it out)
     if (tab == allTab && (view.shows (browserview::pluginsRootId) || swapSession.active()))
+    {
+        browserStartupMark ("  browser: roots (FL folders, user folders, view, collections)");
         top.push_back (FileTree::makePluginDatabase (*this, openPluginFolders));
+        browserStartupMark ("  browser: the Plugin database tree");
+    }
 
     if (tab == allTab)
         for (int i = 0; i < allRoots.size(); ++i)

+ 11 - 0
src/ui/BrowserComponent.h

@@ -85,6 +85,17 @@ public:
     static std::unique_ptr<juce::Component> makeSampleBrowserContent (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire);
     // Whether the Sample browser was open when LYNX last closed (its view file).
     static bool sampleBrowserWasOpen();
+    // Round 190hd: the Browser's search index kept up to date by a low-priority child process (LYNX --browser-indexer
+    // <parent pid> <roots file>) woken by file-system changes, as Live's Indexer. Main allows it for the normal window
+    // only (command-line modes and tests index in-process, as before); LYNX_INDEXER_PROCESS=0 turns it off.
+    static inline bool allowIndexerProcess = false;
+    static int runIndexerProcess (const juce::StringArray& args); // the child: never returns while its parent lives
+
+private:
+    bool constructing = true; // (round 190hd: the start-up trace's lines of the main Browser's construction)
+    void browserStartupMark (const char* step) const;
+
+public:
     static juce::Rectangle<int> sampleBrowserBounds(); // its last window bounds (empty: default)
 
     std::function<void (const juce::File&)> onOpenProject;

+ 11 - 0
src/ui/MainComponent.h

@@ -699,12 +699,21 @@ private:
     bool hintsFrozen = false; // --snapshot: keep the hint that was set
     juce::String idleHint() const;
 
+    // (round 190hd) a line of the start-up trace when made: where the main window's construction goes
+    struct StartupStep
+    {
+        explicit StartupStep (const char* step) { if (startupMark != nullptr) startupMark (step); }
+    };
+    StartupStep stepMembers { "  window: toolbar and the other members" };
     ChannelRackComponent rack;
     ChannelRackViewport rackViewport { rack };
+    StartupStep stepRack { "  window: channel rack" };
     PianoRollComponent pianoRoll;
+    StartupStep stepPianoRoll { "  window: piano roll" };
     PlaylistComponent playlist;
     PatternPicker picker { engine, playlist };
     PlaylistArea playlistArea { picker, playlist };
+    StartupStep stepPlaylist { "  window: playlist" };
     layoutstyle::Style layoutStyle = layoutstyle::Style::pattern;
     layoutstyle::SettingsReader startStyle; // the style saved in the UI settings (applied when the window is ready)
     // round 190ch: the docked Lyrics / Notes panel (made when first shown) and the ones living in tool windows
@@ -758,7 +767,9 @@ private:
     bool runDetailAction (const std::string& id);
     void openGridClip (int track, int scene);
     MixerComponent mixer;
+    StartupStep stepMixer { "  window: mixer" };
     BrowserComponent browser;
+    StartupStep stepBrowser { "  window: browser" };
     Workspace workspace; // after the panels' contents: it is destroyed first
     updater::UpdateBar updateBar; // "LYNX SHARE x.y.z is available" under the toolbar (round 166b)
     juce::Label remoteControlBar;

+ 492 - 14
src/ui/Splash.cpp

@@ -1,11 +1,30 @@
 #include "ui/Splash.h"
 
+#include <atomic>
+#include <mutex>
+#include <optional>
+#include <thread>
+
 #include "core/StartupSound.h"
 #include "engine/PluginHost.h"
 #include "ui/I18n.h"
 #include "ui/Theme.h"
 #include "ui/WindowOwner.h"
 
+#include <cstring>
+
+#if JUCE_WINDOWS
+ #ifndef NOMINMAX
+  #define NOMINMAX
+ #endif
+ #ifndef WIN32_LEAN_AND_MEAN
+  #define WIN32_LEAN_AND_MEAN
+ #endif
+ #include <windows.h>
+ #undef near // (windows.h; the drawing below has a variable of that name)
+ #undef far
+#endif
+
 namespace lynx
 {
 namespace
@@ -173,8 +192,6 @@ void SplashScreen::timerCallback()
 
 void SplashScreen::paint (juce::Graphics& g)
 {
-    using namespace theme;
-    const auto t = time;
     if (clockStartMs >= 0.0 && fadeStartMs < 0.0) // (the drop's frames: see getDropFrames)
     {
         const auto now = juce::Time::getMillisecondCounterHiRes();
@@ -186,7 +203,43 @@ void SplashScreen::paint (juce::Graphics& g)
         }
         lastDropPaintMs = now;
     }
-    const auto card = getLocalBounds().toFloat().reduced (0.5f);
+
+    SplashFrame frame;
+    frame.t = time;
+    frame.barDuration = barDuration;
+    frame.status = status;
+    frame.subtitle = tr ("Digital audio workstation");
+    frame.version = tr ("Version {0}", { JUCE_APPLICATION_VERSION_STRING });
+    frame.logo = &logoMark;
+    drawSplashFrame (g, frame);
+
+    if (auto first = std::exchange (onFirstFrame, nullptr))
+    {
+        firstFrameTime = std::chrono::steady_clock::now();
+        juce::MessageManager::callAsync (std::move (first)); // (after this frame is on the screen)
+    }
+}
+
+std::array<juce::Font, 4> makeSplashFonts()
+{
+    std::array<juce::Font, 4> fonts { juce::Font (juce::FontOptions (78.0f, juce::Font::bold)), juce::Font (juce::FontOptions (30.0f, juce::Font::bold)),
+                                      juce::Font (theme::font (theme::type::title)), juce::Font (theme::font (theme::type::small)) };
+    for (auto& f : fonts)
+        f.getTypefacePtr(); // (looked up here, once)
+    return fonts;
+}
+
+void drawSplashFrame (juce::Graphics& g, const SplashFrame& frame)
+{
+    using namespace theme;
+    const auto t = frame.t;
+    std::optional<std::array<juce::Font, 4>> made;
+    if (frame.fonts == nullptr)
+        made = makeSplashFonts();
+    const auto* fonts = frame.fonts != nullptr ? frame.fonts : made->data();
+    const juce::Image noLogo; // (an empty image: nothing to free)
+    const auto& logoMark = frame.logo != nullptr ? *frame.logo : noLogo;
+    const auto card = juce::Rectangle<float> (0.0f, 0.0f, (float) SplashScreen::width, (float) SplashScreen::height).reduced (0.5f);
     juce::Path cardShape;
     cardShape.addRoundedRectangle (card, 14.0f);
 
@@ -251,8 +304,8 @@ void SplashScreen::paint (juce::Graphics& g)
     // width; the letters slide in one after another
     {
         const juce::String word ("LYNX"), word2 ("SHARE");
-        const juce::Font big (juce::FontOptions (78.0f, juce::Font::bold));
-        const juce::Font small (juce::FontOptions (30.0f, juce::Font::bold));
+        const auto& big = fonts[0];
+        const auto& small = fonts[1];
         const auto left = 300.0f;
         const auto baseline = 150.0f, baseline2 = 188.0f;
 
@@ -296,11 +349,11 @@ void SplashScreen::paint (juce::Graphics& g)
         if (info > 0.0f)
         {
             g.setColour (colour::textSecondary.withAlpha (info));
-            g.setFont (font (type::title));
-            g.drawText (tr ("Digital audio workstation"), 302, (int) baseline2 + 24, 240, 22, juce::Justification::centredLeft);
+            g.setFont (fonts[2]);
+            g.drawText (frame.subtitle, 302, (int) baseline2 + 24, 240, 22, juce::Justification::centredLeft);
             g.setColour (colour::textDisabled.withAlpha (info));
-            g.setFont (font (type::small));
-            g.drawText (tr ("Version {0}", { JUCE_APPLICATION_VERSION_STRING }), 302, (int) baseline2 + 48, 240, 18, juce::Justification::centredLeft);
+            g.setFont (fonts[3]);
+            g.drawText (frame.version, 302, (int) baseline2 + 48, 240, 18, juce::Justification::centredLeft);
         }
     }
 
@@ -310,17 +363,442 @@ void SplashScreen::paint (juce::Graphics& g)
         g.setColour (colour::bg4);
         g.fillRoundedRectangle (bar, 1.5f);
         g.setColour (colour::accent);
-        g.fillRoundedRectangle (bar.withWidth (bar.getWidth() * (float) easeOutCubic (juce::jmin (1.0, t / juce::jmax (0.1, barDuration)))), 1.5f);
+        g.fillRoundedRectangle (bar.withWidth (bar.getWidth() * (float) easeOutCubic (juce::jmin (1.0, t / juce::jmax (0.1, frame.barDuration)))), 1.5f);
         g.setColour (colour::textDisabled);
-        g.setFont (font (type::small));
-        g.drawText (status, juce::Rectangle<float> (24.0f, bar.getY() - 24.0f, card.getWidth() - 48.0f, 18.0f), juce::Justification::centredLeft);
+        g.setFont (fonts[3]);
+        g.drawText (frame.status, juce::Rectangle<float> (24.0f, bar.getY() - 24.0f, card.getWidth() - 48.0f, 18.0f), juce::Justification::centredLeft);
     }
 
     // hairline border on top of everything
     g.setColour (colour::borderStrong);
     g.strokePath (cardShape, juce::PathStrokeType (1.0f));
+}
+// --- the card on a thread of its own (Windows, round 190hd) --------------------------------------
+//
+// The card was a JUCE window on the message thread: the start-up could not build the main window or open the audio
+// device while the logo dropped (each would stop the drop), and its logo was the process's first Direct2D image, so
+// the Direct3D 11 + Direct2D device (~0.35-0.4 s) was made before the card could show. Here the same drawing
+// (drawSplashFrame) runs on a thread of its own with the CPU (JUCE's software renderer, JUCE patch 30: no Direct2D
+// image on this thread) into a layered window of its own (UpdateLayeredWindow, as JUCE's own transparent windows do
+// without Direct2D): the card shows within a few tens of milliseconds and its 60 frames a second no longer depend on
+// what the message thread does. Same size, place, drop, timing and fade as the JUCE card. LYNX_SPLASH_THREAD=0: the
+// JUCE card.
+#if JUCE_WINDOWS
+} // namespace lynx
 
-    if (auto first = std::exchange (onFirstFrame, nullptr))
-        juce::MessageManager::callAsync (std::move (first)); // (after this frame is on the screen)
+namespace juce
+{
+void lynxSoftwareImagesOnThisThread (bool on); // cmake/LynxPatchJuce.cmake fix 30
+}
+
+namespace lynx
+{
+namespace
+{
+double steadySeconds()
+{
+    return std::chrono::duration<double> (std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+class ThreadedSplash final : public StartupSplash
+{
+public:
+    ThreadedSplash()
+        : fonts (makeSplashFonts()),
+          subtitle (tr ("Digital audio workstation")),
+          version (tr ("Version {0}", { JUCE_APPLICATION_VERSION_STRING })),
+          dropStatus (tr ("Loading the workspace...")),
+          status (tr ("Starting the audio engine..."))
+    {
+        wake = CreateEventW (nullptr, FALSE, FALSE, nullptr);
+    }
+
+    ~ThreadedSplash() override
+    {
+        quit = true;
+        if (wake != nullptr)
+            SetEvent (wake);
+        if (thread.joinable())
+            thread.join();
+        if (wake != nullptr)
+            CloseHandle (wake);
+    }
+
+    void showOnDesktop() override
+    {
+        if (! thread.joinable())
+            thread = std::thread ([this] { run(); });
+    }
+
+    void startClock() override { clockStart.store (steadySeconds()); }
+
+    double getElapsed() const override
+    {
+        const auto start = clockStart.load();
+        return start < 0.0 ? 0.0 : steadySeconds() - start;
+    }
+
+    void setStatus (const juce::String& text) override
+    {
+        const std::scoped_lock hold (lock);
+        status = text;
+    }
+
+    void setBarDuration (double seconds) override { barDuration.store (seconds); }
+
+    void raise() override
+    {
+        raiseAsked = true;
+        SetEvent (wake);
+    }
+
+    void finish (std::function<void()> whenGone) override
+    {
+        {
+            const std::scoped_lock hold (lock);
+            onGone = std::move (whenGone);
+        }
+        fadeStart.store (steadySeconds());
+        SetEvent (wake);
+    }
+
+    int getDropFrames() const override { return dropFrames.load(); }
+    double getLongestDropGapMs() const override { return longestDropGapMs.load(); }
+
+    std::chrono::steady_clock::time_point getFirstFrameTime() const override
+    {
+        return std::chrono::steady_clock::time_point (std::chrono::steady_clock::duration (firstFrameTicks.load()));
+    }
+
+    bool drawsOnItsOwnThread() const override { return true; }
+
+    void whenLanded (double seconds, std::function<void()> then) override
+    {
+        {
+            const std::scoped_lock hold (lock);
+            onLanded = std::move (then);
+        }
+        landingAt.store (seconds);
+    }
+
+    double getLongestDropGapAt() const override { return longestDropGapAt.load(); }
+
+    juce::String getLongestDropGapDetail() const override
+    {
+        const std::scoped_lock hold (lock);
+        return longestGapDetail;
+    }
+
+private:
+    // runs `f` on the message thread unless this card is gone by then (it is deleted there)
+    void post (std::function<void (ThreadedSplash&)> f)
+    {
+        juce::MessageManager::callAsync ([weak = std::weak_ptr<int> (alive), self = this, f = std::move (f)] {
+            if (! weak.expired())
+                f (*self);
+        });
+    }
+
+    void run()
+    {
+        juce::lynxSoftwareImagesOnThisThread (true);
+        SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
+        // its window in physical pixels, like JUCE's (per-monitor DPI awareness)
+        using SetContext = HANDLE (WINAPI*) (HANDLE);
+        if (auto* user32 = GetModuleHandleW (L"user32.dll"))
+            if (auto set = reinterpret_cast<SetContext> (reinterpret_cast<void*> (GetProcAddress (user32, "SetThreadDpiAwarenessContext"))))
+                set (reinterpret_cast<HANDLE> (static_cast<std::intptr_t> (-4))); // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
+
+        const auto logo = decodeLogoImage();
+
+        // centred in the main display's work area (JUCE's card: the primary display's user area)
+        const auto monitor = MonitorFromPoint (POINT { 0, 0 }, MONITOR_DEFAULTTOPRIMARY);
+        MONITORINFO info {};
+        info.cbSize = sizeof (info);
+        GetMonitorInfoW (monitor, &info);
+        UINT dpiX = 96, dpiY = 96;
+        using GetDpi = HRESULT (WINAPI*) (HMONITOR, int, UINT*, UINT*);
+        if (auto* shcore = LoadLibraryW (L"shcore.dll"))
+            if (auto get = reinterpret_cast<GetDpi> (reinterpret_cast<void*> (GetProcAddress (shcore, "GetDpiForMonitor"))))
+                if (FAILED (get (monitor, 0 /* MDT_EFFECTIVE_DPI */, &dpiX, &dpiY)))
+                    dpiX = 96;
+        const auto scale = juce::jmax (1.0, (double) dpiX / 96.0);
+        const auto w = juce::roundToInt (SplashScreen::width * scale), h = juce::roundToInt (SplashScreen::height * scale);
+        const auto& work = info.rcWork;
+        const auto x = (work.left + work.right) / 2 - w / 2, y = (work.top + work.bottom) / 2 - h / 2;
+
+        const auto instance = GetModuleHandleW (nullptr);
+        WNDCLASSEXW windowClass {};
+        windowClass.cbSize = sizeof (windowClass);
+        windowClass.lpfnWndProc = DefWindowProcW;
+        windowClass.hInstance = instance;
+        windowClass.hCursor = LoadCursorW (nullptr, MAKEINTRESOURCEW (32512)); // (IDC_ARROW)
+        windowClass.lpszClassName = L"LYNXSplashCard";
+        RegisterClassExW (&windowClass);
+        // no title (nothing looks for it), no taskbar entry, never activated
+        const auto window = CreateWindowExW (WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, windowClass.lpszClassName, L"",
+                                             WS_POPUP, x, y, w, h, nullptr, nullptr, instance, nullptr);
+
+        BITMAPINFO bitmapInfo {};
+        bitmapInfo.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
+        bitmapInfo.bmiHeader.biWidth = w;
+        bitmapInfo.bmiHeader.biHeight = -h; // (top-down)
+        bitmapInfo.bmiHeader.biPlanes = 1;
+        bitmapInfo.bmiHeader.biBitCount = 32;
+        bitmapInfo.bmiHeader.biCompression = BI_RGB;
+        void* bits = nullptr;
+        const auto dib = window != nullptr ? CreateDIBSection (nullptr, &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0) : nullptr;
+        const auto memoryDc = CreateCompatibleDC (nullptr);
+        const auto oldBitmap = dib != nullptr ? SelectObject (memoryDc, dib) : nullptr;
+        // (high resolution where Windows has it: 60 frames a second on the dot)
+        auto timer = CreateWaitableTimerExW (nullptr, nullptr, 0x00000002 /* CREATE_WAITABLE_TIMER_HIGH_RESOLUTION */, TIMER_ALL_ACCESS);
+        if (timer == nullptr)
+            timer = CreateWaitableTimerW (nullptr, FALSE, nullptr);
+
+        if (window == nullptr || dib == nullptr || bits == nullptr)
+        {
+            // (no card: the start-up goes on all the same)
+            firstFrameTicks.store (std::chrono::steady_clock::now().time_since_epoch().count());
+            post ([] (ThreadedSplash& s) { if (auto first = std::exchange (s.onFirstFrame, nullptr)) first(); });
+            while (! quit && fadeStart.load() < 0.0)
+                WaitForSingleObject (wake, 50);
+            if (! quit)
+                post ([] (ThreadedSplash& s) { s.gone(); });
+            cleanUp (window, memoryDc, oldBitmap, dib, timer);
+            return;
+        }
+
+        juce::Image frame (juce::Image::ARGB, w, h, true, juce::SoftwareImageType());
+        // every glyph the card will draw, once, before its first frame (an outline looked up mid-drop waited for the
+        // font system while the message thread loaded the window's fonts: a frame of ~0.1 s)
+        {
+            SplashFrame warm;
+            warm.t = 1.6;
+            warm.status = dropStatus + " " + status;
+            warm.subtitle = subtitle;
+            warm.version = version;
+            warm.logo = &logo;
+            warm.fonts = fonts.data();
+            juce::Graphics g (frame);
+            g.addTransform (juce::AffineTransform::scale ((float) scale));
+            drawSplashFrame (g, warm);
+        }
+        constexpr double period = 1.0 / 60.0;
+        auto next = steadySeconds();
+        auto shown = false, faded = false;
+        auto lastDropPaint = -1.0;
+
+        while (! quit)
+        {
+            const auto now = steadySeconds();
+            const auto start = clockStart.load(), fade = fadeStart.load();
+            const auto t = start < 0.0 ? 0.0 : now - start;
+            auto alpha = 1.0;
+            if (fade >= 0.0)
+            {
+                const auto f = (now - fade) / SplashScreen::fadeOutTime;
+                alpha = 1.0 - clamp01 (f);
+                if (f >= 1.0)
+                {
+                    faded = true;
+                    break;
+                }
+            }
+            if (start >= 0.0 && fade < 0.0 && t <= 1.05) // (the drop's frames, as the JUCE card counts them)
+            {
+                if (lastDropPaint >= 0.0 && (now - lastDropPaint) * 1000.0 > longestDropGapMs.load())
+                {
+                    longestDropGapMs.store ((now - lastDropPaint) * 1000.0);
+                    longestDropGapAt.store (t);
+                    const std::scoped_lock hold (lock); // (what the frame before it spent its time on)
+                    longestGapDetail = "draw " + juce::String (spent[0], 1) + " ms, show " + juce::String (spent[1], 1) + " ms, messages "
+                                       + juce::String (spent[2], 1) + " ms, wait " + juce::String (spent[3], 1) + " ms";
+                }
+                ++dropFrames;
+                lastDropPaint = now;
+            }
+            if (const auto landing = landingAt.load(); start >= 0.0 && landing >= 0.0 && t >= landing)
+            {
+                landingAt.store (-1.0);
+                post ([] (ThreadedSplash& s) {
+                    std::function<void()> then;
+                    {
+                        const std::scoped_lock hold (s.lock);
+                        then = std::move (s.onLanded);
+                    }
+                    if (then)
+                        then(); // (may delete this card)
+                });
+            }
+
+            auto mark = steadySeconds();
+            const auto lap = [&mark] (double& into) { const auto n = steadySeconds(); into = (n - mark) * 1000.0; mark = n; };
+            SplashFrame look;
+            look.t = t;
+            look.barDuration = barDuration.load();
+            {
+                const std::scoped_lock hold (lock);
+                look.status = status;
+            }
+            look.subtitle = subtitle;
+            look.version = version;
+            look.logo = &logo;
+            look.fonts = fonts.data();
+            frame.clear (frame.getBounds());
+            {
+                juce::Graphics g (frame);
+                g.addTransform (juce::AffineTransform::scale ((float) scale));
+                drawSplashFrame (g, look);
+            }
+            {
+                const juce::Image::BitmapData pixels (frame, juce::Image::BitmapData::readOnly);
+                for (int row = 0; row < h; ++row) // (premultiplied BGRA, as UpdateLayeredWindow wants)
+                    std::memcpy (static_cast<std::uint8_t*> (bits) + (std::size_t) row * (std::size_t) w * 4, pixels.getLinePointer (row), (std::size_t) w * 4);
+            }
+            lap (spent[0]);
+            POINT source { 0, 0 }, place { x, y };
+            SIZE size { w, h };
+            BLENDFUNCTION blend { AC_SRC_OVER, 0, (BYTE) juce::roundToInt (alpha * 255.0), AC_SRC_ALPHA };
+            UpdateLayeredWindow (window, nullptr, &place, &size, memoryDc, &source, 0, &blend, ULW_ALPHA);
+            if (raiseAsked.exchange (false))
+                SetWindowPos (window, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+            if (! std::exchange (shown, true))
+            {
+                ShowWindow (window, SW_SHOWNOACTIVATE);
+                firstFrameTicks.store (std::chrono::steady_clock::now().time_since_epoch().count());
+                post ([] (ThreadedSplash& s) { if (auto first = std::exchange (s.onFirstFrame, nullptr)) first(); });
+            }
+            lap (spent[1]);
+
+            MSG message;
+            while (PeekMessageW (&message, nullptr, 0, 0, PM_REMOVE))
+            {
+                TranslateMessage (&message);
+                DispatchMessageW (&message);
+            }
+            lap (spent[2]);
+
+            // the next tick of a 60 Hz clock (a tick missed is skipped, as JUCE's timer does)
+            next += period;
+            const auto later = steadySeconds();
+            while (next <= later)
+                next += period;
+            LARGE_INTEGER due;
+            due.QuadPart = -juce::jmax ((LONGLONG) 1, (LONGLONG) ((next - later) * 1.0e7)); // (relative, 100 ns units)
+            // (the timeout: the tick plus a little, in case the timer never signals; never a long wait)
+            const auto timeoutMs = (DWORD) juce::jmax (1, (int) std::ceil ((next - later) * 1000.0) + 2);
+            if (timer != nullptr && SetWaitableTimer (timer, &due, 0, nullptr, nullptr, FALSE))
+            {
+                const HANDLE waitFor[] = { timer, wake };
+                MsgWaitForMultipleObjects (2, waitFor, FALSE, timeoutMs, QS_ALLINPUT);
+            }
+            else
+            {
+                MsgWaitForMultipleObjects (1, &wake, FALSE, timeoutMs, QS_ALLINPUT);
+            }
+            lap (spent[3]);
+        }
+
+        ShowWindow (window, SW_HIDE);
+        cleanUp (window, memoryDc, oldBitmap, dib, timer);
+        if (faded && ! quit)
+            post ([] (ThreadedSplash& s) { s.gone(); });
+    }
+
+    static void cleanUp (HWND window, HDC memoryDc, HGDIOBJ oldBitmap, HBITMAP dib, HANDLE timer)
+    {
+        if (window != nullptr)
+            DestroyWindow (window);
+        if (oldBitmap != nullptr)
+            SelectObject (memoryDc, oldBitmap);
+        if (dib != nullptr)
+            DeleteObject (dib);
+        if (memoryDc != nullptr)
+            DeleteDC (memoryDc);
+        if (timer != nullptr)
+            CloseHandle (timer);
+    }
+
+    // (message thread) the fade has ended
+    void gone()
+    {
+        std::function<void()> then;
+        {
+            const std::scoped_lock hold (lock);
+            then = std::move (onGone);
+        }
+        if (then)
+            then(); // (may delete this card)
+    }
+
+    const std::array<juce::Font, 4> fonts;
+    const juce::String subtitle, version, dropStatus;
+    mutable std::mutex lock; // guards status, onGone, onLanded and longestGapDetail
+    juce::String status;
+    std::function<void()> onGone, onLanded;
+    std::atomic<double> landingAt { -1.0 }, longestDropGapAt { -1.0 };
+    double spent[4] {}; // (the splash thread) the last frame's draw, show, messages, wait, ms
+    juce::String longestGapDetail; // (guarded by lock)
+    std::atomic<double> clockStart { -1.0 }, fadeStart { -1.0 }, barDuration { SplashScreen::minimumDuration };
+    std::atomic<bool> quit { false }, raiseAsked { false };
+    std::atomic<int> dropFrames { 0 };
+    std::atomic<double> longestDropGapMs { 0.0 };
+    std::atomic<std::chrono::steady_clock::rep> firstFrameTicks { 0 };
+    HANDLE wake = nullptr;
+    std::shared_ptr<int> alive = std::make_shared<int> (0);
+    std::thread thread; // (last)
+};
+} // namespace
+#endif
+
+juce::Array<juce::File> writeSplashShots (const juce::File& folder)
+{
+    juce::Array<juce::File> written;
+    folder.createDirectory();
+    const auto fonts = makeSplashFonts();
+    const auto gpuLogo = decodeLogoImage();
+#if JUCE_WINDOWS
+    juce::lynxSoftwareImagesOnThisThread (true);
+#endif
+    const auto cpuLogo = decodeLogoImage();
+#if JUCE_WINDOWS
+    juce::lynxSoftwareImagesOnThisThread (false);
+#endif
+    for (const auto scale : { 1.0f, 1.5f })
+        for (const auto t : { 0.0, 0.29, 0.58, 1.0, 1.6 })
+            for (const auto cpu : { false, true })
+            {
+                const juce::SoftwareImageType software;
+                const juce::NativeImageType native;
+                const juce::ImageType& type = cpu ? static_cast<const juce::ImageType&> (software) : static_cast<const juce::ImageType&> (native);
+                juce::Image image (juce::Image::ARGB, juce::roundToInt (SplashScreen::width * scale), juce::roundToInt (SplashScreen::height * scale), true, type);
+                {
+                    juce::Graphics g (image);
+                    g.addTransform (juce::AffineTransform::scale (scale));
+                    SplashFrame frame;
+                    frame.t = t;
+                    frame.barDuration = 1.05;
+                    frame.status = tr ("Loading the workspace...");
+                    frame.subtitle = tr ("Digital audio workstation");
+                    frame.version = tr ("Version {0}", { JUCE_APPLICATION_VERSION_STRING });
+                    frame.logo = cpu ? &cpuLogo : &gpuLogo;
+                    frame.fonts = fonts.data();
+                    drawSplashFrame (g, frame);
+                }
+                const auto file = folder.getChildFile ("splash-" + juce::String (juce::roundToInt (scale * 100)) + "-" + juce::String (t, 2) + (cpu ? "-cpu" : "-gpu") + ".png");
+                file.deleteFile();
+                if (juce::FileOutputStream out (file); out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out))
+                    written.add (file);
+            }
+    return written;
+}
+
+std::unique_ptr<StartupSplash> makeStartupSplash()
+{
+#if JUCE_WINDOWS
+    if (juce::SystemStats::getEnvironmentVariable ("LYNX_SPLASH_THREAD", {}) != "0")
+        return std::make_unique<ThreadedSplash>();
+#endif
+    return std::make_unique<SplashScreen>();
 }
 } // namespace lynx

+ 83 - 18
src/ui/Splash.h

@@ -1,5 +1,7 @@
 #pragma once
 
+#include <array>
+#include <chrono>
 #include <functional>
 #include <memory>
 
@@ -24,7 +26,77 @@ struct StartupOptions
 // LYNX's start-up sound (core/StartupSound.h) as a sample the preview player can play.
 std::shared_ptr<const SampleData> makeStartupSample();
 
+// What Main drives during the start-up (round 190hd): the card on the message thread (SplashScreen, a JUCE window: Linux,
+// macOS, LYNX_SPLASH_THREAD=0) or, on Windows, a layered window of its own drawn by a thread of its own with the same
+// drawing code (makeStartupSplash): the message thread can then start the engine, open the audio device and build the
+// main window while the card is up and while the logo drops, without stopping a single frame of the drop.
+class StartupSplash
+{
+public:
+    virtual ~StartupSplash() = default;
+
+    // Shows the card centred on the main display, above other windows (the clock has not started yet).
+    virtual void showOnDesktop() = 0;
+    // t = 0 of the animation (start the start-up sound at the same moment).
+    virtual void startClock() = 0;
+    virtual double getElapsed() const = 0;
+    virtual void setStatus (const juce::String& text) = 0;
+    // the progress bar fills over this (default SplashScreen::minimumDuration)
+    virtual void setBarDuration (double seconds) = 0;
+    // above every other window again, without taking the focus
+    virtual void raise() = 0;
+    // Fades out, removes itself from the desktop and calls `whenGone` (on the message thread).
+    virtual void finish (std::function<void()> whenGone) = 0;
+
+    // The frames painted during the drop (the clock's first `landing` seconds) and the longest time between two of
+    // them, in ms (round 190go: the start-up trace shows that the window built behind the card leaves the drop alone)
+    virtual int getDropFrames() const = 0;
+    virtual double getLongestDropGapMs() const = 0;
+    // When the first frame was on the screen (steady clock; the epoch: not yet)
+    virtual std::chrono::steady_clock::time_point getFirstFrameTime() const = 0;
+    // true: the card draws on a thread of its own, the message thread may work during the drop
+    virtual bool drawsOnItsOwnThread() const { return false; }
+    // Runs `then` on the message thread once the clock has reached `seconds` (the logo has landed). The JUCE card: a
+    // JUCE timer, as before. The card on its own thread: its own clock (round 190hd: a JUCE timer started while the
+    // message thread is busy can fire up to ~0.3 s early: JUCE's timer thread takes the time it waited for a busy
+    // message thread off a timer added meanwhile, which showed the window and faded the card in the middle of the drop)
+    virtual void whenLanded (double seconds, std::function<void()> then)
+    {
+        juce::Timer::callAfterDelay (juce::roundToInt (seconds * 1000.0), std::move (then));
+    }
+    // (the card on its own thread) the clock time of the longest gap between two frames of the drop, seconds
+    virtual double getLongestDropGapAt() const { return -1.0; }
+    // (the card on its own thread) where the frame before that gap spent its time
+    virtual juce::String getLongestDropGapDetail() const { return {}; }
+
+    // Called once on the message thread, after the card's first frame is on the screen (round 190go: the start-up goes
+    // on then, not after a fixed wait)
+    std::function<void()> onFirstFrame;
+};
+
+// The card for this start: Windows draws it on a thread of its own (round 190hd), unless LYNX_SPLASH_THREAD=0.
+std::unique_ptr<StartupSplash> makeStartupSplash();
+
+// One frame of the card (SplashScreen::width x height, the logical size): the same drawing for both kinds of card
+// and for --snapshot. `fonts` resolved on the message thread (a card drawn by its own thread uses them there).
+struct SplashFrame
+{
+    double t = 0.0;              // seconds of the clock (0: the still card before the drop)
+    double barDuration = 2.1;    // the progress bar fills over this
+    juce::String status, subtitle, version;
+    const juce::Image* logo = nullptr;
+    const juce::Font* fonts = nullptr; // [4]: "LYNX", "SHARE", the subtitle, the small text (nullptr: made here)
+};
+void drawSplashFrame (juce::Graphics& g, const SplashFrame& frame);
+// The fonts drawSplashFrame uses, resolved (their typefaces looked up) on the calling thread.
+std::array<juce::Font, 4> makeSplashFonts();
+// LYNX --splashshot <folder> (round 190hd): the card at a few moments of its clock, drawn as the JUCE card is (the
+// platform's renderer: Direct2D on Windows; "-gpu") and as the card on its own thread is (the CPU; "-cpu"), at 100 %
+// and 150 %, as PNGs for a side by side. Returns the files written.
+juce::Array<juce::File> writeSplashShots (const juce::File& folder);
+
 class SplashScreen final : public juce::Component,
+                           public StartupSplash,
                            private juce::Timer
 {
 public:
@@ -38,30 +110,22 @@ public:
     // How long the card stays given that the process started `sinceProcessStart` seconds before its clock: the rest of
     // minimumDuration, but at least `landing` (the logo's drop, after which the main window is built).
     static double remainingDuration (double sinceProcessStart, double landing = 1.05);
-    // the progress bar fills over this (default minimumDuration)
-    void setBarDuration (double seconds) { barDuration = seconds; }
     static constexpr double fadeOutTime = 0.25;
 
-    // Shows the card centred on the main display, above other windows (the clock has not started yet).
-    void showOnDesktop();
-    // t = 0 of the animation (start the start-up sound at the same moment).
-    void startClock();
-    double getElapsed() const;
-
-    void setStatus (const juce::String& text);
-    // Called once, right after the card's first frame is painted (round 190go: the start-up goes on then, not after a
-    // fixed wait)
-    std::function<void()> onFirstFrame;
-    // Fades out, removes itself from the desktop and calls `whenGone`.
-    void finish (std::function<void()> whenGone);
+    void showOnDesktop() override;
+    void startClock() override;
+    double getElapsed() const override;
+    void setStatus (const juce::String& text) override;
+    void setBarDuration (double seconds) override { barDuration = seconds; }
+    void raise() override { toFront (false); }
+    void finish (std::function<void()> whenGone) override;
 
     // --snapshot: draws the frame at `seconds` (no desktop, no timer).
     void setTimeForSnapshot (double seconds);
 
-    // The frames painted during the drop (the clock's first `landing` seconds) and the longest time between two of
-    // them, in ms (round 190go: the start-up trace shows that the window built behind the card leaves the drop alone)
-    int getDropFrames() const noexcept { return dropFrames; }
-    double getLongestDropGapMs() const noexcept { return longestDropGapMs; }
+    int getDropFrames() const override { return dropFrames; }
+    double getLongestDropGapMs() const override { return longestDropGapMs; }
+    std::chrono::steady_clock::time_point getFirstFrameTime() const override { return firstFrameTime; }
 
     void paint (juce::Graphics& g) override;
 
@@ -75,6 +139,7 @@ private:
     double barDuration = minimumDuration;
     int dropFrames = 0;
     double longestDropGapMs = 0.0, lastDropPaintMs = -1.0;
+    std::chrono::steady_clock::time_point firstFrameTime;
     std::function<void()> onGone;
 
     JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen)

+ 5 - 0
src/ui/WindowOwner.cpp

@@ -189,6 +189,11 @@ juce::Image logoImage()
     return juce::ImageCache::getFromMemory (logo::png512, (int) sizeof (logo::png512));
 }
 
+juce::Image decodeLogoImage()
+{
+    return juce::ImageFileFormat::loadFrom (logo::png512, sizeof (logo::png512));
+}
+
 juce::Image logoSmallImage()
 {
     return juce::ImageCache::getFromMemory (logo::pngSmall, (int) sizeof (logo::pngSmall));

+ 2 - 0
src/ui/WindowOwner.h

@@ -122,6 +122,8 @@ juce::TextEditor* firstTextField (juce::Component& dialog);
 // small-size form (thicker lines, the mark larger in the tile: tools/make_logo.py) with the pepper stem for 21-32
 // physical pixels and without it for 20 px and less. All three are square with the tile filling them.
 juce::Image logoImage();
+// The app icon decoded now, on the calling thread, outside the image cache (round 190hd: the splash's own thread)
+juce::Image decodeLogoImage();
 juce::Image logoSmallImage();
 juce::Image logoTinyImage();
 // The mark alone (w3teal's lynx in the red ring with the stem, no tile; 512 px) and its small-size form (128 px).

+ 157 - 0
tests/Startup190hdTests.inc

@@ -0,0 +1,157 @@
+// Round 190hd (start-up faster than FL Studio): the Browser's search index is kept up to date by a low-priority child
+// process woken by file-system changes (REA 190hc action 5, after Live's Indexer). The app's own search service then
+// saves nothing, runs no re-check pass after a search, and takes in the file the indexer wrote (Index::adopt).
+
+#include "core/SearchService.h"
+
+#include <mutex>
+
+namespace s190hd
+{
+lynx::search::FileSystem diskOf (std::map<std::string, lynx::search::FolderListing>& disk, std::mutex& m)
+{
+    lynx::search::FileSystem f;
+    f.folderTime = [&disk, &m] (const std::string& p) {
+        const std::lock_guard<std::mutex> g (m);
+        const auto i = disk.find (p);
+        return i == disk.end() ? (std::int64_t) -1 : i->second.time;
+    };
+    f.list = [&disk, &m] (const std::string& p) {
+        const std::lock_guard<std::mutex> g (m);
+        const auto i = disk.find (p);
+        return i == disk.end() ? lynx::search::FolderListing {} : i->second;
+    };
+    return f;
+}
+
+lynx::search::FolderListing folder (std::int64_t time, std::vector<std::string> files, std::vector<std::string> subs = {})
+{
+    lynx::search::FolderListing l;
+    l.exists = true;
+    l.time = time;
+    l.files = std::move (files);
+    l.subfolders = std::move (subs);
+    return l;
+}
+
+std::vector<std::string> findAll (const lynx::search::Index& index, const std::string& query, const std::vector<std::string>& roots)
+{
+    bool truncated = false;
+    return index.find (query, roots, 1000, truncated);
+}
+} // namespace s190hd
+
+TEST (startup190hd_adopt_takes_the_indexer_trees_and_keeps_the_app_own_ones)
+{
+    std::mutex m;
+    std::map<std::string, lynx::search::FolderListing> disk;
+    disk["/lib"] = s190hd::folder (1, { "kick.wav" }, { "old", "drums" });
+    disk["/lib/old"] = s190hd::folder (1, { "old kick.wav" });
+    disk["/lib/drums"] = s190hd::folder (1, { "snare.wav" });
+    disk["/mine"] = s190hd::folder (1, { "my kick.wav" });
+    const auto fs = s190hd::diskOf (disk, m);
+
+    lynx::search::Index app; // the app's index: /lib and /mine walked to the end
+    app.refresh ("/lib", fs);
+    app.markComplete ("/lib");
+    app.refresh ("/mine", fs);
+    app.markComplete ("/mine");
+
+    // meanwhile the files change: /lib/old is removed, a kick is added to /lib/drums; the indexer walks /lib again
+    {
+        const std::lock_guard<std::mutex> g (m);
+        disk["/lib"] = s190hd::folder (2, { "kick.wav" }, { "drums" });
+        disk.erase ("/lib/old");
+        disk["/lib/drums"] = s190hd::folder (2, { "snare.wav", "new kick.wav" });
+        disk["/mine"] = s190hd::folder (2, {}); // (the indexer does not walk /mine: the app's tree stays)
+    }
+    lynx::search::Index indexer;
+    indexer.refresh ("/lib", fs);
+    indexer.markComplete ("/lib");
+    indexer.refresh ("/other", fs); // (not complete: an interrupted walk)
+
+    const auto before = app.generation();
+    app.adopt (indexer);
+    CHECK (app.generation() != before);
+    CHECK (! app.contains ("/lib/old"));
+    CHECK (app.isComplete ("/lib") && app.isComplete ("/mine"));
+    const auto kicks = s190hd::findAll (app, "kick", { "/lib" });
+    CHECK (kicks.size() == 2);
+    CHECK (std::find (kicks.begin(), kicks.end(), "/lib/drums/new kick.wav") != kicks.end());
+    CHECK (s190hd::findAll (app, "kick", { "/mine" }).size() == 1); // (the app's own tree, unchanged)
+    // the round trip of the result is the same index
+    lynx::search::Index again;
+    CHECK (again.fromText (app.toText()) && again.toText() == app.toText());
+}
+
+TEST (startup190hd_service_with_an_external_indexer_saves_nothing_and_reloads_what_it_wrote)
+{
+    std::mutex m, fileLock;
+    std::map<std::string, lynx::search::FolderListing> disk;
+    disk["/lib"] = s190hd::folder (1, { "kick.wav", "snare.wav" });
+    std::string file; // the index file both processes share
+    int appSaves = 0;
+    std::atomic<int> changed { 0 };
+
+    lynx::search::Service::Callbacks appCb;
+    appCb.load = [&] { const std::lock_guard<std::mutex> g (fileLock); return file; };
+    appCb.save = [&] (const std::string&) { ++appSaves; };
+    appCb.indexChanged = [&] { ++changed; };
+    lynx::search::Service app (s190hd::diskOf (disk, m), appCb);
+    app.setExternalIndexer (true);
+    CHECK (app.hasExternalIndexer());
+
+    std::vector<std::string> found;
+    std::mutex foundLock;
+    const auto sink = [&] (const lynx::search::SearchResult& r) {
+        if (! r.partial)
+        {
+            const std::lock_guard<std::mutex> g (foundLock);
+            found = r.paths;
+        }
+    };
+    app.search ("kick", { "/lib" }, 100, sink); // (a tree never indexed: walked for the search, not saved)
+    CHECK (app.waitIdle (10000));
+    {
+        const std::lock_guard<std::mutex> g (foundLock);
+        CHECK (found.size() == 1);
+    }
+    CHECK (appSaves == 0);
+    CHECK (app.status().checkedAt == 0); // (no re-check pass ran after the search)
+
+    // the indexer process: a kick added, its own service walks the tree and writes the file
+    {
+        const std::lock_guard<std::mutex> g (m);
+        disk["/lib"] = s190hd::folder (2, { "kick.wav", "snare.wav", "kick 2.wav" });
+    }
+    lynx::search::Service::Callbacks indexerCb;
+    indexerCb.load = appCb.load;
+    indexerCb.save = [&] (const std::string& text) { const std::lock_guard<std::mutex> g (fileLock); file = text; };
+    {
+        lynx::search::Service indexer (s190hd::diskOf (disk, m), indexerCb);
+        indexer.refresh ({ "/lib" });
+        CHECK (indexer.waitIdle (10000));
+    }
+    {
+        const std::lock_guard<std::mutex> g (fileLock);
+        CHECK (file.find ("kick 2.wav") != std::string::npos);
+    }
+
+    const auto changedBefore = changed.load();
+    app.reload();
+    CHECK (app.waitIdle (10000));
+    CHECK (changed.load() == changedBefore + 1);
+    app.search ("kick", { "/lib" }, 100, sink);
+    CHECK (app.waitIdle (10000));
+    {
+        const std::lock_guard<std::mutex> g (foundLock);
+        CHECK (found.size() == 2);
+    }
+    CHECK (appSaves == 0);
+
+    // the indexer gone: the service saves again
+    app.setExternalIndexer (false);
+    app.refresh ({ "/lib" });
+    CHECK (app.waitIdle (10000));
+    CHECK (appSaves == 0 || appSaves == 1); // (saved only when a folder was listed again: none changed)
+}

+ 1 - 0
tests/tests.cpp

@@ -17712,6 +17712,7 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "PerfWin190gdTests.inc"
 #include "Ram190gnTests.inc"
 #include "Startup190goTests.inc"
+#include "Startup190hdTests.inc"
 #include "Freeze190ayTests.inc"
 #include "LiveFreeze190ffTests.inc"
 #include "QaFix190bjTests.inc"