// ===========================================================================
//
//	File:		APEMain.m
//
//	Contains:	ICeCoffEE APE Module code
//
//	Copyright:	Copyright (c) 2003, Nicholas Riley
//			All Rights Reserved.
//
//	Author(s):	Nicholas Riley (Sun Jan 19 2003)
//
// ===========================================================================

#import <Carbon/Carbon.h>
#import <ApplicationEnhancer/ApplicationEnhancer.h>
#import <ApplicationEnhancer/APETools.h>
#import <objc/objc-runtime.h>
#import "ICeCoffEE.h"

//ĄĄĄ Our settings

//ĄĄĄ Function prototypes
static void ICCF_ReloadPrefs();				// reloads our preferences

//ĄĄĄ Enter sandman, the code begins --

#define ICCF_GET_PATCHCLASS(patchclass) \
    struct objc_class *patchclass = objc_getClass(patchclass ## Name); \
    if (patchclass == NULL) { \
        apeprintf("can't get %s\n", patchclass ## Name); \
        return NO; \
    }

#define ICCF_GET_METHOD(name, patchclass, sel) \
    Method name = class_getInstanceMethod(patchclass, sel); \
    if (name == NULL) { \
        apeprintf("can't get %s\n", patchclass ## Name); \
        return NO; \
    }

BOOL ICCF_PatchMethod(char *patcheeClassName,
                      char *patchClassName,
                      char *patchSuperclassName,
                      char *selectorString) {

    ICCF_GET_PATCHCLASS(patcheeClass);
    ICCF_GET_PATCHCLASS(patchClass);
    ICCF_GET_PATCHCLASS(patchSuperclass);

    SEL selector = sel_getUid(selectorString);

    ICCF_GET_METHOD(patcheeMethod, patcheeClass, selector);
    ICCF_GET_METHOD(patchMethod, patchClass, selector);
    ICCF_GET_METHOD(patchSuperMethod, patchSuperclass, selector);

    APEPatchCreate(patchSuperMethod->method_imp,
                   APEPatchCreate(patcheeMethod->method_imp, patchMethod->method_imp));
    return YES;
}

void APEBundleMain(CFBundleRef inBundle)
{
    // first check if this application is in the exclude list;
    // if it is, simply return and do not apply any patches.
    // APETools will help us with that; APE Manager will take care of
    // exclude list management for us.
    if (APEToolsIsInExcludeList(CFSTR("net.sabi.ICeCoffEE"), NULL))
    {
        apeprintf("ICeCoffEE APE: not loading as this application is excluded.\n");
        return;
    }
    
    ICCF_ReloadPrefs();					// load your preferences
    // Add any of your initialization here...

    CFStringRef bundleID = CFBundleGetIdentifier(CFBundleGetMainBundle());
    BOOL shouldLoadAlways = YES;
    
    if (bundleID != NULL) {
        if (CFStringCompare(bundleID, CFSTR("com.apple.projectbuilder"), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
            ICCF_PatchMethod("PBXTextView", "ICeCoffEEMenuOnly", "ICeCoffEEMenuSuper", "menuForEvent:");
            apeprintf("ICeCoffEE APE: loading in PB!\n");
            shouldLoadAlways = NO;
        } else if (CFStringCompare(bundleID, CFSTR("com.apple.terminal"), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
            ICCF_PatchMethod("TermSubview", "ICeCoffEEMenuOnly", "ICeCoffEEMenuSuper", "menuForEvent:");
            apeprintf("ICeCoffEE APE: loading in Terminal!\n");
        } else if (CFStringCompare(bundleID, CFSTR("com.apple.safari"), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
            ICCF_PatchMethod("WebHTMLView", "ICeCoffEEWebKit", "ICeCoffEEWebKitSuper", "mouseUp:");
            ICCF_PatchMethod("WebHTMLView", "ICeCoffEEWebKit", "ICeCoffEEWebKitSuper", "mouseDown:");
            ICCF_PatchMethod("WebHTMLView", "ICeCoffEEWebKit", "ICeCoffEEWebKitSuper", "menuForEvent:");
            apeprintf("ICeCoffEE APE: loading in Safari!\n");
        }
    }

    if (shouldLoadAlways) {
        ICCF_PatchMethod("NSTextView", "ICeCoffEE", "ICeCoffEESuper", "mouseDown:");
        ICCF_PatchMethod("NSTextView", "ICeCoffEE", "ICeCoffEESuper", "menuForEvent:");
        apeprintf("ICeCoffEE APE: loading\n");
    }

    ICCF_AddServicesMenu();
        
    return;
}

// We define APEBundleMessage so we can receive messages from our preference pane.  We actually only know the Refresh message that instructs our APE module to reload the preferences.  Why do we reload preferences here and not do it in our patch? Well, although you can poll CFPreferences in every patch call, that'll result in some performance loss - we better cache the settings in a static variable and refresh them from prefs only when needed.
OSStatus APEBundleMessage(CFStringRef message,CFDataRef inData,CFDataRef *outData)
{
    apeprintf("ICeCoffEE APE: message '%@' (inData = %@)\n", message, inData);
    
    if (CFStringCompare(message, CFSTR("Refresh"), NULL) == kCFCompareEqualTo)		
    {	// request to reload prefs from our preference pane
        ICCF_ReloadPrefs();
    }
    
    return noErr;
}

// Reload our settings from the (nonexistent) plist
static void ICCF_ReloadPrefs()
{
    CFPreferencesAppSynchronize(CFSTR("net.sabi.ICeCoffEE"));

    // Load your preferences here...
}
