/* menu.c- generic menu class, used for root menu, application menus etc.
 *
 *  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 <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#include "generic/wwmlib.h"
#include "WindowMaker.h"
#include "wcore.h"
#include "button.h"
#include "menu.h"
#include "actions.h"
#include "funcs.h"
#include "stacking.h"

/****** Global Variables ******/

extern Cursor wCursor[WCUR_LAST];

extern XContext wWinContext;

extern WPreferences wPreferences;


static void menuMouseDown(WObjDescriptor *desc, XButtonEvent *bev);
static void menuTitleMouseDown(WObjDescriptor *desc, XButtonEvent *bev);
static void menuTitleDoubleClick(WObjDescriptor *desc, XEvent *event);
static void menuCloseClick(WObjDescriptor *desc, XEvent *unused);


static WMethodTable wMenuMethods = {
    (WEventHandler)menuMouseDown,
      NULL,
      NULL,
      NULL
};

static WMethodTable wMenuTitlebarMethods = {
    (WEventHandler)menuTitleMouseDown,
    NULL,
    (WEventHandler)menuTitleDoubleClick,
    NULL
};


static WMethodTable wMenuButtonMethods;


void
wMenuInitialize()
{
    memcpy(&wMenuButtonMethods, &wButtonMethods, sizeof(WMethodTable));
    wMenuButtonMethods.click = menuCloseClick;
}


/*
 *----------------------------------------------------------------------
 * wMenuCreate--
 * 	Creates a new empty menu with the specified title. If main_menu
 * is True, the created menu will be a main menu, which has some special
 * properties such as being placed over other normal menus.
 * 	If title is NULL, the menu will have no titlebar.
 * 
 * Returns:
 * 	The created menu.
 *---------------------------------------------------------------------- 
 */
WMenu *
wMenuCreate(WScreen *screen, char *title, int main_menu)
{
    WMenu *menu;
    WButton *wbut=NULL;
    int title_h, title_w;
    int width, height;
    int bsize;
    static int brother=0;
    
    menu = wmalloc(sizeof(WMenu));

    memset(menu, 0, sizeof(WMenu));
    if (title) {
	menu->title = strdup(title);
	title_w = MyTextWidth(screen->menu_title_font.font, title, 
			      strlen(title));
	title_h = MIN_TITLEFONT_HEIGHT(screen->menu_title_font.height) + 9;
    } else {
	title_w = 0;
	title_h = 0;
    }
    menu->entry_no = 0;
    menu->alloced_entries = 0;
    menu->selected_entry = -1;
    menu->entries = NULL;
    
    if (title) {
	width = title_w + title_h + 7;
#ifdef NEWSTYLE
	width += 5;
#endif
	height = title_h*2;
    } else {
	width = 1;
	height = 1;
    }
    menu->frame = wCoreCreateTopLevel(screen, 8, 2, width, height, 0, False);
    menu->frame_x = screen->app_menu_x;
    menu->frame_y = screen->app_menu_y;
    menu->frame->descriptor.parent = menu;
    menu->frame->descriptor.parent_type = WCLASS_MENU;
    menu->frame->descriptor.methods = &wMenuMethods;
    
    /* setup stacking information */
    menu->frame->stacking = wmalloc(sizeof(WStacking));
    menu->frame->stacking->above = NULL;
    menu->frame->stacking->under = NULL;
    menu->frame->stacking->child_of = NULL;
#ifdef SINGLE_MENULEVEL
    menu->frame->stacking->window_level = NSSubmenuWindowLevel;
#else
    menu->frame->stacking->window_level =
      (main_menu ? NSMainMenuWindowLevel : NSSubmenuWindowLevel);
#endif
    menu->flags.lowered = 0;

    /* create borders */
    if (title) {
#ifdef NEWSTYLE
	menu->titlebar = wCoreCreate(menu->frame, 0, 0, menu->frame->width,
				     title_h);
	bsize = title_h;
	if (!brother) {
	    wbut = wButtonCreate(menu->frame, width - bsize,
				 0, bsize-1, bsize);
	    wbut->texture = screen->menu_title_texture;
	    wbut->image1 = wbut->image = screen->b_pixmaps[WBUT_CLOSE];
	}
#else
	menu->titlebar = wCoreCreate(menu->frame, 0, 0, menu->frame->width,
				     title_h);
	bsize = (title_h - 8);
	if (!brother) {
	    wbut = wButtonCreate(menu->titlebar, width - 4 - bsize, 
				 (title_h + 1 - bsize)/2, bsize, bsize);
	    wbut->image = screen->b_pixmaps[WBUT_CLOSE];
	}
#endif
	/* setup object descriptors */
	menu->titlebar->descriptor.parent = menu;
	menu->titlebar->descriptor.parent_type = WCLASS_MENU;
	menu->titlebar->descriptor.methods = &wMenuTitlebarMethods;

	if (!brother) {
	    wbut->core->descriptor.parent = menu;
	    wbut->core->descriptor.parent_type = WCLASS_MENU;
	    wbut->core->descriptor.methods = &wMenuButtonMethods;
	    menu->close_button = wbut;
	} else {
	    menu->close_button = NULL;
	}
    }
    
    menu->menu = wCoreCreate(menu->frame, 0, title_h, width, height-title_h);

    menu->menu->descriptor.parent = menu;
    menu->menu->descriptor.parent_type = WCLASS_MENU;
    menu->menu->descriptor.methods = &wMenuMethods;
    
    menu->menu_texture_data = 0;
    menu->titlebar_texture_data = 0;
    if (title)
      XMapWindow(dpy, menu->titlebar->window);
    XMapWindow(dpy, menu->menu->window);

    AddToStackList(menu->frame);

    XFlush(dpy);
    
    if (!brother) {
	brother = 1;
	menu->brother = wMenuCreate(screen, title, main_menu);
	brother = 0;
	menu->brother->flags.brother = 1;
	menu->brother->brother = menu;
    }
    return menu;
}




