// ==WindhawkMod==
// @id              explorer-ribbon-restartcommands-tabs-fix
// @name            Restore Explorer Ribbon windows through RestartCommandsTabs
// @description     Makes the native tab-aware Explorer session saver see one synthetic tab in classic Ribbon windows
// @version         0.1.1
// @author          mihail2501
// @license         GPL-3.0
// @include         explorer.exe
// @architecture    x86-64
// @compilerOptions -lole32 -loleaut32 -lshell32 -luuid
// ==/WindhawkMod==

// Source code is published under the GNU General Public License v3.0.

// ==WindhawkModReadme==
/*
# Restore Explorer Ribbon windows through RestartCommandsTabs

This is an experimental compatibility fix for **Restore previous folder
windows at logon** when ExplorerPatcher enables the Windows 10 Ribbon on
Windows 11 24H2/25H2.

Recent Explorer builds save a window through the native, tab-aware
`CExplorerFrame::AddToRestartList_Tabs` path. A classic Ribbon window has no
entries in Explorer's modern `FEBrowserTab` vector, so that path records
nothing.

For an empty vector, this mod:

1. resolves the current folder of that exact Explorer HWND as an `IShellItem2`;
2. creates a narrow COM proxy representing one browser tab;
3. calls the original `AddToRestartList_Tabs` with a temporary shadow frame
   containing that one tab.

The original Explorer code then obtains the PIDL itself and writes the normal
`RestartCommandsTabs` data. The real `CExplorerFrame` and its vector are never
modified.

This mod does **not** change Windows Feature Store state, hook a feature ID,
use ViVeTool, write its own session file, or create a startup task.

## Requirements

* Enable **Restore previous folder windows at logon** in Folder Options.
* Select **Windows 10 Ribbon** in ExplorerPatcher.
* Restart Explorer after installing or removing the mod.

## Compatibility and safety

The private function is located through Microsoft symbols. The mod also
validates the native saver contract and discovers the tab-vector offset from
the function's machine code. If the expected contract is absent, it refuses to
install instead of patching an unknown layout.

The contract was checked against x64 ExplorerFrame builds 26100.3037,
26100.5074, 26100.6725, 26100.7019, 26100.7462, and 26100.8972.
*/
// ==/WindhawkModReadme==

#include <windhawk_utils.h>

#include <windows.h>
#include <exdisp.h>
#include <servprov.h>
#include <shlobj.h>
#include <shobjidl.h>

#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <new>

namespace {

using AddToRestartListTabs_t = HRESULT(__fastcall*)(void* explorerFrame);

AddToRestartListTabs_t g_addToRestartListTabsOriginal;
size_t g_tabVectorOffset;

constexpr size_t kNativeFunctionScanSize = 0x1400;
constexpr size_t kFEBrowserTabSize = 0x28;
constexpr size_t kActiveTabGuidDelta = 0x28;

// The first object in FEBrowserTab is queried for this private interface.
// The saver then calls its vtable slot 7 with IID_IShellItem2.
constexpr GUID kBrowserHostViewInterface = {
    0xb965e203,
    0x2a6a,
    0x4e2e,
    {0xa1, 0x5d, 0xce, 0xcd, 0x73, 0x6f, 0x12, 0xb2}};

constexpr CLSID kCLSID_ShellWindows = {
    0x9ba05972,
    0xf6a8,
    0x11cf,
    {0xa4, 0x42, 0x00, 0xa0, 0xc9, 0x0a, 0x8f, 0x39}};

constexpr GUID kSID_STopLevelBrowser = {
    0x4c96be40,
    0x915c,
    0x11cf,
    {0x99, 0xd3, 0x00, 0xaa, 0x00, 0x4a, 0xe8, 0x37}};

template <typename T>
class ComPtr {
   public:
    ComPtr() = default;
    ComPtr(const ComPtr&) = delete;
    ComPtr& operator=(const ComPtr&) = delete;

    ~ComPtr() {
        if (m_ptr) {
            m_ptr->Release();
        }
    }

    T* Get() const {
        return m_ptr;
    }

    T* operator->() const {
        return m_ptr;
    }

    T** Put() {
        if (m_ptr) {
            m_ptr->Release();
            m_ptr = nullptr;
        }
        return &m_ptr;
    }

