/*
 *  CenterScreen.c
 *
 *  Commodity
 *
 *  Author: Stefan Sticht
 *
 *  Copyright: source is public domain, no copyright
 *
 *  Version history:
 *
 *  V1.01   initial release
 *  V1.02   knows how to center lores and superhires screens
 *  V1.03   recompiled with main.c V1.02
 *  V1.04   completly rewritten; shared commodity code thrown away; smaller, uses less CPU time
 *  V1.05   some really minor changes
 */

#define VERSION "V1.05"

/********************************************************************
 *                             interfacing                          *
 ********************************************************************/

/*
 *  include files
 */

#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <graphics/gfxbase.h>
#include <intuition/intuitionbase.h>
#include <libraries/commodities.h>

#include <clib/alib_protos.h>
#include <clib/commodities_protos.h>
#include <pragmas/commodities_pragmas.h>
#include <clib/dos_protos.h>
#include <pragmas/dos_pragmas.h>
#include <clib/exec_protos.h>
#include <pragmas/exec_pragmas.h>
#include <clib/intuition_protos.h>
#include <pragmas/intuition_pragmas.h>

#ifdef DEBUG
#define printf KPrintF
#include <clib/dlib_protos.h>
#endif

/*
 *  prototypes
 */
long request(char *title, char *gadgets, char *text, ...);
struct Library *myopenlibrary(char *name, unsigned long version);
void processmessages(void);

/*
 *  global data defined in other moduls
 *
 *  libraries opened by startup code; basepointers needed by function pragmas
 */
extern struct Library *DOSBase;
extern struct Library *SysBase;

/*
 *  Disable SAS/C CTRL/C handling
 */
void chkabort(void) {}

/********************************************************************
 *                             global data                          *
 ********************************************************************/

/*
 *  definition of all messages (multi language support not completed yet)
 */
#ifdef GERMAN

#define RETRY_GADGETS           "Wiederholen|Abbrechen"
#define RESUME_GADGETS          "Weiter"
#define MSG_LIBRARY_OPENERR     "Die %s (V%ld+) kann nicht geöffnet werden!"
#define COM_NAME                "ZentriereSchirm"
#define COM_DESCR               "Zentriert Bildschirm mit "
#define TT_ACTION               "AKTION"
#define NO                      "NEIN"
#define YES                     "JA"

#else

#define RETRY_GADGETS           "Retry|Cancel"
#define RESUME_GADGETS          "Resume"
#define MSG_LIBRARY_OPENERR     "%s (V%ld+) can't be opened!"
#define COM_NAME                "CenterScreen"
#define COM_DESCR               "Center frontmost screen on "
#define TT_ACTION               "ACTION"
#define YES                     "YES"
#define NO                      "NO"

#endif

#define COM_TITLE           COM_NAME " " VERSION
#define CX_PRIORITY         "CX_PRIORITY"
#define DEF_CX_PRIORITY     0

#define DEF_TT_ACTION       "lcommand c"

/*
 *  data for cback.o
 */
long _stack = 2048l;
char *_procname = COM_NAME;
long _priority = 0l;
long _BackGroundIO = 1;
extern BPTR _Backstdout;

/*
 *  library base pointers
 */
struct GfxBase *GfxBase;
struct IntuitionBase *IntuitionBase;
struct Library *CxBase;
struct Library *IconBase;

/*
 *  message port
 */
struct MsgPort *cxport = NULL;

/*
 *  signal flag
 */
unsigned long cxsigflag = 0l;

/*
 *  programtitle and version for Version command
 */
char versionstring[] ="\0$VER: " COM_NAME " " VERSION;

/*
 *  helpstring
 */
#ifdef GERMAN
char helpstring[] = "\033[1m" COM_NAME "\033[0m " VERSION " (Public Domain) von Stefan Sticht\n"\
                    "Aufruf: " COM_NAME " [" CX_PRIORITY "=<n>] [" TT_ACTION "=<Aktion>]\n";
#else
char helpstring[] = "\033[1m" COM_NAME "\033[0m " VERSION " (Public Domain) by Stefan Sticht\n"
                    "Usage: " COM_NAME " [" CX_PRIORITY "=<n>] [" TT_ACTION "=<action>]\n";
#endif

/*
 *  the tooltypearray
 */
char **tooltypes;

/*
 *  our broker
 */
CxObj *broker = NULL;

char descr[CBD_DESCRLEN + 1] = COM_DESCR;