WMenu*
wMenuCreateForApp(WScreen *screen, char *title, int main_menu)
{
    WMenu *menu;
    
    menu = wMenuCreate(screen, title, main_menu);
    if (!menu)
      return NULL;
    menu->flags.app_menu = 1;
    menu->brother->flags.app_menu = 1;
#ifdef NEWSTYLE
    if (menu->close_button)
      menu->close_button->texture = screen->appmenu_title_texture;
#endif
    return menu;
}



static void
insertEntry(WMenu *menu, WMenuEntry *entry, int index)
{
    int i;
    
    for (i=menu->entry_no; i>index; i--) {
	menu->entries[i]->order++;
	menu->entries[i+1]=menu->entries[i];
    }
    menu->entries[index] = entry;
}




WMenuEntry * 
wMenuInsertCallback(WMenu *menu, int index, char *text,
		    void (*callback)(WMenu *menu, WMenuEntry *entry), 
		    void *clientdata)
{
    WMenuEntry *entry;

#ifdef DEBUG
    if (!menu) {
	printf("Passed NULL as menu parameter to wMenuAddCallback() \n");
	return NULL;
    }    
#endif

    menu->flags.realized = 0;
    menu->brother->flags.realized = 0;
    
    /* reallocate array if it's too small */
    if (menu->entry_no >= menu->alloced_entries) {
	void *tmp;
#ifdef DEBUG
	puts("doing wrealloc()");
#endif	
	tmp = wrealloc(menu->entries,
		      sizeof(WMenuEntry)*(menu->alloced_entries+5));
	if (tmp==NULL) {
	    wWarning(_("wrealloc() failed while trying to add menu item"));
	    return NULL;
	}
	menu->entries = tmp;
	menu->alloced_entries += 5;
	
	menu->brother->entries = tmp;
	menu->brother->alloced_entries = menu->alloced_entries;
    }
    entry = wmalloc(sizeof(WMenuEntry));
    entry->flags.enabled = 1;    
    entry->text = strdup(text);
    entry->rtext = NULL;
    entry->cascade = -1;
    entry->clientdata = clientdata;
    entry->free_cdata = NULL;
    entry->callback = callback;
    if (index<0 || index>=menu->entry_no) {
	entry->order = menu->entry_no;
	menu->entries[menu->entry_no] = entry;
    } else {
	entry->order = index;
	insertEntry(menu, entry, index);
    }
    
    menu->entry_no++;
    menu->brother->entry_no = menu->entry_no;
    
    return entry;
}



void
wMenuEntrySetCascade(WMenu *menu, WMenuEntry *entry, WMenu *cascade)
{
    WMenu *brother = menu->brother;
    int i, done;

    menu->flags.realized = 0;
    cascade->parent = menu;

    brother->flags.realized = 0;
    cascade->brother->parent = brother;
    
    
    done = 0;
    for (i=0; i<menu->cascade_no; i++) {
	if (menu->cascades[i]==NULL) {
	    menu->cascades[i] = cascade;
	    brother->cascades[i] = cascade->brother;
	    done = 1;
	    entry->cascade = i;
	    break;
	}
    }
    if (!done) {
	entry->cascade = menu->cascade_no;

	menu->cascades = wrealloc(menu->cascades, 
				  sizeof(WMenu)*(menu->cascade_no+1));
	menu->cascades[menu->cascade_no++] = cascade;
	

	brother->cascades = wrealloc(brother->cascades, 
				     sizeof(WMenu)*(brother->cascade_no+1));
	brother->cascades[brother->cascade_no++] = cascade->brother;
    }


    if (menu->flags.lowered) {
	
	cascade->flags.lowered = 1;
	ChangeStackingLevel(cascade->frame, NSNormalWindowLevel);
	
	cascade->brother->flags.lowered = 1;
	ChangeStackingLevel(cascade->brother->frame, NSNormalWindowLevel);
    }    
}



