// ppc-amigaos-gcc -Wall -O3 -N WB2Filer.c -o WB2Filer -lauto ; ppc-amigaos-strip WB2Filer

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/wb.h>
#include <proto/intuition.h>

struct Screen *screen = NULL;
char *filer_binary = NULL;
BOOL disable_flash_beep = FALSE;

int which_icon = 0;

struct Window * APICALL (*Original_OpenWindowTagList)(struct IntuitionIFace *Self, const struct NewWindow * newWindow, const struct TagItem * tagList);
VOID * APICALL (*Original_DisplayBeep)(struct IntuitionIFace *Self, struct Screen *screen);

// A hook to be used with ChangeWorkbenchSelection() to unselect icons

BOOL UnSelectIcon(struct Hook *h, VOID *o, VOID *msg)
{
	return ISMACTION_Unselect; // ISMACTION_Unselect = Unselect the icon (workbench.library autodoc)
}

VOID * APICALL Patched_DisplayBeep(struct IntuitionIFace *Self, struct Screen *screen)
{
	// If TRUE set from patched_OpenWindowTagList(), we return NULL to not blink-beep
	// otherwise return original to keep other task's DisplayBeep() to work as intended.
	
	if (disable_flash_beep == TRUE) {
		disable_flash_beep = FALSE;
		return NULL;
	} else {
		return Original_DisplayBeep(Self,screen);
	}
	
}

struct Window * APICALL Patched_OpenWindowTagList(struct IntuitionIFace *Self, const struct NewWindow * nw, const struct TagItem * tagList) 
{

	// Do check, if this is our WB window(s) which we need to patch:
	// if FALSE, then return original OpenWindowTagList(), if TRUE, we do our magic futher 
	// (inverting condition check done for easy code-reading and to avoid of the distang else)
	
	if (!nw || !(nw->Flags & WFLG_WBENCHWINDOW) || (nw->Flags & WFLG_BACKDROP)) {
		return Original_OpenWindowTagList(Self,nw, tagList);
	}

	struct Task *Caller = (struct Task *)IExec->FindTask(NULL);

	if (!Caller || stricmp(Caller->tc_Node.ln_Name, "Workbench") != 0) {
		return Original_OpenWindowTagList(Self,nw, tagList);
	}	

	// Firstly define a flag for final error checking and code simplification
	
	BOOL ok = FALSE;
	
	// As we can select more than one icon on desktop, we need a way to handle it all correctly and to not run for each
	// OpenWindowTagList() the same and the same Filer instances as it happens when we use only WhichWorkbenchObject()
	// So, we use WorkbenchControl/WBCTRLA_GetSelectedIconList to not only get list of all selected icons on desktop,
	// but also to handle selection of many icons in the proper way and to not spawn same Filer's instances. 
	
	// The logic behind of it (c) msteed and implemented with help of Javier. To quote msteed:
	// if more than one icon is selected, then each time OpenWindowTagList() is called, one of the selected icons
	// will have its window opened. The which_icon variable keeps track of the next entry in the list, the one
	// that will have its window opened the next time OpenWindowTagList() is called. Once the last entry has had
	// its window opened, the variable resets to the first entry again for next time.

	struct List *selList = NULL;
	
	if ((IWorkbench->WorkbenchControl(NULL, WBCTRLA_GetSelectedIconList, &selList, TAG_DONE)) == FALSE) {
		return Original_OpenWindowTagList(Self,nw, tagList);
	}


	// check on active window to distinguish between main desktop and other windows
	// if it not 0 by LeftEdge, then most probably this is not main desktop window

	ULONG lock = IIntuition->LockIBase(0);
	int LeftEdge = ((struct IntuitionBase *)IntuitionBase)->ActiveWindow->LeftEdge;
	IIntuition->UnlockIBase(lock);
	
	if ( LeftEdge != 0) goto end;
		 
	// a bit of error checking to avoid unexpected crashes if no icons are selected.
	
	struct Node *n = IExec->GetHead(selList);
	if (!n) goto end;
	
	// Call GetSucc() 'which_icon' times, to get which_icon'th entry in the list.
	// don't forget to check on NULL just in case the number of selected icons changed unexpectedly.
	