struct NewBroker newbroker = {
    NB_VERSION,                         /* BYTE nb_Version               */
    COM_NAME,                           /* BYTE *nb_Name                 */
    COM_TITLE,                          /* BYTE *nb_Title                */
    descr,                              /* BYTE *nb_Descr                */
    NBU_NOTIFY | NBU_UNIQUE,            /* SHORT nb_Unique               */
    0,                                  /* SHORT nb_Flags                */
    0,                                  /* BYTE nb_Pri                   */
    NULL,                               /* struct MsgPort nb_Port        */
    0                                   /* WORD nb_ReservedChannel       */
};

#define CENTERSCREEN 1

/********************************************************************
 *                             functions                            *
 ********************************************************************/

#define pos(x) ((x > 0) ? x : 0)

/*
 *  request(): a glue routine to EasyRequest as simple as printf plus
 *             titlestring, gadgettexts
 *
 *  Input: char *title:         pointer to the title of the requester
 *         char *gadgets:       pointer to gadgettext
 *         char *text:          text displayed in requester
 *
 *  Result: same as EasyrequestArgs()
 *
 * !!! for more info see EasyRequestArgs() in Autodocs/intuition.doc !!!
 */
long request(char *title, char *gadgets, char *text, ...)
{
    /*
     *  structure textreq only needed in this function, so hide it here
     *  must be static, in order to be initialized only once
     */
    static struct EasyStruct textreq = {
        sizeof (struct EasyStruct), /* ULONG es_StructSize      */
        0l,                         /* ULONG es_Flags           */
        NULL,                       /* UBYTE *es_Title          */
        NULL,                       /* UBYTE *es_TextFormat     */
        NULL,                       /* UBYTE *es_GadgetFormat   */
        };
    va_list ap;
    long rc;

    /*
     *  get start of variable arguments
     */
    va_start(ap, text);

    /*
     *  update textreq
     */
    textreq.es_Title = (UBYTE *)title;
    textreq.es_TextFormat = (UBYTE *)text;
    textreq.es_GadgetFormat = (UBYTE *)gadgets;

    /*
     *  win may be NULL
     */
    rc = EasyRequestArgs(NULL, &textreq, NULL, ap);

    va_end(ap);

    return(rc);
}

/*
 *  myopenlibrary(): same as OpenLibrary(), but opens a retry-requester
 *                   if OpenLibrary() fails, to give the user a chance to
 *                   copy the library to libs: and retry
 *                   requires request(), see above
 */
struct Library *myopenlibrary(char *name, unsigned long version)
{
    static char errortext[] = MSG_LIBRARY_OPENERR;
    struct Library *libptr;
    long ok = TRUE;

    do {
        if (!(libptr = OpenLibrary((UBYTE *)name, version))) {
            if (IntuitionBase) {
                ok = request(COM_NAME ":", RETRY_GADGETS, errortext, name, version);
                }
            else ok = FALSE;
            }
        } while (!libptr && ok);

    #ifdef DEBUG
    printf("myopenlibrary(%s, %ld) = 0x%lx\n", name, version, libptr);
    #endif
    return(libptr);
}