void
wMenuRemoveItem(WMenu *menu, int index)
{
    int i;
    
    if (menu->flags.brother) {
	wMenuRemoveItem(menu->brother, index);
	return;
    }
    
    if (index>=menu->entry_no) return;

    /* destroy cascade menu */
    if (menu->entries[index]->cascade>=0) {
	wMenuDestroy(menu->cascades[menu->entries[index]->cascade], True);
	wMenuDestroy(menu->brother->cascades[menu->entries[index]->cascade],
		     True);

	menu->cascades[menu->entries[index]->cascade] = NULL;
	menu->brother->cascades[menu->entries[index]->cascade] = NULL;

	menu->entries[index]->cascade = -1;
    }
    
    /* destroy unshared data */

    if (menu->entries[index]->text)
      free(menu->entries[index]->text);
    
    if (menu->entries[index]->rtext)
      free(menu->entries[index]->rtext);
	
    if (menu->entries[index]->free_cdata && menu->entries[index]->clientdata)
      (*menu->entries[index]->free_cdata)(menu->entries[index]->clientdata);

    wfree(menu->entries[index]);
	
    for (i=index; i<menu->entry_no-1; i++) {
	menu->entries[i+1]->order--;
	menu->entries[i]=menu->entries[i+1];
    }
    menu->entry_no--;
    menu->brother->entry_no--;
}



void 
wMenuRealize(WMenu *menu)
{
    int i;
    int width, mwidth, extra_width, bsize;
    int theight, eheight;
    WScreen *scr = menu->frame->screen_ptr;
    static int brother_done=0;


    if (!brother_done) {
	brother_done = 1;
	wMenuRealize(menu->brother);
	brother_done = 0;
    }
    
    menu->flags.realized = 1;
    if (menu->title) {
	mwidth = MyTextWidth(scr->menu_title_font.font, menu->title, 
			     strlen(menu->title));
	theight = MIN_TITLEFONT_HEIGHT(scr->menu_title_font.height) + 9;
#ifdef NEWSTYLE
	mwidth += 5;
#endif
    } else {
	mwidth = 0;
	theight = 0;
    }
    eheight = scr->menu_entry_font.height + 6;
    menu->entry_height = eheight;
    extra_width = MyTextWidth(scr->menu_entry_font.font, "F8", 2) + 16;
    
    for (i=0; i<menu->entry_no; i++) {
	char *text, *rtext;

	text = menu->entries[i]->text;
	rtext = menu->entries[i]->rtext;
	width = MyTextWidth(scr->menu_entry_font.font, text, strlen(text));
	if (rtext)
	  width += MyTextWidth(scr->menu_entry_font.font, rtext, strlen(rtext));
	if (width > mwidth)
	  mwidth = width;
    }
    wCoreConfigure(menu->frame, menu->frame_x, menu->frame_y, 
		   mwidth + extra_width, theight + menu->entry_no * eheight);
    wCoreConfigure(menu->menu, 0, theight, mwidth + extra_width, 
		   menu->entry_no * eheight);

    if (menu->title) {
#ifdef NEWSTYLE
	bsize = menu->titlebar->height;
	if (menu->flags.buttoned) {
	    wCoreConfigure(menu->titlebar, 0, 0, menu->frame->width-(bsize-3),
			   bsize);
	} else {
	    wCoreConfigure(menu->titlebar, 0, 0, mwidth+extra_width, bsize);
	}
	
	if (menu->close_button) {
	    XMoveWindow(dpy, menu->close_button->core->window,
			menu->frame->width - (bsize-1), 0);

	    if (menu->flags.app_menu)
	      wTextureFreeData(menu->frame->screen_ptr->appmenu_title_texture,
			       &menu->close_button->texture_data);
	    else
	      wTextureFreeData(menu->frame->screen_ptr->menu_title_texture,
			       &menu->close_button->texture_data);
	}
#else
	wCoreConfigure(menu->titlebar, 0, 0, menu->frame->width, theight);
	
	if (menu->close_button) {
	    bsize = menu->close_button->core->width;
	    XMoveWindow(dpy,menu->close_button->core->window, mwidth 
			+ extra_width - 4 - bsize, (theight + 1 -bsize)/2);
	}
#endif
    }
    if (!menu->flags.brother) {
	if (menu->flags.app_menu) 
	  wTextureFreeData(menu->frame->screen_ptr->appmenu_title_texture,
			   &menu->titlebar_texture_data);
	else
	  wTextureFreeData(menu->frame->screen_ptr->menu_title_texture,
			   &menu->titlebar_texture_data);

	wTextureFreeData(menu->frame->screen_ptr->menu_item_texture,
			 &menu->menu_texture_data);
    }
    /* setup background texture */
    switch (scr->menu_item_texture->any.type) {
     case WTEX_GRADIENT:
	wTextureRender(scr, scr->menu_item_texture, 
		       &menu->menu_texture_data, menu->menu->width,
		       menu->entry_height);
	XSetWindowBackgroundPixmap(dpy, menu->menu->window, 
				   menu->menu_texture_data);
	break;
     default:
	XSetWindowBackground(dpy, menu->menu->window,
			     scr->menu_item_texture->any.color.pixel);
    }
    if (menu->flags.mapped)
      wMenuPaint(menu);
}



