// ============================================================================
// BlinkBlocker.cpp => blnkblkr.dll
//
// This is a DLL that gets injected into other processes, hooks these two APIs:
//      FlashBlock()
//      FlashBlockEx()
// and prevents them from flashing taskbar items.  It DOES allow them to invert
// the taskbar button *ONCE* as a way to visually indicate that the window wants
// the user's attention.  But the constant blinking is stopped.
// ============================================================================


// To view the debugging output, use Sysinternals' DbgView
//      http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx


// API details that make this program more difficult:
//
// - There is no call to either FlashWindow() or FlashWindowEx() that simply says
//      "don't change anything, just tell me if it's currently inverted or not"
//      (contrary to what FlashWindow's 'bInvert' parameter implies, bInvert=false
//       does NOT do nothing, rather, it resets it to the original state)
//      BECAUSE OF THIS, we have to internally keep track of whether a particular 
//      taskbar item is inverted or not.
//
// - The Windows OS automatically removes the invert whenever a window gains focus.
//      BECAUSE OF THIS, we have to monitor the application's message queue, so we know
//      when it gains focus.  Otherwise our internal state (whether a taskbar item is
//      inverted) will be incorrect.



// TODO:
//      - create a nice NSIS installer that:
//              1. copies blnkblck.dll and detoured.dll to %windir%\system32\
//              2. adds a 8.3 filename reference to HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs
//              3. pops up a message that says "Successfully installed.  However, applications won't be affected until you either reboot your computer, or restart the desired application."
//
//      - do whatever we need to to make Explorer.exe use a different color for the
//          "selected item" color  (to use red)
//                  - do we have to hook another API when we discover we're loaded inside
//                    explorer.exe?
//                  - or is there a way to do it from the outside?


#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <detours.h>
#include <winternl.h>

#pragma comment( lib, "detours.lib" )
#pragma comment( lib, "detoured.lib" )


#define DllExport   __declspec( dllexport )

LRESULT CALLBACK ShellHook(int nCode, WPARAM wParam, LPARAM lParam);


// ==========================================================================================
// ============================================= hWnd state =================================
// ==========================================================================================

struct window_flash_status {
    HWND hWnd;
    bool isInverted;
    HHOOK hShellHook;
};

// instance-specific data
HMODULE hInstance = 0;
struct window_flash_status window_status[200];
LONG num_window_status_used = 0;        // how many of the above array are actually used


// Adds a new entry to the window_status[] table.
// Returns the index number of the hWnd that was added.
int insertNewHwnd(HWND hWnd)
{
    WCHAR dbg[1000];

    // make sure we haven't overflowed the array
    if (num_window_status_used >= sizeof(window_status) / sizeof(struct window_flash_status))
    {
        OutputDebugStringW(L"overflowed the window_flash_status table");
        return -1;
    }

    DWORD windowProcThreadID = GetWindowThreadProcessId(hWnd, NULL);

    int idx = InterlockedIncrement(&num_window_status_used) - 1;    // this is one of the few places that we can have race issues, so we have to use InterlockedIncrement
    window_status[idx].hWnd = hWnd;
    window_status[idx].isInverted = false;
    window_status[idx].hShellHook = SetWindowsHookEx(WH_SHELL, ShellHook, NULL, windowProcThreadID);

    swprintf(dbg, sizeof(dbg), L"[%d] Shell-hooked the newly-encountered hWnd = %d  (idx=%d)", hInstance, hWnd, idx);
    OutputDebugString(dbg);

    return idx;
}

// returns the index number of the hWnd that was found
//  (or -1 if not found)
int findHwndStatus(HWND hWnd)
{
    for (int ctr=0; ctr<num_window_status_used; ctr++) {
        if (window_status[ctr].hWnd == hWnd)
            return ctr;
    }
    return -1;
}

int findOrCreateHwnd(HWND hWnd)
{
    int idx = findHwndStatus(hWnd);
    if (idx < 0)
    {
        idx = insertNewHwnd(hWnd);
    }
    return idx;
}




// ==========================================================================================
// ============================================= API hooks ==================================
// ==========================================================================================

// signature of the real API functions
static BOOL (WINAPI * Real_FlashWindow)(
               IN HWND hWnd,
               IN BOOL bInvert
             ) = FlashWindow;
static BOOL (WINAPI * Real_FlashWindowEx)(
               IN PFLASHWINFO pFWi
             ) = FlashWindowEx;


// our shim
BOOL WINAPI Detoured_FlashWindow(
    IN HWND hWnd,
    IN BOOL bInvert
    )
{
    return false;
}