   private:
    T* m_ptr = nullptr;
};

// Only the vtable shape matters here. Slots 3 through 6 aren't used by the
// native saver; slot 7 returns an object for a requested IID.
struct IBrowserHostViewBridge : IUnknown {
    virtual HRESULT STDMETHODCALLTYPE Reserved3() = 0;
    virtual HRESULT STDMETHODCALLTYPE Reserved4() = 0;
    virtual HRESULT STDMETHODCALLTYPE Reserved5() = 0;
    virtual HRESULT STDMETHODCALLTYPE Reserved6() = 0;
    virtual HRESULT STDMETHODCALLTYPE GetViewObject(REFIID riid,
                                                     void** object) = 0;
};

class SyntheticBrowserHost final : public IBrowserHostViewBridge {
   public:
    explicit SyntheticBrowserHost(IShellItem2* folder) : m_folder(folder) {
        m_folder->AddRef();
    }

    HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
                                             void** object) override {
        if (!object) {
            return E_POINTER;
        }

        *object = nullptr;
        if (IsEqualIID(riid, IID_IUnknown) ||
            IsEqualIID(riid, kBrowserHostViewInterface)) {
            *object = static_cast<IBrowserHostViewBridge*>(this);
            AddRef();
            return S_OK;
        }

        return E_NOINTERFACE;
    }

    ULONG STDMETHODCALLTYPE AddRef() override {
        return ++m_refs;
    }

    ULONG STDMETHODCALLTYPE Release() override {
        ULONG refs = --m_refs;
        if (!refs) {
            delete this;
        }
        return refs;
    }

    HRESULT STDMETHODCALLTYPE Reserved3() override {
        return E_NOTIMPL;
    }

    HRESULT STDMETHODCALLTYPE Reserved4() override {
        return E_NOTIMPL;
    }

    HRESULT STDMETHODCALLTYPE Reserved5() override {
        return E_NOTIMPL;
    }

    HRESULT STDMETHODCALLTYPE Reserved6() override {
        return E_NOTIMPL;
    }

    HRESULT STDMETHODCALLTYPE GetViewObject(REFIID riid,
                                             void** object) override {
        if (!object) {
            return E_POINTER;
        }
        return m_folder->QueryInterface(riid, object);
    }

   private:
    ~SyntheticBrowserHost() {
        m_folder->Release();
    }

    std::atomic<ULONG> m_refs = 1;
    IShellItem2* m_folder;
};

struct SyntheticFEBrowserTab {
    IUnknown* browserHost;
    IUnknown* explorerRibbonProxy;
    GUID tabId;
    BYTE flag;
    BYTE padding[7];
};

static_assert(sizeof(SyntheticFEBrowserTab) == kFEBrowserTabSize);
static_assert(offsetof(SyntheticFEBrowserTab, tabId) == 0x10);
static_assert(offsetof(SyntheticFEBrowserTab, flag) == 0x20);

bool IsRangeInsideModule(const BYTE* address,
                         size_t size,
                         const BYTE* moduleBase,
                         size_t moduleSize) {
    uintptr_t begin = reinterpret_cast<uintptr_t>(address);
    uintptr_t end = begin + size;
    uintptr_t imageBegin = reinterpret_cast<uintptr_t>(moduleBase);
    uintptr_t imageEnd = imageBegin + moduleSize;

    return end >= begin && begin >= imageBegin && end <= imageEnd;
}

bool FunctionReferencesGuid(const BYTE* function,
                            size_t scanSize,
                            const GUID& guid,
                            const BYTE* moduleBase,
                            size_t moduleSize) {
    // x64: lea rdx, [rip + rel32]
    for (size_t i = 0; i + 7 <= scanSize; i++) {
        if (function[i] != 0x48 || function[i + 1] != 0x8d ||
            function[i + 2] != 0x15) {
            continue;
        }

        int32_t displacement;
        std::memcpy(&displacement, function + i + 3, sizeof(displacement));
        uintptr_t instructionEnd =
            reinterpret_cast<uintptr_t>(function + i + 7);
        const BYTE* target = reinterpret_cast<const BYTE*>(
            instructionEnd + static_cast<intptr_t>(displacement));
        if (IsRangeInsideModule(target, sizeof(GUID), moduleBase, moduleSize) &&
            std::memcmp(target, &guid, sizeof(GUID)) == 0) {
            return true;
        }
    }

    return false;
}