void
wMenuDestroy(WMenu *menu, int recurse)
{
    int i;
    WCoreWindow *frame=menu->frame;
    WScreen *scr=frame->screen_ptr;

    
#ifdef BUGGYSTACKING
    /* remove from stacking list */
    if (frame->stacking->under)
      frame->stacking->under->stacking->above = frame->stacking->above;
    if (frame->stacking->above)
      frame->stacking->above->stacking->under = frame->stacking->under;
    else /* this was the first window on the list */
      scr->stacking_list = frame->stacking->under;
    menu->frame->screen_ptr->window_count--;
#else /* BUGGYSTACKING */
    RemoveFromStackList(frame);
#endif /* !BUGGYSTACKING */

#ifdef NEWSTYLE
    if (menu->close_button) {
	if (menu->flags.app_menu)
	  wTextureFreeData(scr->appmenu_title_texture,
			   &menu->close_button->texture_data);
	else
	  wTextureFreeData(scr->menu_title_texture,
			   &menu->close_button->texture_data);
    }
#endif
    
    /* the copy of the menu share the same textures of the original */

    if (!menu->flags.brother) {
	if (menu->flags.app_menu)
	  wTextureFreeData(scr->appmenu_title_texture,
			   &menu->titlebar_texture_data);
	else
	  wTextureFreeData(scr->menu_title_texture, 
			   &menu->titlebar_texture_data);

	wTextureFreeData(scr->menu_item_texture, &menu->menu_texture_data);
    }
    
    /* Destroy items if this menu own them. If this is the "brother" menu,
     * leave them alone.
     */
    if (!menu->flags.brother) {
	for (i=0; i<menu->entry_no; i++) {

	    wfree(menu->entries[i]->text);

	    if (menu->entries[i]->rtext)
	      wfree(menu->entries[i]->rtext);

	    if (menu->entries[i]->free_cdata && menu->entries[i]->clientdata) {
		(*menu->entries[i]->free_cdata)(menu->entries[i]->clientdata);
	    }
	    wfree(menu->entries[i]);
	}

	if (recurse) {
	    for (i=0; i<menu->cascade_no; i++) {
		if (menu->cascades[i]) {
		    if (menu->cascades[i]->flags.brother)
		      wMenuDestroy(menu->cascades[i]->brother, recurse);
		    else
		      wMenuDestroy(menu->cascades[i], recurse);
		}
	    }
	}
	
	if (menu->entries)
	  wfree(menu->entries);
    }
    
    if (menu->cascades)
      wfree(menu->cascades);

    
    if (!menu->flags.brother && menu->title) {
	  wfree(menu->title);
    }
    
    if (menu->close_button)
      wButtonDestroy(menu->close_button);
    
    if (menu->titlebar)
      wCoreDestroy(menu->titlebar);

    wCoreDestroy(menu->menu);
    wCoreDestroy(menu->frame);
    
    /* destroy copy of this menu */
    if (!menu->flags.brother && menu->brother)
      wMenuDestroy(menu->brother, False);
    
    wfree(menu);
}


static void
drawFrame(WScreen *scr, Window win, int y, int w, int h)
{
    XSegment segs[4];

    segs[0].x1 = 1;
    segs[0].y1 = y;
    segs[0].x2 = w-2;
    segs[0].y2 = y;
    segs[1].x1 = 1;
    segs[1].y1 = y;
    segs[1].x2 = 1;
    segs[1].y2 = y + h - 2;
    XDrawSegments(dpy, win, scr->menu_item_auxtexture->light_gc, segs, 2);
    
    segs[0].x1 = 1;
    segs[0].x2 = w-1;
    segs[0].y1 = segs[0].y2 = y + h-1;
    segs[1].x1 = segs[1].x2 = w-1;
    segs[1].y1 = y;
    segs[1].y2 = y + h-1;
    XDrawSegments(dpy, win, scr->menu_item_auxtexture->dark_gc, segs, 2);
    
    segs[0].x1 = 2;
    segs[0].y1 = segs[0].y2 = y + h-2;
    segs[0].x2 = w-2;
    segs[1].x1 = segs[1].x2 = w-2;
    segs[1].y1 = y + 1;
    segs[1].y2 = y + h-2;
    segs[2].x1 = segs[2].x2 = 0;
    segs[2].y1 = y;
    segs[2].y2 = y + h-1;
    XDrawSegments(dpy, win, scr->menu_item_auxtexture->dim_gc, segs, 3);
}