	for(int i=0; i<which_icon; i++)  {
		n = IExec->GetSucc(n);
		if (!n) {
			which_icon = 0;
			goto end;
		}
	}
	
	// Check if it DISK or not, to allow us to use original workbench when need it (with "wbrun" and Filer's "Open Workbench").
	// Without this check, we can't navigate in workbench windows in original form. And we can't use WhichWorkbenchObject() +
	// WBDISK to check, as it rely on mouse pointer, which not always the case (like when do "open" from Workbench's menu).
	// So if the last character of the icon name is not ":" , we return to original, but if is ":" (so DISK), then handle it over.
	
	char *icon_name = n->ln_Name;
	if (!icon_name || !icon_name[0] || icon_name[strlen(icon_name)-1] != ':') goto end;
	
	// Now construct a string to run: name of binary and partition in quotes.
	// (quotes are must for taking spaces into account, like for "Ram Disk:")
	
	char *command_line = NULL;
	
	int ret = asprintf(&command_line, "%s%c%c%s%c", filer_binary, ' ', '"', icon_name, '"');
	if (ret < 0) goto end;
	
	// set our error checking flag to TRUE, so to return NULL at the end, as everything were good for us.
	ok = TRUE;

	// Set to disable flashing of DisplayBeep() only for our hack, and keep it original for other processes.
	// We do it right before calling command, to minimize the risks of meeting with DisplayBeep from other processes
	
	disable_flash_beep = TRUE;
	
	// Run an actual command:
	
	IDOS->SystemTags(command_line,
		SYS_Asynch, TRUE,
		SYS_Input,  IDOS->DupFileHandle(IDOS->Input()),
		SYS_Output, IDOS->DupFileHandle(IDOS->Output()),
	TAG_DONE);
	
	free(command_line);

	which_icon++;
	
	// Are we done with selected icons ?
	
	n = IExec->GetSucc(n);
	if (!n) {
		// Clean global variable of selected icons
		
		which_icon = 0; 
	
		// Unselect all the selected icons (to avoid situations when icon keeps selected,
		// but you trying to open original WB windows by "wbrun" or by Filer itself)
		
		struct Hook *hook = IExec->AllocSysObjectTags(ASOT_HOOK, ASOHOOK_Entry, UnSelectIcon, TAG_DONE);
		IWorkbench->ChangeWorkbenchSelection(NULL, hook, TAG_DONE);
		IExec->FreeSysObject(ASOT_HOOK, hook);
	}

end:
	IWorkbench->WorkbenchControl(NULL, WBCTRLA_FreeSelectedIconList,selList, TAG_DONE);

	return ok ? NULL : Original_OpenWindowTagList(Self, nw, tagList);

}


void init()
{
	screen = IIntuition->LockPubScreen(NULL);
	
	Original_OpenWindowTagList = IExec->SetMethod((struct Interface *)IIntuition, offsetof(struct IntuitionIFace, OpenWindowTagList),  (APTR)Patched_OpenWindowTagList);
	Original_DisplayBeep = IExec->SetMethod((struct Interface *)IIntuition, offsetof(struct IntuitionIFace, DisplayBeep),  (APTR)Patched_DisplayBeep);
	
}

void deinit()
{
	if(Original_DisplayBeep) {
		IExec->SetMethod((struct Interface *)IIntuition, offsetof(struct IntuitionIFace, DisplayBeep),  (APTR)Original_DisplayBeep);
	}

	if(Original_OpenWindowTagList) {
		IExec->SetMethod((struct Interface *)IIntuition, offsetof(struct IntuitionIFace, OpenWindowTagList),  (APTR)Original_OpenWindowTagList);
	}

	if(screen) IIntuition->UnlockPubScreen(NULL, screen);

}


int main (int argc, char* argv[])
{	
	
	if (argc !=2) {
		printf ("you need to specify a PATH to the Filer binary\n");
		exit(0);
	}

	filer_binary = argv[1];
   
	init();
	IDOS->Printf("patching activated\n");
	
	// CTRL+C check
	while(1) {
		if(IExec->Wait(SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C) break;
	}	
	
	deinit();
	IDOS->Printf("patching cleaned\n");

}