bool FunctionHasFEBrowserTabStride(const BYTE* function, size_t scanSize) {
    // x64: add r64, 28h. The destination register varies by compiler build.
    for (size_t i = 0; i + 4 <= scanSize; i++) {
        if (function[i] >= 0x48 && function[i] <= 0x4f &&
            function[i + 1] == 0x83 && function[i + 2] >= 0xc0 &&
            function[i + 2] <= 0xc7 && function[i + 3] == 0x28) {
            return true;
        }
    }

    return false;
}

bool IsPlausibleVectorOffset(uint32_t beginOffset, uint32_t endOffset) {
    return beginOffset >= 0x100 && beginOffset <= 0x4000 &&
           (beginOffset % sizeof(void*)) == 0 &&
           endOffset == beginOffset + sizeof(void*);
}

bool DiscoverTabVectorOffset(const BYTE* function,
                             size_t scanSize,
                             size_t* vectorOffset) {
    for (size_t i = 0; i + 17 <= scanSize; i++) {
        // Builds 26100.5074 through at least 26100.8972:
        //   mov r15, [rsi + beginOffset]
        //   mov r12, [rsi + endOffset]
        //   cmp r15, r12
        if (function[i] == 0x4c && function[i + 1] == 0x8b &&
            function[i + 2] == 0xbe && function[i + 7] == 0x4c &&
            function[i + 8] == 0x8b && function[i + 9] == 0xa6 &&
            function[i + 14] == 0x4d && function[i + 15] == 0x3b &&
            function[i + 16] == 0xfc) {
            uint32_t beginOffset;
            uint32_t endOffset;
            std::memcpy(&beginOffset, function + i + 3,
                        sizeof(beginOffset));
            std::memcpy(&endOffset, function + i + 10, sizeof(endOffset));
            if (IsPlausibleVectorOffset(beginOffset, endOffset)) {
                *vectorOffset = beginOffset;
                return true;
            }
        }

        // Build 26100.3037 uses different saved registers and spills the end
        // pointer before entering the same FEBrowserTab loop.
        if (function[i] == 0x4d && function[i + 1] == 0x8b &&
            function[i + 2] == 0xae && function[i + 7] == 0x49 &&
            function[i + 8] == 0x8b && function[i + 9] == 0x8e) {
            uint32_t beginOffset;
            uint32_t endOffset;
            std::memcpy(&beginOffset, function + i + 3,
                        sizeof(beginOffset));
            std::memcpy(&endOffset, function + i + 10, sizeof(endOffset));
            if (IsPlausibleVectorOffset(beginOffset, endOffset)) {
                *vectorOffset = beginOffset;
                return true;
            }
        }
    }

    return false;
}

bool ValidateAndDiscoverNativeContract(HMODULE explorerFrame,
                                       const BYTE* function,
                                       size_t* vectorOffset) {
    const auto* dosHeader = reinterpret_cast<const IMAGE_DOS_HEADER*>(
        explorerFrame);
    if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
        return false;
    }

    const auto* ntHeaders = reinterpret_cast<const IMAGE_NT_HEADERS*>(
        reinterpret_cast<const BYTE*>(explorerFrame) + dosHeader->e_lfanew);
    if (ntHeaders->Signature != IMAGE_NT_SIGNATURE) {
        return false;
    }

    const BYTE* moduleBase = reinterpret_cast<const BYTE*>(explorerFrame);
    size_t moduleSize = ntHeaders->OptionalHeader.SizeOfImage;
    if (!IsRangeInsideModule(function, 1, moduleBase, moduleSize)) {
        return false;
    }

    size_t bytesToImageEnd =
        moduleSize - static_cast<size_t>(function - moduleBase);
    size_t scanSize = bytesToImageEnd < kNativeFunctionScanSize
                          ? bytesToImageEnd
                          : kNativeFunctionScanSize;

    if (!FunctionReferencesGuid(function, scanSize,
                                kBrowserHostViewInterface, moduleBase,
                                moduleSize) ||
        !FunctionReferencesGuid(function, scanSize, __uuidof(IShellItem2),
                                moduleBase, moduleSize) ||
        !FunctionHasFEBrowserTabStride(function, scanSize) ||
        !DiscoverTabVectorOffset(function, scanSize, vectorOffset)) {
        return false;
    }

    return true;
}