static void
paintEntry(WMenu *menu, int index, int selected)
{
    int y, w, h, tw;
    GC light, dim, dark, textGC;
    WScreen *scr=menu->frame->screen_ptr;
    Window win = menu->menu->window;
    WMenuEntry *entry=menu->entries[index];

    if (!menu->flags.realized) return;
    h = menu->entry_height;
    w = menu->menu->width;
    y = index * h;

    light = scr->menu_item_auxtexture->light_gc;
    dim = scr->menu_item_auxtexture->dim_gc;
    dark = scr->menu_item_auxtexture->dark_gc;

    /* paint background */
    if (selected) {
	XSetForeground(dpy, scr->select_menu_gc, scr->white_pixel);
	XFillRectangle(dpy, win, scr->select_menu_gc, 0, y, w, h);
	drawFrame(scr, win, y, w, h);
    } else {
	XClearArea(dpy, win, 0, y, w, h, False);

	switch (scr->menu_item_texture->any.type) {
	 case WTEX_SOLID:
	    /* draw the frame */
	    drawFrame(scr, win, y, w, h);
	    break;
	}
    }

    if (entry->cascade>=0) {
	/* draw the cascade indicator */
	XDrawLine(dpy,win,dim, w-11, y+6, w-6, y+h/2-1);
	XDrawLine(dpy,win,light, w-11, y+h-8, w-6, y+h/2-1);
	XDrawLine(dpy,win,dark, w-12, y+6, w-12, y+h-8);
    }

    /* draw text */
    if (selected) {
	textGC = scr->select_menu_gc;
	XSetForeground(dpy, textGC, scr->black_pixel);
    } else if (entry->flags.enabled) {
	textGC = scr->menu_entry_gc;
    } else {
	textGC = scr->disabled_menu_entry_gc;
    }
#ifdef I18N_MB
    XmbDrawString(dpy, win, scr->menu_entry_font.font, 
		  textGC, 6, 3+y+scr->menu_entry_font.y, entry->text, 
		strlen(entry->text));
#else
    XDrawString(dpy, win, textGC, 6, 3+y+scr->menu_entry_font.y, entry->text, 
		strlen(entry->text));
#endif
    if (entry->rtext && entry->cascade<0) {
	tw = MyTextWidth(scr->menu_entry_font.font, entry->rtext,
			 strlen(entry->rtext));
#ifdef I18N_MB
	XmbDrawString(dpy, win, scr->menu_entry_font.font, 
		      textGC, w-6-tw, 3+y+scr->menu_entry_font.y, entry->rtext,
		      strlen(entry->rtext));
#else
	XDrawString(dpy, win, textGC, w-6-tw,3+y+scr->menu_entry_font.y, 
		    entry->rtext, strlen(entry->rtext));
#endif
    }
}


void
wMenuMapAt(WMenu *menu, int x, int y)
{
    int scr_width = menu->frame->screen_ptr->scr_width;
    int scr_height = menu->frame->screen_ptr->scr_height;

    if (!menu->flags.realized) {
	menu->flags.realized=1;
	wMenuRealize(menu);
    }
    if (x<0) x = 0;
    if (y<0) y = 0;
    if (x+menu->frame->width > scr_width)
      x = scr_width - menu->frame->width;
    if (y+menu->frame->height > scr_height)
      y = scr_height - menu->frame->height;
	
    XMoveWindow(dpy, menu->frame->window, x, y);
    menu->frame_x = x;
    menu->frame_y = y;
    XMapWindow(dpy, menu->frame->window);
    wRaiseFrame(menu->frame);
    menu->flags.mapped = 1;
}


void
wMenuMapCopyAt(WMenu *menu, int x, int y)
{
    wMenuMapAt(menu->brother,x,y);
}


void
wMenuMap(WMenu *menu)
{
    if (!menu->flags.realized) {
	menu->flags.realized=1;
	wMenuRealize(menu);
    }
    if (menu->flags.app_menu && menu->parent==NULL) {
	menu->frame_x = menu->frame->screen_ptr->app_menu_x;
	menu->frame_y = menu->frame->screen_ptr->app_menu_y;
	XMoveWindow(dpy, menu->frame->window, menu->frame_x, menu->frame_y);
    }
    XMapWindow(dpy, menu->frame->window);
    wRaiseFrame(menu->frame);
    menu->flags.mapped = 1;
}


void
wMenuUnmap(WMenu *menu)
{
    int i;

    XUnmapWindow(dpy, menu->frame->window);
    if (menu->title && menu->flags.buttoned) {
	XUnmapWindow(dpy, menu->close_button->core->window);
#ifdef NEWSTYLE
	wCoreConfigure(menu->titlebar, 0, 0, menu->frame->width,
		       menu->titlebar->height);
#endif
    }
    menu->flags.buttoned = 0;
    menu->flags.mapped = 0;
    menu->flags.open_to_left = 0;

    for (i=0; i<menu->cascade_no; i++) {
	if (menu->cascades[i]!=NULL
	    && menu->cascades[i]->flags.mapped 
	    && !menu->cascades[i]->flags.buttoned) {
	    
	    wMenuUnmap(menu->cascades[i]);
	}
    }
    menu->selected_entry = -1;
} 


