/*
 *  WindowMaker window manager
 * 
 *  Copyright (c) 1997 Alfredo K. Kojima
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "wconfig.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#ifdef __FreeBSD__
#include <sys/signal.h>
#endif

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Intrinsic.h>
#include <X11/cursorfont.h>
#include <X11/Xproto.h>

#include "generic/wwmlib.h"
#include "WindowMaker.h"
#include "GNUstep.h"
#include "texture.h"
#include "screen.h"
#include "window.h"
#include "actions.h"
#include "client.h"
#include "funcs.h"
#include "dock.h"



#ifdef SYS_SIGLIST_DECLARED
extern const char * const sys_siglist[];
#endif
/****** Global Variables ******/

extern WPreferences wPreferences;

/* currently only single screen support */
extern WScreen wScreen;
/* modules */
extern int ModuleNo;

/* contexts */
extern XContext wWinContext;
extern XContext wAppWinContext;
extern XContext wStackContext;

/* atoms */
extern Atom _XA_WM_STATE;
extern Atom _XA_WM_CHANGE_STATE;
extern Atom _XA_WM_PROTOCOLS;
extern Atom _XA_WM_TAKE_FOCUS;
extern Atom _XA_WM_DELETE_WINDOW;
extern Atom _XA_WM_SAVE_YOURSELF;
extern Atom _XA_WM_CLIENT_LEADER;
extern Atom _XA_WM_COLORMAP_WINDOWS;

extern Atom _XA_GNUSTEP_WM_ATTR;

extern Atom _XA_WINDOWMAKER_MENU;
extern Atom _XA_WINDOWMAKER_WM_PROTOCOLS;
extern Atom _XA_WINDOWMAKER_STATE;

extern Atom _XA_GNUSTEP_WM_MINIATURIZE_WINDOW;
extern Atom _XA_GNUSTEP_WM_RESIZEBAR;

extern Atom _XA_GNUSTEP_WM_FUNCTION;
#if 0
extern Atom _XA_GNUSTEP_WM_RESIZE_WINDOW;
extern Atom _XA_GNUSTEP_WM_RESIZED_WINDOW;
#endif

/* cursors */
extern Cursor wCursor[WCUR_LAST];

static void manageAllWindows();

#ifdef DOCK
extern void NotifyDeadProcess(pid_t pid, unsigned char status);
#endif


static int 
catchXError(Display *dpy, XErrorEvent *error)
{
    char buffer[MAXLINE];
    
    /* ignore some errors */
    if (error->resourceid != None 
	&& ((error->error_code == BadDrawable 
	     && error->request_code == X_GetGeometry)
	    || (error->error_code == BadMatch
		&& (error->request_code == X_SetInputFocus))
	    || (error->error_code == BadWindow)
	    /*
		&& (error->request_code == X_GetWindowAttributes
		    || error->request_code == X_SetInputFocus
		    || error->request_code == X_ChangeWindowAttributes
		    || error->request_code == X_GetProperty
		    || error->request_code == X_ChangeProperty
		    || error->request_code == X_QueryTree
		    || error->request_code == X_GrabButton
		    || error->request_code == X_UngrabButton
		    || error->request_code == X_SendEvent
		    || error->request_code == X_ConfigureWindow))
	     */
	    || (error->request_code == X_InstallColormap))) {
#ifndef DEBUG
	return 0;
#else
	printf("got X error %x %x %x\n", error->request_code,
	       error->error_code, (unsigned)error->resourceid);
	return 0;
#endif
    }
    wFormatXError(dpy, error, buffer, MAXLINE); 
    wWarning(_("internal X error: %s\n"), buffer);
    return -1;
}


/*
 *----------------------------------------------------------------------
 * handleSig--
 * 	general signal handler. Exits the program gently.
 *---------------------------------------------------------------------- 
 */
static RETSIGTYPE
handleSig(int sig)
{
#ifdef SYS_SIGLIST_DECLARED
    wFatal(_("got signal %i (%s)\n"), sig, sys_siglist[sig]);
#else
    wFatal(_("got signal %i\n"), sig);
#endif

    wAbort();
    if (sig==SIGSEGV)
	abort();
    else
    	exit(1);
}

static RETSIGTYPE
ignoreSig(int signal)
{
    return;
}