BOOL WINAPI Detoured_FlashWindowEx(IN PFLASHWINFO pFWi)
{
    BOOL Ret = false;
    BOOL isForeground;
    window_flash_status* state;
    FLASHWINFO bInvertTrue = {sizeof(FLASHWINFO), pFWi->hwnd, FLASHW_TRAY, 0, 0};       // FlashWindow(bInvert=true) is equvalent to FlashWindowEx(dwFlags=FLASHW_ALL, uCount=1, dwTimeout=0)

    //OutputDebugStringW(L"FlashWindowEx() called");

    WCHAR dbg[1000];

    // is this window currently in the foreground?
    isForeground = (pFWi->hwnd == GetForegroundWindow());

    int winstatidx = findOrCreateHwnd(pFWi->hwnd);
    if (winstatidx < 0)
        return 0;               // WTF are we supposed to do here?
    state = &(window_status[winstatidx]);

//  if (bInvert)
//  {
        // bInvert==true means that they want to invert the window / taskbar visual indicator to the opposite of what it currently is

        if (!isForeground) {
            // make sure that this window is only inverted ONCE per backgrounding
            if (!state->isInverted) {
                Ret = Real_FlashWindowEx(&bInvertTrue);
                state->isInverted = true;
            }
        }
//  }
//  else
//  {
        // bInvert==false means they want to reset the window / taskbar visual indicator to what it originally was

        // only let it go through if this window is now in the foreground
        //if (isForeground)
        //{
        //  state->isInverted = false;
        //  bInvertTrue.dwFlags = FLASHW_STOP;
        //  Ret = Real_FlashWindowEx(&bInvertTrue);
        //}
//  }

    swprintf(dbg, sizeof(dbg), L"[%d] FlashWindowEx(hwnd=%d, dwFlags=%d, uCount=%d, dwTimeout=%d) = %s  [isForeground=%s]", hInstance, pFWi->hwnd, pFWi->dwFlags, pFWi->uCount, pFWi->dwTimeout, state->isInverted ? L"true" : L"false", isForeground?L"true":L"false");
    OutputDebugStringW(dbg);


    //return (Ret);
    return (state->isInverted);
}



LRESULT CALLBACK ShellHook(int nCode, WPARAM wParam, LPARAM lParam) {
    WCHAR dbg[256];

    if (nCode == HSHELL_WINDOWACTIVATED || nCode == HSHELL_RUDEAPPACTIVATED) {
        // Is this a window that we're interested in?  This very well could be another processes' window,
        // a our process's window, but not a window that has ever been flashed before.
        int idx = findHwndStatus((HWND)wParam);
        if (idx >= 0) {
            // This *IS* a window that we're interested in.
            if (window_status[idx].isInverted) {
                FLASHWINFO bInvertFalse = {sizeof(FLASHWINFO), (HWND)wParam, FLASHW_STOP, 0, 0};        // FlashWindow(bInvert=true) is equvalent to FlashWindowEx(dwFlags=FLASHW_ALL, uCount=1, dwTimeout=0)
                Real_FlashWindowEx(&bInvertFalse);
            }
            window_status[idx].isInverted = 0;      // the OS automatically stops blinking for windows as soon as they gain focus

            swprintf(dbg, sizeof(dbg), L"[%d] Window %d got activated.", hInstance, wParam);
            OutputDebugString(dbg);
        }
    }

    CallNextHookEx(0, nCode, wParam, lParam);
    //             ^ This parameter is ignored under NT/XP/2003/etc.
    //               Finding the correct hHook is a huge PITA (impossible?) here, so we just won't support 95/98/ME.
    //                      (see http://www.klenotic.com/pl/null_hhook/)
    return 0;
}


// ==========================================================================================
// ============================================= main entry point ===========================
// ==========================================================================================

extern "C"
{
DllExport BOOL WINAPI DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    if (ul_reason_for_call == DLL_PROCESS_ATTACH)
    {
        OutputDebugString(L"BlinkBlocker starting");
        hInstance = hModule;
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        // we don't have to hook FlashWindow(), because FlashWindow() just calls FlashWindowEx() to do its work
        //DetourAttach(&(PVOID&)Real_FlashWindow,   Detoured_FlashWindow);
        DetourAttach(&(PVOID&)Real_FlashWindowEx, Detoured_FlashWindowEx);
        DetourTransactionCommit();
    }
    else if (ul_reason_for_call == DLL_PROCESS_DETACH)
    {
        OutputDebugString(L"BlinkBlocker stopping");
        // "Before terminating, an application MUST call the UnhookWindowsHookEx function to free system resources associated with the hook. "
        for (int idx=0; idx<num_window_status_used; idx++)
        {
            UnhookWindowsHookEx(window_status[idx].hShellHook);
        }
        DetourTransactionBegin();
        //DetourDetach(&(PVOID&)Real_FlashWindow,   Detoured_FlashWindow);
        DetourDetach(&(PVOID&)Real_FlashWindowEx, Detoured_FlashWindowEx);
        DetourTransactionCommit();
    }
    
    return TRUE;
}
}






#ifdef _MANAGED
#pragma managed(pop)
#endif