void 
wMenuPaint(WMenu *menu)
{
    int i;
    WScreen *scr = menu->frame->screen_ptr;
    
    if (menu->title) {
	/* paint titlebar */
	if (menu->flags.brother) {
	    if (menu->flags.app_menu)
	      wTexturePaint(scr->appmenu_title_texture, 
			    &menu->brother->titlebar_texture_data,
			    menu->titlebar, 
			    False);
	    else
	      wTexturePaint(scr->menu_title_texture, 
			    &menu->brother->titlebar_texture_data,
			    menu->titlebar, False);
	} else {
	    if (menu->flags.app_menu)
	      wTexturePaint(scr->appmenu_title_texture, 
			    &menu->titlebar_texture_data, menu->titlebar, 
			    False);
	    else
	      wTexturePaint(scr->menu_title_texture,
			    &menu->titlebar_texture_data, menu->titlebar, 
			    False);
	}
	
#ifdef I18N_MB
	XmbDrawString(dpy, menu->titlebar->window, scr->menu_title_font.font, 
		      scr->menu_title_gc, 6, 
		      (menu->titlebar->height-scr->menu_title_font.height)/2
		      + scr->menu_title_font.y, menu->title, 
		      strlen(menu->title));
#else
	XDrawString(dpy, menu->titlebar->window, scr->menu_title_gc, 6,
		    (menu->titlebar->height-scr->menu_title_font.height)/2
		    + scr->menu_title_font.y, menu->title, 
		    strlen(menu->title));
#endif
    }
    /* paint entries */
    for (i=0; i<menu->entry_no; i++) {
	paintEntry(menu, i, i==menu->selected_entry);
    }
    if (menu->title && menu->flags.buttoned)
      wButtonPaint(menu->close_button, False);
}


void
wMenuSetEnabled(WMenu *menu, int index, int enable)
{
    if (index>=menu->entry_no) return;
    menu->entries[index]->flags.enabled=enable;
    paintEntry(menu, index, index==menu->selected_entry);
    paintEntry(menu->brother, index, index==menu->selected_entry);
}


/* ====================================================================== */


static void
selectEntry(WMenu *menu, int entry_no)
{
    WMenuEntry *entry;
    WMenu *submenu;

    if (menu->selected_entry!=entry_no) {
	
	/* unselect previous entry */
	if (menu->selected_entry>=0) {
	    
	    entry = menu->entries[menu->selected_entry];
	    paintEntry(menu, menu->selected_entry, False);
	    entry = menu->entries[menu->selected_entry];
	    
	    /* unmap cascade */
	    if (entry->cascade>=0) {
		if (!menu->cascades[entry->cascade]->flags.buttoned) {
		    wMenuUnmap(menu->cascades[entry->cascade]);
		}
	    }
	}
	if (entry_no<0) {
	    menu->selected_entry = -1;
	    return;
	}
	entry = menu->entries[entry_no];
	if (entry->flags.enabled) {
	    
	    if (entry->cascade>=0) {
		
		submenu = menu->cascades[entry->cascade];

		/* map cascade */
		if (!submenu->flags.mapped) {
		    int x, y;
		    
		    if (!submenu->flags.realized)
		      wMenuRealize(submenu);
		    
		    if (menu->flags.open_to_left)
		      submenu->flags.open_to_left = 1;
		    
		    if (submenu->flags.open_to_left) {
			x = menu->frame_x - submenu->frame->width;
			if (x<0) {
			    x = 0;
			    submenu->flags.open_to_left = 0;
			}
		    } else {
			x = menu->frame_x + menu->frame->width;
			
			if (x + submenu->frame->width
			    > menu->frame->screen_ptr->scr_width) {
			    
			    x = menu->frame_x - submenu->frame->width;
			    submenu->flags.open_to_left = 1;
			}
		    }
		    if (wPreferences.align_menus) {
			y = menu->frame_y;
		    } else {
			y = menu->frame_y + menu->entry_height*entry_no;
		    }
		    wMenuMapAt(menu->cascades[entry->cascade], x, y);
		    menu->cascades[entry->cascade]->parent = menu;
		    
		} else 
		  return;
	    }
	    menu->selected_entry = entry_no;
	    paintEntry(menu, entry_no, True);
	} else {
	    menu->selected_entry = -1;
	}
    }    
}



static WMenu*
findMenu(WScreen *scr, int *x_ret, int *y_ret)
{
    WMenu *menu;
    WObjDescriptor *desc;
    Window root_ret, win, junk_win;
    int x, y, wx, wy;
    unsigned int mask;
    
    XQueryPointer(dpy, scr->root_win, &root_ret, &win, &x, &y, &wx, &wy,
		  &mask);
    
    if (win==None) return NULL;
    
    if (XFindContext(dpy, win, wWinContext, (XPointer *)&desc)==XCNOENT)
      return NULL;
    
    if (desc->parent_type==WCLASS_MENU) {
	menu = desc->parent;
	XTranslateCoordinates(dpy, root_ret, menu->menu->window, wx, wy, 
			      x_ret, y_ret, &junk_win);
	return menu;
    }
    
    return NULL;
}


static void
closeCascade(WMenu *menu)
{
    WMenu *parent=menu->parent;

    if (menu->flags.brother 
	|| (!menu->flags.buttoned 
	    && (!menu->flags.app_menu||menu->parent!=NULL))) {

	selectEntry(menu, -1);
	XSync(dpy, 0);
#if (MENU_BLINK_DELAY > 2)
	wmsleep(MENU_BLINK_DELAY/2);
#endif
	wMenuUnmap(menu);
	while (parent!=NULL 
	       && (parent->parent!=NULL || !parent->flags.app_menu
		   ||parent->flags.brother)
	       && !parent->flags.buttoned) {
	    selectEntry(parent, -1);
	    wMenuUnmap(parent);
	    parent = parent->parent;
	}
	if (parent)
	  selectEntry(parent, -1);
    }
}