HRESULT GetCurrentFolderItem(HWND explorerHwnd, IShellItem2** folderItem) {
    if (!folderItem) {
        return E_POINTER;
    }
    *folderItem = nullptr;

    ComPtr<IShellWindows> shellWindows;
    HRESULT hr = CoCreateInstance(
        kCLSID_ShellWindows, nullptr, CLSCTX_LOCAL_SERVER,
        __uuidof(IShellWindows),
        reinterpret_cast<void**>(shellWindows.Put()));
    if (FAILED(hr)) {
        return hr;
    }

    long count = 0;
    hr = shellWindows->get_Count(&count);
    if (FAILED(hr)) {
        return hr;
    }

    for (long i = 0; i < count; i++) {
        VARIANT index;
        VariantInit(&index);
        index.vt = VT_I4;
        index.lVal = i;

        ComPtr<IDispatch> dispatch;
        hr = shellWindows->Item(index, dispatch.Put());
        VariantClear(&index);
        if (FAILED(hr) || !dispatch.Get()) {
            continue;
        }

        ComPtr<IWebBrowser2> webBrowser;
        hr = dispatch->QueryInterface(
            __uuidof(IWebBrowser2),
            reinterpret_cast<void**>(webBrowser.Put()));
        if (FAILED(hr)) {
            continue;
        }

        SHANDLE_PTR browserHwnd = 0;
        hr = webBrowser->get_HWND(&browserHwnd);
        if (FAILED(hr) ||
            reinterpret_cast<HWND>(browserHwnd) != explorerHwnd) {
            continue;
        }

        ComPtr<IServiceProvider> serviceProvider;
        hr = webBrowser->QueryInterface(
            __uuidof(IServiceProvider),
            reinterpret_cast<void**>(serviceProvider.Put()));
        if (FAILED(hr)) {
            return hr;
        }

        ComPtr<IShellBrowser> shellBrowser;
        hr = serviceProvider->QueryService(
            kSID_STopLevelBrowser, __uuidof(IShellBrowser),
            reinterpret_cast<void**>(shellBrowser.Put()));
        if (FAILED(hr)) {
            return hr;
        }

        ComPtr<IShellView> shellView;
        hr = shellBrowser->QueryActiveShellView(shellView.Put());
        if (FAILED(hr)) {
            return hr;
        }

        ComPtr<IFolderView> folderView;
        hr = shellView->QueryInterface(
            __uuidof(IFolderView),
            reinterpret_cast<void**>(folderView.Put()));
        if (FAILED(hr)) {
            return hr;
        }

        ComPtr<IPersistFolder2> persistFolder;
        hr = folderView->GetFolder(
            __uuidof(IPersistFolder2),
            reinterpret_cast<void**>(persistFolder.Put()));
        if (FAILED(hr)) {
            return hr;
        }

        PIDLIST_ABSOLUTE pidl = nullptr;
        hr = persistFolder->GetCurFolder(&pidl);
        if (FAILED(hr)) {
            return hr;
        }

        hr = SHCreateItemFromIDList(pidl, __uuidof(IShellItem2),
                                    reinterpret_cast<void**>(folderItem));
        CoTaskMemFree(pidl);
        return hr;
    }

    return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
}

