/* Category ToolKit of Application class
 *
 * Copyright (C)  1994  The Board of Trustees of  
 * The Leland Stanford Junior University.  All Rights Reserved.
 *
 * Authors: Scott Francis, Fred Harris, Paul Kunz, Tom Pavel, 
 *	    Imran Qureshi, and Libing Wang
 *
 * This file is part of an Objective-C class library for X-Windows
 *
 * WARNING: All WidgetSets that use this ToolKit category must use the
 * same definition of XWContext in dpsclient/xwfriends.h.  FIXME.
 *
 * xtApplication.m,v 1.12 1995/12/13 22:33:33 fedor Exp
 */

#include "Application.h"
#include "Window.h"
#include "dpsclient/XtDrawContext.h"
#include <objc/List.h>
#include "stdmacros.h"
#ifdef	sgi
#include <malloc.h>	/* although you might need to edit malloc.h */
#endif	/* sgi */

void 
appMainLoop( void *app_con )
{
    XtAppMainLoop((XtAppContext) app_con);
    return;
}

void *
createApplicationContext( void )
{
    XtToolkitInitialize();
    return XtCreateApplicationContext();
}

void
destroyApplicationContext( void *app_con) 
{
    XtDestroyApplicationContext((XtAppContext)app_con);
    return;
}
void *
openDisplay( void *app_con, char *appName, int ac, char **av)
{

   void *display = XtOpenDisplay((XtAppContext)app_con, 0,
			    NULL, appName,
			    NULL, 0,
			     &ac, av);
   if ( !display) {
      XtWarning("cannot open display");
      exit(1);
   }
   return display;
}

@implementation Application(ToolKit)

- (int)_runModalFor:theWindow
{
    XEvent	event;
    Widget 	dlog = [theWindow _widget];
	
    _modalReturnCode = X_RUNNINGMODAL;
    XtAddGrab( dlog, True, True );
    while ((XtIsManaged(dlog)) && (_modalReturnCode == X_RUNNINGMODAL)) {
	XtAppNextEvent(app_con, &event);
	XtDispatchEvent(&event);
    }
    XtRemoveGrab( dlog );
    return _modalReturnCode;
}

/* Open the X-Windows display */
- _displayInitArgc:(int)ac argv:(char**)av
{
    XtDrawContext *ctxt;

    _X_display = openDisplay( app_con, appName, ac, av);
    if (!_X_display) {
        XtWarning("cannot open display");
	return nil;
    }
    
    /* Create a context */
    /* FIXME: Hide this behind a DPSCreateContext call */
    ctxt = [[XtDrawContext allocWithZone: [self zone]]
	  initWithDisplay:_X_display];
    _context = (DPSContext)[ctxt XWContext];

    return self;
}

@end