#define getEntryAt(menu, x, y)   ((y)<0 ? -1 : (y)/(menu->entry_height))

static void  
menuMouseDown(WObjDescriptor *desc, XButtonEvent *bev)
{
    WMenu *menu=desc->parent;
    WMenu *smenu;
    WScreen *scr=menu->frame->screen_ptr;    
    WMenuEntry *entry=NULL;
    XEvent event;
    int close_on_exit=0;
    int done=0;
    int entry_no;
    int x, y;


    wRaiseFrame(menu->frame);
    
    close_on_exit = (bev->send_event || menu->flags.brother);
    
    smenu = findMenu(scr, &x, &y);
    if (!smenu) {
	x = -1;
	y = -1;
    } else {
	menu = smenu;
    }
    entry_no = getEntryAt(menu, x, y);
    if (entry_no>=0) {
	entry = menu->entries[entry_no];
	
	if (entry->flags.enabled && entry->cascade>=0) {
	    WMenu *submenu = menu->cascades[entry->cascade];
	    
	    /* map cascade */
	    if (!submenu->flags.mapped) {
		selectEntry(menu, entry_no);
	    } else if (!submenu->flags.buttoned) {
		selectEntry(menu, -1);
	    }
	    
	} else {
	    
	    selectEntry(menu, entry_no);
	}
    }
    while (!done) {
	int x, y;
	XMaskEvent(dpy, ExposureMask|ButtonMotionMask|ButtonReleaseMask,
		   &event);
	switch (event.type) {
	 case MotionNotify:
	    smenu = findMenu(scr, &x, &y);
	    if (smenu == NULL) {
		if (menu==NULL
		    || (menu->selected_entry>=0
			&& menu->entries[menu->selected_entry]->cascade>=0))
		    break;
		selectEntry(menu, -1);
		menu = smenu;
		break;
	    } else if (menu && menu!=smenu &&
		       !(menu->selected_entry>=0
			 && menu->entries[menu->selected_entry]->cascade>=0)) {
		selectEntry(menu, -1);
	    }
	    menu = smenu;
	    entry_no = getEntryAt(menu, x, y);
	    selectEntry(menu, entry_no);
	    break;

	 case ButtonRelease:
	    done=1;
	    break;

	 case Expose: 
	    DispatchEvent(&event);
	    break;
 	}
    }

    if (menu && menu->selected_entry>=0) {
	entry = menu->entries[menu->selected_entry];
	/* erase menu selection */
	if (entry->callback!=NULL) {
#if (MENU_BLINK_DELAY > 0)
	    int sel = menu->selected_entry;
	    int i;

	    for (i=0; i<MENU_BLINK_COUNT; i++) {
		paintEntry(menu, sel, False);
		XSync(dpy, 0);
		wmsleep(MENU_BLINK_DELAY);
		paintEntry(menu, sel, True);
		XSync(dpy, 0);
		wmsleep(MENU_BLINK_DELAY);
	    }
#endif
	    /* unmap the menu, it's parents and call the callback */
	    if (!menu->flags.buttoned && 
		(!menu->flags.app_menu||menu->parent!=NULL)) {
		closeCascade(menu);
	    } else {
		selectEntry(menu, -1);
	    }
	    (*entry->callback)(menu, entry);

	    /* If the user double clicks an entry, the entry will
	     * be executed twice, which is not good for things like
	     * the root menu. So, ignore any clicks that were generated 
	     * while the entry was being executed */
	    while (XCheckTypedWindowEvent(dpy, menu->menu->window, 
					  ButtonPress, &event));
	} else {
	    if (close_on_exit || menu->flags.brother) {
		closeCascade(menu);
	    }
	    
	    if (entry->cascade>=0
		&& menu->cascades[entry->cascade]->flags.brother) {
		selectEntry(menu, -1);
	    }
	}
    } else {
	if (close_on_exit && (!menu || entry_no>=0 || menu->flags.brother)) {
	    if (menu) {
		closeCascade(menu);
	    } else {
		closeCascade(desc->parent);
	    }
	} else {
	    if (((WMenu*)desc->parent)->selected_entry>=0) {
		selectEntry(desc->parent, -1);
	    }
	}
    }
}


void
wMenuMove(WMenu *menu, int x, int y)
{
    WMenu *submenu;
    int i;
    
    if (!menu) return;
    
    menu->frame_x = x;
    menu->frame_y = y;
    XMoveWindow(dpy, menu->frame->window, x, y);
    
    if (menu->selected_entry>=0) {
	i = menu->entries[menu->selected_entry]->cascade;
	
	if (i>=0) {
	    submenu = menu->cascades[i];
	    if (submenu->flags.mapped && !submenu->flags.buttoned)
	      if (wPreferences.align_menus) {
		  wMenuMove(submenu, x + menu->frame->width, y);
	      } else {
		  wMenuMove(submenu, x+ menu->frame->width,
			    y + submenu->entry_height*menu->selected_entry);
	      }
	}
    }
}