HRESULT __fastcall AddToRestartListTabsHook(void* explorerFrame) {
    BYTE* frame = static_cast<BYTE*>(explorerFrame);
    auto** realVector = reinterpret_cast<void**>(frame + g_tabVectorOffset);

    // A normal Windows 11 tabbed window already has native records and must be
    // passed through unchanged. Ribbon windows are the empty-vector case.
    if (realVector[0] != realVector[1]) {
        return g_addToRestartListTabsOriginal(explorerFrame);
    }

    HWND hwnd = *reinterpret_cast<HWND*>(frame + 8);
    if (!IsWindow(hwnd)) {
        Wh_Log(L"Empty tab vector, but CExplorerFrame HWND is invalid: %p",
               hwnd);
        return g_addToRestartListTabsOriginal(explorerFrame);
    }

    ComPtr<IShellItem2> folder;
    HRESULT hr = GetCurrentFolderItem(hwnd, folder.Put());
    if (FAILED(hr)) {
        Wh_Log(L"Couldn't resolve the current folder for HWND %p, hr=0x%08X",
               hwnd, static_cast<unsigned int>(hr));
        return g_addToRestartListTabsOriginal(explorerFrame);
    }

    auto* browserHost =
        new (std::nothrow) SyntheticBrowserHost(folder.Get());
    if (!browserHost) {
        return g_addToRestartListTabsOriginal(explorerFrame);
    }

    SyntheticFEBrowserTab tab = {};
    tab.browserHost = static_cast<IBrowserHostViewBridge*>(browserHost);

    // The saver compares the record GUID with the frame's active-tab GUID to
    // write the active index. Preserve that GUID in the synthetic record.
    constexpr size_t activeGuidOffset =
        kActiveTabGuidDelta;  // Added to g_tabVectorOffset below.
    std::memcpy(&tab.tabId,
                frame + g_tabVectorOffset + activeGuidOffset,
                sizeof(tab.tabId));

    size_t shadowSize = g_tabVectorOffset + activeGuidOffset + sizeof(GUID);
    BYTE* shadow = static_cast<BYTE*>(
        HeapAlloc(GetProcessHeap(), 0, shadowSize));
    if (!shadow) {
        browserHost->Release();
        return g_addToRestartListTabsOriginal(explorerFrame);
    }

    // This function is read-only with respect to CExplorerFrame in every
    // validated build. Copying the relevant prefix preserves window-placement
    // flags and any future read-only fields while keeping all writes isolated.
    std::memcpy(shadow, frame, shadowSize);

    auto** shadowVector =
        reinterpret_cast<void**>(shadow + g_tabVectorOffset);
    shadowVector[0] = &tab;
    shadowVector[1] = reinterpret_cast<BYTE*>(&tab) + sizeof(tab);
    shadowVector[2] = shadowVector[1];

    Wh_Log(L"HWND %p: passing one synthetic Ribbon tab to native "
           L"AddToRestartList_Tabs",
           hwnd);
    hr = g_addToRestartListTabsOriginal(shadow);

    HeapFree(GetProcessHeap(), 0, shadow);
    browserHost->Release();
    return hr;
}

}  // namespace

BOOL Wh_ModInit() {
    HMODULE explorerFrame = GetModuleHandleW(L"ExplorerFrame.dll");
    if (!explorerFrame) {
        explorerFrame = LoadLibraryExW(
            L"ExplorerFrame.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
    }
    if (!explorerFrame) {
        Wh_Log(L"Failed to load ExplorerFrame.dll, error %u", GetLastError());
        return FALSE;
    }

    WCHAR modulePath[MAX_PATH];
    DWORD pathLength = GetModuleFileNameW(
        explorerFrame, modulePath, ARRAYSIZE(modulePath));
    if (pathLength && pathLength < ARRAYSIZE(modulePath)) {
        Wh_Log(L"Loaded ExplorerFrame: %s", modulePath);
    }

    AddToRestartListTabs_t targetFunction = nullptr;
    WindhawkUtils::SYMBOL_HOOK findSymbol[] = {
        {
            {
                L"?AddToRestartList_Tabs@CExplorerFrame@@AEAAJXZ",
                L"private: long __cdecl "
                L"CExplorerFrame::AddToRestartList_Tabs(void)",
            },
            &targetFunction,
            nullptr,
            false,
        },
    };

    if (!WindhawkUtils::HookSymbols(explorerFrame, findSymbol,
                                    ARRAYSIZE(findSymbol)) ||
        !targetFunction) {
        Wh_Log(L"CExplorerFrame::AddToRestartList_Tabs wasn't found");
        return FALSE;
    }

    if (!ValidateAndDiscoverNativeContract(
            explorerFrame, reinterpret_cast<const BYTE*>(targetFunction),
            &g_tabVectorOffset)) {
        Wh_Log(L"AddToRestartList_Tabs has an unknown ABI; refusing to hook");
        return FALSE;
    }

    if (!WindhawkUtils::SetFunctionHook(
            targetFunction, AddToRestartListTabsHook,
            &g_addToRestartListTabsOriginal)) {
        Wh_Log(L"Failed to hook AddToRestartList_Tabs");
        return FALSE;
    }

    Wh_Log(L"Native RestartCommandsTabs hook installed; tab vector offset "
           L"0x%zX",
           g_tabVectorOffset);
    return TRUE;
}

void Wh_ModUninit() {
    Wh_Log(L"Native RestartCommandsTabs hook removed");
}