static RETSIGTYPE
buryChild(int foo)
{
#ifdef DOCK
    pid_t pid;
#endif
    int status;
    
    /* R.I.P. */
    pid = waitpid(-1, &status, WNOHANG);
#ifdef DOCK
    if (pid>0) {
	NotifyDeadProcess(pid, WEXITSTATUS(status));
    }
#endif
}


static int
getWorkspaceState(Window root, WWorkspaceState **state)            
{
    Atom type_ret;
    int fmt_ret;    
    unsigned long nitems_ret;
    unsigned long bytes_after_ret;

    if (XGetWindowProperty(dpy, root, _XA_WINDOWMAKER_STATE, 0,
                           sizeof(WWorkspaceState),
                           True, _XA_WINDOWMAKER_STATE,
                           &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret,
                           (unsigned char **)state)!=Success)
      return 0;
    if (type_ret==_XA_WINDOWMAKER_STATE)
      return 1;
    else
      return 0;
}

       
/*
 *---------------------------------------------------------- 
 * StartUp--
 * 	starts the window manager and setup global data
 * 
 * Side effects:
 * global data declared in main.c is initialized
 *----------------------------------------------------------
 */
void 
StartUp()
{
    WWorkspaceState *ws_state;
    struct sigaction sig_action;
    
    ModuleNo = 1; /* 0 is ourself */

    wWinContext = XUniqueContext();
    wAppWinContext = XUniqueContext();
    wStackContext = XUniqueContext();
    _XA_WM_STATE = XInternAtom(dpy, "WM_STATE", False);
    _XA_WM_CHANGE_STATE = XInternAtom(dpy, "WM_CHANGE_STATE", False);
    _XA_WM_PROTOCOLS = XInternAtom(dpy, "WM_PROTOCOLS", False);
    _XA_WM_TAKE_FOCUS = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
    _XA_WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
    _XA_WM_SAVE_YOURSELF = XInternAtom(dpy, "WM_SAVE_YOURSELF", False);    
    _XA_WM_CLIENT_LEADER = XInternAtom(dpy, "WM_CLIENT_LEADER", False);
    _XA_WM_COLORMAP_WINDOWS = XInternAtom(dpy, "WM_COLORMAP_WINDOWS", False);
    
    _XA_GNUSTEP_WM_ATTR = XInternAtom(dpy, GNUSTEP_WM_ATTR_NAME, False);
    
    _XA_WINDOWMAKER_MENU = XInternAtom(dpy, "_WINDOWMAKER_MENU", False);
    _XA_WINDOWMAKER_STATE = XInternAtom(dpy, "_WINDOWMAKER_STATE", False);

    _XA_WINDOWMAKER_WM_PROTOCOLS =
      XInternAtom(dpy, "_WINDOWMAKER_WM_PROTOCOLS", False);

    _XA_GNUSTEP_WM_MINIATURIZE_WINDOW = 
      XInternAtom(dpy, GNUSTEP_WM_MINIATURIZE_WINDOW, False);
    
    _XA_GNUSTEP_WM_RESIZEBAR =
      XInternAtom(dpy, GNUSTEP_WM_RESIZEBAR, False);

    _XA_GNUSTEP_WM_FUNCTION = XInternAtom(dpy, GNUSTEP_WM_FUNCTION, False);    
#if 0
    _XA_GNUSTEP_WM_RESIZE_WINDOW =
      XInternAtom(dpy, GNUSTEP_WM_RESIZE_WINDOW, False);
    _XA_GNUSTEP_WM_RESIZED_WINDOW = 
      XInternAtom(dpy, GNUSTEP_WM_RESIZED_WINDOW, False);
#endif
    /* cursors */
    wCursor[WCUR_NORMAL] = XCreateFontCursor(dpy, XC_left_ptr);    
    wCursor[WCUR_ARROW] = XCreateFontCursor(dpy, XC_top_left_arrow);
    wCursor[WCUR_MOVE] = XCreateFontCursor(dpy, XC_fleur);
    wCursor[WCUR_RESIZE] = XCreateFontCursor(dpy, XC_sizing);
    wCursor[WCUR_WAIT] = XCreateFontCursor(dpy, XC_watch);
    wCursor[WCUR_QUESTION] = XCreateFontCursor(dpy, XC_question_arrow);
    wCursor[WCUR_TEXT]     = XCreateFontCursor(dpy, XC_xterm); /* odd name???*/
    
    /* right now, only works for the deault screen */
    wScreen = *wScreenInit(DefaultScreen(dpy));
    XSetErrorHandler((XErrorHandler)catchXError);
    
    /* emergency exit... */
    signal(SIGINT, handleSig);
    signal(SIGHUP, handleSig);
    signal(SIGTERM, handleSig);
    signal(SIGQUIT, handleSig);
    signal(SIGSEGV, handleSig);
    signal(SIGBUS, handleSig);
    signal(SIGFPE, handleSig);
    
    /* handle dead children */
    sig_action.sa_handler = buryChild;
    sigemptyset(&sig_action.sa_mask);
    sig_action.sa_flags = SA_NOCLDSTOP;
    sigaction(SIGCHLD, &sig_action, NULL);

    /* ignore dead pipe */
    sig_action.sa_handler = ignoreSig;
    sigemptyset(&sig_action.sa_mask);
    sigaction(SIGPIPE, &sig_action, NULL);

    
    /* restore workspace state */
    if (!getWorkspaceState(wScreen.root_win, &ws_state)) {
        ws_state = NULL;
    } else {
	wScreen.last_workspace = ws_state->workspace;
    }

#ifdef DOCK
    /* create and display the application dock */
    if (!wPreferences.flags.nodock) {
	char *path;
	wScreen.dock = wDockCreate(&wScreen);
	if (ws_state)
	  wScreen.dock->y_pos = ws_state->dock_position;
	path = find_file(DEF_USERPREF_PATH, DEF_DOCKCONFIG);
	wDockRestoreState(wScreen.dock, path);
	free(path);
    }
#endif

    /* manage all windows that were already 
     * here before us */
    manageAllWindows(&wScreen);
    

    if (ws_state && (ws_state->flags & WSS_ROOTMENU)) {
	/* restore root menu position */
	OpenRootMenu(&wScreen, ws_state->menu_x, ws_state->menu_y);
	wMenuMove(wScreen.root_menu, ws_state->menu_x, ws_state->menu_y);
	XMapWindow(dpy, wScreen.root_menu->close_button->core->window);
	wScreen.root_menu->flags.buttoned = 1;
    } else if (wPreferences.root_menu_pos.x>0) {
	/* map the root menu at the specified position */
	OpenRootMenu(&wScreen, wPreferences.root_menu_pos.x, 
		     wPreferences.root_menu_pos.y);
	wMenuMove(wScreen.root_menu, wPreferences.root_menu_pos.x, 
		     wPreferences.root_menu_pos.y);
	XMapWindow(dpy, wScreen.root_menu->close_button->core->window);
	wScreen.root_menu->flags.buttoned = 1;
    }

    if (ws_state) {
	if (ws_state->flags & WSS_SWITCHMENU) {
	    /* restore window list menu position */
	    OpenSwitchMenu(&wScreen, ws_state->smenu_x, ws_state->smenu_y);
	    wMenuMove(wScreen.switch_menu, ws_state->smenu_x, ws_state->smenu_y);
	    XMapWindow(dpy, wScreen.switch_menu->close_button->core->window);
	    wScreen.switch_menu->flags.buttoned = 1;
	}
	
	
	if (!wScreen.root_menu) {
	    OpenRootMenu(&wScreen, wScreen.scr_width*2, 0);
	    wMenuUnmap(wScreen.root_menu);
	}
	if (ws_state->flags & WSS_WSMENU) {
	    WMenu *menu = wScreen.workspace_menu;
	    int i;	    
	    
	    /* restore workspace menu position */
	    wMenuMapAt(menu, ws_state->wmenu_x, ws_state->wmenu_y);
	    XMapWindow(dpy, menu->close_button->core->window);
	    menu->flags.buttoned = 1;
	    if (menu->parent) {
		/* make parent map the copy in place of the original */
		for (i=0; i<menu->parent->cascade_no; i++) {
		    if (menu->parent->cascades[i] == menu) {
			menu->parent->cascades[i] = menu->brother;
			break;
		    }
		}
	    }
	}
    }
    
#ifdef DOCK
    /* auto-launch apps */
    if (!wPreferences.flags.nodock && wScreen.dock) {
	wDockDoAutoLaunch(wScreen.dock);
    }
#endif

    /* go to workspace where we were before restart */
    if (ws_state) { 
	wChangeWorkspace(&wScreen, ws_state->workspace);
        XFree(ws_state);
    }
}