static void
changeMenuLevels(WMenu *menu, int lower)
{
    int i;

    if (!lower) {
	ChangeStackingLevel(menu->frame, (!menu->parent ? NSMainMenuWindowLevel
					  : NSSubmenuWindowLevel));
	wRaiseFrame(menu->frame);
	menu->flags.lowered = 0;
    } else {
	ChangeStackingLevel(menu->frame, NSNormalWindowLevel);
	wLowerFrame(menu->frame);
	menu->flags.lowered = 1;
    }
    for (i=0; i<menu->cascade_no; i++) {
	if (menu->cascades[i]
	    && !menu->cascades[i]->flags.buttoned
	    && menu->cascades[i]->flags.lowered!=lower) {
	    changeMenuLevels(menu->cascades[i], lower);
	}
    }
}



static void 
menuTitleDoubleClick(WObjDescriptor *desc, XEvent *event)
{
    WMenu *menu=desc->parent;
    int lower;
    if (event->xbutton.state & Mod1Mask) {
	if (menu->flags.lowered) {
	    lower = 0;
	} else {
	    lower = 1;
	}
	changeMenuLevels(menu, lower);
    }
}


/*
 *---------------------------------------------------------------------- 
 * menuTitleMouseDown--
 * 	Handle ButtonPress events on the menu titlebar.
 * 
 * Side effects:
 * 	The pointer is grabbed until the button is released, but 
 * events are dispatched properly.
 * 
 * Notes:
 * 	Moves the menu according to user action and enables the close
 * button (stick) if the menu is moved.
 *---------------------------------------------------------------------- 
 */
static void 
menuTitleMouseDown(WObjDescriptor *desc, XButtonEvent *bev)
{
    WMenu *menu=desc->parent, *tmp;
    XEvent event;
    int x=menu->frame_x, y=menu->frame_y;
    int dx=bev->x_root, dy=bev->y_root;
    int i, lower;
    
#ifdef DEBUG
    puts("Moving menu");
#endif
    if (bev->button != Button1 && bev->button != Button2)
      return;
    if (XGrabPointer(dpy, menu->titlebar->window, False, 
		     ButtonMotionMask|ButtonReleaseMask,
		     GrabModeAsync, GrabModeAsync, None, 
		     wCursor[WCUR_MOVE], CurrentTime)!=GrabSuccess) {
#ifdef DEBUG0
	wWarning("pointer grab failed for menu move");
#endif
	return;
    }
    if (bev->state & Mod1Mask) {
	wLowerFrame(menu->frame);
	lower = 1;
    } else {
	wRaiseFrame(menu->frame);
	lower = 0;
    }
    tmp = menu;
    
    /* lower/raise all submenus */
    while (1) {
	if (tmp->selected_entry>=0) {
	    tmp = tmp->cascades[tmp->entries[tmp->selected_entry]->cascade];
	    if (!tmp || !tmp->flags.mapped)
	      break;
	    if (lower)
	      wLowerFrame(tmp->frame);
	    else
	      wRaiseFrame(tmp->frame);
	} else {
	    break;
	}
    }
    /* tear off the menu if it's a root menu or a cascade 
     application menu */
    if (!menu->flags.buttoned && !menu->flags.brother 
	&& (!menu->flags.app_menu||menu->parent!=NULL)) {
	XMapWindow(dpy, menu->close_button->core->window);
	menu->flags.buttoned=1;
#ifdef NEWSTYLE
	wCoreConfigure(menu->titlebar, 0, 0, 
		       menu->frame->width - (menu->titlebar->height-3),
		       menu->titlebar->height);
#endif
	if (menu->parent) {
	    /* turn off selected menu entry in parent menu */
	    selectEntry(menu->parent, -1);

	    /* 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;
		}
	    }
	}
    }    
    while(1) {
	XMaskEvent(dpy, ButtonMotionMask|ButtonReleaseMask|ExposureMask,
		   &event);
	switch (event.type) {
	 case MotionNotify:
	    x += event.xmotion.x_root - dx;
	    y += event.xmotion.y_root - dy;
	    dx = event.xmotion.x_root;
	    dy = event.xmotion.y_root;
	    wMenuMove(menu, x, y);
	    break;

	 case ButtonRelease:
#ifdef DEBUG
	    puts("End menu move");
#endif
	    XUngrabPointer(dpy, CurrentTime);
	    return;
	    
	 default:
	    DispatchEvent(&event);
	}
    }
}

/*
 *----------------------------------------------------------------------
 * menuCloseClick--
 * 	Handles mouse click on the close butoon of menus. The menu is
 * closed when the button is clicked. 
 * 
 * Side effects:
 * 	The closed menu is reinserted at it's parent menus
 * cascade list.
 *---------------------------------------------------------------------- 
 */
static void 
menuCloseClick(WObjDescriptor *desc, XEvent *unused)
{
    WMenu *menu=desc->parent;
    WMenu *parent=menu->parent;
    int i;
    
    if (parent) {
	for (i=0; i<parent->cascade_no; i++) {
	    /* find the entry that points to the copy */
	    if (parent->cascades[i] == menu->brother) {
		/* make it point to the original */
		parent->cascades[i] = menu;
		menu->parent = parent;
		break;
	    }
	}
    }
    wMenuUnmap(menu);
}