void main(int argc, char *argv[])
{
    CxObj *centerfilter;
    char *centeraction;
    struct Message *msg;
    unsigned long len;

    if ((argc > 1) && (*argv[1] == '?')) {
        /*
         *  display help string
         */
        if (_Backstdout) {
            Write(_Backstdout, helpstring, sizeof(helpstring) - 1l);
            Close(_Backstdout);
            }
        return;
        }
    else if (argc && _Backstdout) Close(_Backstdout);

    /*
     *  open required libraries first
     */
    if (IntuitionBase = (struct IntuitionBase *)myopenlibrary("intuition.library", 37l)) {

        if (CxBase = myopenlibrary("commodities.library", 37l)) {

            if (IconBase = myopenlibrary("icon.library", 37l)) {

                if (GfxBase = (struct GfxBase *)myopenlibrary("graphics.library", 37l)) {

                    /*
                     * create tooltypes array (requires icon.library open!!!)
                     */
                    tooltypes = (char **)ArgArrayInit(argc, argv);

                    /*
                     *  create our message port
                     */
                    if (cxport = CreateMsgPort()) {

                        cxsigflag = 1l << cxport->mp_SigBit;
                        /*
                         * set up some broker data
                         */
                        newbroker.nb_Pri = ArgInt(tooltypes, CX_PRIORITY, DEF_CX_PRIORITY);
                        newbroker.nb_Port = cxport;

                        if ((centeraction = ArgString(tooltypes, TT_ACTION, DEF_TT_ACTION)) &&
                            *centeraction) {

                            len = strlen(descr);
                            strncpy(descr + len, centeraction, sizeof(descr) - len - 2l);

                            if (broker = CxBroker(&newbroker, NULL)) {

                                if (centerfilter = HotKey(centeraction, cxport, CENTERSCREEN)) {

                                    AttachCxObj(broker, centerfilter);

                                    if (!CxObjError(centerfilter)) {

                                        /*
                                         *  activate our commodity
                                         */
                                        ActivateCxObj(broker, 1l);
                                        /*
                                         *  now watch our numerous ports
                                         */
                                        processmessages();

                                        } /* if !CxObjError() */

                                    } /* if centerfilter */

                                DeleteCxObjAll(broker);

                                } /* if broker */

                            #ifdef DEBUG
                            else printf("main(): CxBroker() failed!\n");
                            #endif

                            } /* if centeraction */

                        /*
                         *  delete our message port after replying all pending messages
                         */
                        while (msg = GetMsg(cxport)) ReplyMsg(msg);
                        DeleteMsgPort(cxport);
                        } /* if cxport */

                    #ifdef DEBUG
                    else printf("main(): CraeteMsgPort() failed!\n");
                    #endif

                    ArgArrayDone();

                    CloseLibrary((struct Library *)GfxBase);
                    } /* if GfxBase */

                CloseLibrary(IconBase);
                } /* if IconBase */

            CloseLibrary(CxBase);
            } /* if CxBase */

    CloseLibrary((struct Library *)IntuitionBase);
    } /* if IntuitionBase */

} /* main() */

void processmessages(void)
{
    struct Message *msg;
    struct Screen *scr;
    unsigned long lock;
    unsigned long msgid;
    unsigned long msgtype;
    unsigned long sigreceived;
    unsigned short leftedge;
    unsigned short normalwidth; 
    unsigned short width;
    unsigned short quit = FALSE;

    while (!quit) {

        sigreceived = Wait(SIGBREAKF_CTRL_C | cxsigflag);

        #ifdef DEBUG
        printf("processmessages(): signal received\n");
        #endif

        if (sigreceived & SIGBREAKF_CTRL_C) quit = TRUE;

        if (sigreceived & cxsigflag) {

            while (msg = (struct Message *)GetMsg(cxport)) {

                msgid = CxMsgID((CxMsg *)msg);
                msgtype = CxMsgType((CxMsg *)msg);

                ReplyMsg(msg);

                switch (msgtype) {

                    case CXM_IEVENT:
                        switch (msgid) {

                            case CENTERSCREEN:
                                normalwidth = GfxBase->NormalDisplayColumns;
                                lock = LockIBase(0l);
                                if (scr = IntuitionBase->FirstScreen) {

                                    width = scr->Width;

                                    if (!(scr->ViewPort.Modes & HIRES)) {
                                        /*
                                         *  lores screen (I hope so): half normalwidth
                                         */
                                        normalwidth >>= 1;
                                        }

                                    else if (scr->ViewPort.Modes & SUPERHIRES) {
                                        /*
                                         *  superhires screen: double normalwidth
                                         */
                                        normalwidth <<= 1;
                                        }

                                    if (scr && (width < normalwidth)) {
                                        leftedge = pos((normalwidth - width) >> 1);
                                        UnlockIBase(lock);
                                        MoveScreen(scr, (long)(leftedge - scr->LeftEdge), 0l);
                                        }
                                    else UnlockIBase(lock);

                                    } /* if (scr = IntuitionBase->FirstScreen) */

                                else UnlockIBase(lock);

                                break;

                            } /* switch msgid */

                        break;

                    case CXM_COMMAND:
                        switch (msgid) {

                            case CXCMD_UNIQUE:
                            case CXCMD_KILL:
                                quit = TRUE;
                                break;

                            case CXCMD_DISABLE:
                                ActivateCxObj(broker, 0l);
                                break;

                            case CXCMD_ENABLE:
                                ActivateCxObj(broker, 1l);
                                break;

                            }
                        break;

                    } /* switch msgtype */

                } /* while CxMsg */

            } /* if (sigreceived & cxsigflag) */

        } /* while !quit */

    ActivateCxObj(broker, 0l);
}