static int
getState(Window window)
{
    Atom type;
    int form;
    unsigned long nitems, bytes_rem;
    unsigned char *data;

    if (XGetWindowProperty(dpy, window, _XA_WM_STATE, 0, 3, False,
			   _XA_WM_STATE, &type,&form,&nitems,&bytes_rem,
			   &data)==Success) {
      if (data != NULL)
	  return *(long *)data;
    }
    return -1;
}


/*
 *-----------------------------------------------------------------------
 * manageAllWindows--
 * 	Manages all windows in the screen.
 * 
 * Notes:
 * 	Called when the wm is being started.
 *	No events can be processed while the windows are being
 * reparented/managed. 
 *----------------------------------------------------------------------- 
 */
static void
manageAllWindows(WScreen *scr)
{
    Window root, parent;
    Window *children;
    unsigned int nchildren;
    XWindowAttributes wattribs;
    unsigned int i, j;
    int state;
    WWindow *wwin;
    XWMHints *wmhints;
    
    XGrabServer(dpy);
    XQueryTree(dpy, scr->root_win, &root, &parent, &children, &nchildren);

    scr->flags.startup = 1;
    
    /* first remove all icon windows */
    for (i=0; i<nchildren; i++) {
	if (children[i]==None) 
	  continue;

    	wmhints = XGetWMHints(dpy, children[i]);
	if (wmhints && (wmhints->flags & IconWindowHint)) {
	    for (j = 0; j < nchildren; j++)  {
		if (children[j] == wmhints->icon_window) {
		    children[j] = None;
		    break;
		}
	    }
	}
    }
    /* map all windows without OverrideRedirect */
    for (i=0; i<nchildren; i++) {
	if (children[i]==None) 
	  continue;

	XGetWindowAttributes(dpy, children[i], &wattribs);

	state = getState(children[i]);
	if (!wattribs.override_redirect 
	    && (state>=0 || wattribs.map_state!=IsUnmapped)) {
	    XUnmapWindow(dpy, children[i]);
	    
	    if (state==WithdrawnState) {
		/* move the window far away so that it doesn't flash */
		XMoveWindow(dpy, children[i], scr->scr_width+10,
			    scr->scr_height+10);
	    }
	    wwin = wManageWindow(scr, children[i]);
	    if (wwin) {
		if (state==WithdrawnState) {
		    wwin->flags.mapped = 0;
		    wClientSetState(wwin, WithdrawnState, None);
		    XSelectInput(dpy, wwin->client_win, NoEventMask);
		    XRemoveFromSaveSet(dpy, wwin->client_win);
		    wUnmanageWindow(wwin, True);
		} else
		/* apply states got from WSavedState */
		if (wwin->flags.shaded) {
		    wShadeWindow(wwin);
		} else if (wwin->flags.hidden) {
		    WApplication *wapp = wApplicationOf(wwin->main_window);
		    wwin->flags.hidden = 0;
		    if (wapp)
		    	wHideApplication(wapp);
		    wwin->flags.ignore_next_unmap=1;
		} else {
		    if (wwin->wm_hints && (wwin->wm_hints->flags & StateHint)
			&& state<0)
		      state=wwin->wm_hints->initial_state;
		    if (state==IconicState) {
			wIconifyWindow(wwin);
			wwin->flags.ignore_next_unmap=1;
		    } else {
			wClientSetState(wwin, NormalState, None);
		    }
		}
	    }
	    if (state==WithdrawnState) {
		/* move the window back to it's old position */
		XMoveWindow(dpy, children[i], wattribs.x, wattribs.y);
	    }
	}
    }
    scr->flags.startup = 0;
    XUngrabServer(dpy);
    XFree(children);
    while (XPending(dpy)) {
	XEvent ev;
	wNextEvent(&ev);
	DispatchEvent(&ev);
    }
    scr->workspace = -1;
    wChangeWorkspace(scr, 0);
}



