/*                         TaskMenuCode.c                               */
/*       This module handles the functionality of the menus.            */
/*                            31-8-91                                   */

#include <exec/types.h>
#include <exec/tasks.h>
#include <intuition/intuition.h>
#include <graphics/gfxbase.h>
#include <libraries/dos.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>

#ifdef LATTICE
#include <proto/exec.h>
#include <proto/graphics.h>
#include <proto/intuition.h>
#endif

/*-My Headers-*/
#include "TaskTool.h"

#define NAMESDISPLAYED 8
#define TOTALGADGETS (NAMESDISPLAYED + 8)

/*-Prototypes-*/
BOOL HandleMenuPick(struct IntuiMessage *, struct TimeInfo *);
VOID About(VOID);
VOID Iconify(VOID);
extern VOID SendTimerRequest(struct TimeInfo *);
extern VOID AbortTimer(VOID);

/*-External Vars-*/
extern struct Menu TaskToolMenus[];
extern struct Gadget NameGads[];
extern TaskNode TaskList[];
extern TaskListInfo TaskToolInfo;
extern struct Window *TTWindow;
extern struct TextAttr TTTextAttr;
extern struct TextFont *TTfont;


/*------------------------------------------------------------------------*/
BOOL HandleMenuPick( msg, TimerInfo)
struct IntuiMessage *msg;
struct TimeInfo *TimerInfo;
/*  Handles the users' choice of menus. Supports multiple selection
 *  If Quit selected returns TRUE to close TaskTool down.
 */
{
    BOOL   Quit = FALSE;

    USHORT Selection,Flags;
    ULONG  menuNum,itemNum,subNum;
    struct MenuItem *i;
    struct Menu *FirstMenu = &TaskToolMenus[0];
    extern struct MenuItem Refresh_Timed[];

    Selection = msg->Code;
    while (Selection != MENUNULL)  {
        menuNum = MENUNUM(Selection);
        itemNum = ITEMNUM(Selection);
        subNum  = SUBNUM(Selection);
        Flags   = ((struct MenuItem *)ItemAddress(FirstMenu,
                    (LONG)Selection))->Flags;

        switch (menuNum) {
            case 0: /* TaskTool */
                switch (itemNum)  {
                    case 0: /* About... */
                        About();
                        break;
                    case 1: /* Iconify */
                        Iconify();
                        break;
                    case 2: /* Print */
                        break;
                    case 3: /* Quit */
                        Quit = TRUE;
                        break;
                    default:
                        break;
                }
                break;

            case 1: /* Refresh */
                switch (itemNum)  {
                    case 0: /* Manual */
                        if (TimerInfo->TimeStatus==RUNNING) {
                            /* Reset Timer Device- */
                            AbortTimer();
                            TimerInfo->TimeStatus=STOPPED;
                        }
                        for (i=&Refresh_Timed[0];i;i=i->NextItem)
                            i->Flags &= ~CHECKED; /* Uncheck times */

                        break;
                    case 1: /* Activity */
                        if (TimerInfo->TimeStatus==RUNNING) {
                            /* Reset Timer Device- */
                            AbortTimer();
                            TimerInfo->TimeStatus=STOPPED;
                        }
                        for (i=ItemAddress(FirstMenu,SHIFTMENU(1)|SHIFTITEM(2)|SHIFTSUB(0));
                          i;i=i->NextItem)
                            i->Flags &= ~CHECKED; /* Uncheck times */
                        break;
                    case 2: /* Timed »» */
                        /* Send a first IORequest to the device, future
                         * IO Requests are handled by the Wait() loop
                         * in main()
                         */

                         switch (subNum) {
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                                if (TimerInfo->TimeStatus==RUNNING) AbortTimer();

                                /* Check Main Menu Item */
                                ItemAddress(FirstMenu,SHIFTMENU(1)|SHIFTITEM(0))->Flags&=~CHECKED;
                                ItemAddress(FirstMenu,SHIFTMENU(1)|SHIFTITEM(1))->Flags&=~CHECKED;
                                ItemAddress(FirstMenu,SHIFTMENU(1)|SHIFTITEM(2))->Flags|=CHECKED;

                                /* Send Timer Request */
                                TimerInfo->TimeIndex=subNum;
                                SendTimerRequest(TimerInfo);
                                TimerInfo->TimeStatus=RUNNING;
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
                break;

            case 2: /* Task */
                switch (itemNum)  {
                    case 0: /* Suspend */
                        break;
                    case 1: /* Remove */
                        break;
                    default:
                        break;
                }
                break;

            default:
                break;

        } /* End of Menu Switch */

        Selection = ((struct MenuItem *)ItemAddress(FirstMenu,
                        (LONG)Selection))->NextSelect;

    } /* End While */

    return(Quit);
}

/*------------------------------------------------------------------------*/
VOID About(VOID)
/* Produces Information on TaskTool in a requester */
{
    UWORD TY=TTTextAttr.ta_YSize+2;
    struct Gadget *Fg=&NameGads[0];
    COUNT i;

    static struct IntuiText AboutText[6] = {
        { 2,1, JAM2, 20,0, &TTTextAttr,"TaskTool v0.8",NULL },
        { 2,1, JAM2, 20,0, &TTTextAttr,"Dynamic Task Priority Manager",NULL },
        { 2,1, JAM2, 20,0, &TTTextAttr,"© E.F.Pritchard 1991.",NULL },
        { 2,1, JAM2, 20,0, &TTTextAttr,"Freely Distributable",NULL },
        { 2,1, JAM2, 20,0, &TTTextAttr,"See ReadMe! for Details",NULL },
        { 2,1, JAM2, 6, 3, &TTTextAttr,"Continue",NULL }
    };

    for(i=0;i<5;i++) { /* Setup IntuiText Properly */
        AboutText[i].TopEdge=TY*(i+1);
        if (i<4) AboutText[i].NextText=&AboutText[i+1];
        };


    /* Remove Gadgets- This may seem unnecessary, but it
     * stops spurious input to the window, which AutoRequest(), unlike
     * Request() allows. I was going to disable all the gadgets too
     * but this just looked ugly and made users think 'What the hell is
     * going on?!!' ;-)
     */

    RemoveGList(TTWindow, Fg, TOTALGADGETS);

    AutoRequest( TTWindow, &AboutText[0], NULL, &AboutText[5], NULL, NULL,
        IntuiTextLength(&AboutText[1])+IntuiTextLength(&AboutText[5])+10,TY*10);

    AddGList(TTWindow, Fg, 0, TOTALGADGETS, NULL);

}

/*------------------------------------------------------------------------*/
VOID Iconify(VOID)
/*  Close main Tasktool window, trap RMB and open as small 'bar' window */
{
    struct IntuiMessage *msg;
    ULONG class;
    BOOL exit = FALSE;
    static BOOL Already = FALSE;

    static struct NewWindow IconNewWindow = {
        0,0,1,1,
        2,1,
        MOUSEBUTTONS,
        WINDOWDRAG|SMART_REFRESH|NOCAREREFRESH|RMBTRAP,
        NULL,NULL,
        "TaskTool",
        NULL,
        NULL,
        (~0),(~0),(~0),(~0),
        WBENCHSCREEN
        };

    struct Window *IconWindow;

    extern struct NewWindow TaskToolWin;    /* So we can open it again! */
    extern jmp_buf env; /* Environment we saved in main() */

    extern VOID CleanExit(int);
    extern VOID InitTaskTool( TaskListInfo *, BOOL);
    extern LONG DisposeTaskList(TaskNode TaskArray[], int ArrayCount);


    /* Free the TaskTool List... */
    if (TaskToolInfo.numentries) {
        DisposeTaskList(TaskList, TaskToolInfo.numentries);
        TaskToolInfo.numentries = 0;
    }

    /* ...Close the Main window... (nicely!) */
    if (TTWindow) {
        TaskToolWin.TopEdge = TTWindow->TopEdge;    /* Remember where user */
        TaskToolWin.LeftEdge = TTWindow->LeftEdge;  /* Positioned window */

        /* Remove Menu Strip */
        if (TTWindow->MenuStrip)  ClearMenuStrip(TTWindow);

        CloseWindow(TTWindow);
    }


    /* ...Open and Size the Iconify Window... */

    if (!(IconWindow = OpenWindow(&IconNewWindow))) CleanExit(RETURN_WARN);

    if (!Already) {     /* If static NewWindow struct not initialized */

        IconNewWindow.Width = TextLength(IconWindow->RPort,
            IconNewWindow.Title,strlen(IconNewWindow.Title))+7;

        IconNewWindow.Height = IconWindow->WScreen->BarHeight;

        SizeWindow(IconWindow,IconNewWindow.Width-1, IconNewWindow.Height-1);

        RefreshWindowFrame(IconWindow);

        Already = TRUE; /* For next Time */
    }


    /* ...Wait until we get a RMB event... */
    while (!exit) {
        Wait(1L << IconWindow->UserPort->mp_SigBit);
        while (msg= (struct IntuiMessage *)GetMsg(IconWindow->UserPort)) {
            class= msg->Class;
            switch(class) {
                case MOUSEBUTTONS:
                    if (msg->Code = MENUUP)  exit=TRUE;
                    break;
                default:
                    break;
            }
            ReplyMsg((struct Message *)msg);
        }
    }


    /* ...Close Iconify Window... */


    if (IconWindow) {
        IconNewWindow.TopEdge = IconWindow->TopEdge;    /* Save where */
        IconNewWindow.LeftEdge = IconWindow->LeftEdge;  /* User moved icon */

        if (IconWindow->MenuStrip)  ClearMenuStrip(IconWindow);
        CloseWindow(IconWindow);
    }


    /* ...Open TaskTool Window Again... */

    TTWindow = OpenWindow( &TaskToolWin );

    if (TTWindow) {
        SetFont(TTWindow->RPort, TTfont);
        SetMenuStrip(TTWindow, &TaskToolMenus[0]);
    }
    else
        CleanExit(RETURN_WARN);

    /* ...Redraw Window, but don't adjust those gadgets... */
    InitTaskTool( &TaskToolInfo, FALSE );

    /* Return to main and refresh TaskTool window. */
    longjmp(env, 1);
}

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/