home *** CD-ROM | disk | FTP | other *** search
/ Magazyn Amiga 5 / MA_Cover_5.iso / ppc / mesa / src-glut / glut_menu.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-01-31  |  32.2 KB  |  1,125 lines

  1. /* Copyright (c) Mark J. Kilgard, 1994, 1997. */
  2.  
  3. /* This program is freely distributable without licensing fees
  4.    and is provided without guarantee or warrantee expressed or
  5.    implied. This program is -not- in the public domain. */
  6.  
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <errno.h>
  11. #include <assert.h>
  12.  
  13. #if !defined(WIN32)
  14. #include <unistd.h>
  15. #include <X11/Xlib.h>
  16. #include <X11/cursorfont.h>  /* for XC_arrow */
  17. #endif /* !WIN32 */
  18.  
  19. #include <GL/glut.h>
  20. #include "glutint.h"
  21. #include "layerutil.h"
  22.  
  23. GLUTmenu *__glutCurrentMenu = NULL;
  24. void (*__glutMenuStatusFunc) (int, int, int);
  25. GLUTmenu *__glutMappedMenu;
  26. GLUTwindow *__glutMenuWindow;
  27. GLUTmenuItem *__glutItemSelected;
  28.  
  29. static GLUTmenu **menuList = NULL;
  30. static int menuListSize = 0;
  31. static XFontStruct *menuFont = NULL;
  32. static Cursor menuCursor;
  33. static Colormap menuColormap;
  34. static Visual *menuVisual;
  35. static int menuDepth;
  36. static int fontHeight;
  37. static GC blackGC, grayGC, whiteGC;
  38. static unsigned long menuBlack, menuWhite, menuGray;
  39. static unsigned long useSaveUnders;
  40.  
  41. #if !defined(WIN32)
  42. /* A replacement for XAllocColor (originally by Brian Paul).
  43.    This  function should never fail to allocate a color.  When
  44.    XAllocColor fails, we return the nearest matching color.  If
  45.    we have to allocate many colors this function isn't a great
  46.    solution; the XQueryColors() could be done just once.  */
  47. static void
  48. noFaultXAllocColor(Display * dpy, Colormap cmap, int cmapSize,
  49.   XColor * color)
  50. {
  51.   XColor *ctable, subColor;
  52.   int i, bestmatch;
  53.   double mindist;       /* 3*2^16^2 exceeds 32-bit long int
  54.                            precision. */
  55.  
  56.   /* First try just using XAllocColor. */
  57.   if (XAllocColor(dpy, cmap, color))
  58.     return;
  59.  
  60.   /* Retrieve color table entries. */
  61.   /* XXX alloca canidate. */
  62.   ctable = (XColor *) malloc(cmapSize * sizeof(XColor));
  63.   for (i = 0; i < cmapSize; i++)
  64.     ctable[i].pixel = i;
  65.   XQueryColors(dpy, cmap, ctable, cmapSize);
  66.  
  67.   /* Find best match. */
  68.   bestmatch = -1;
  69.   mindist = 0.0;
  70.   for (i = 0; i < cmapSize; i++) {
  71.     double dr = (double) color->red - (double) ctable[i].red;
  72.     double dg = (double) color->green - (double) ctable[i].green;
  73.     double db = (double) color->blue - (double) ctable[i].blue;
  74.     double dist = dr * dr + dg * dg + db * db;
  75.     if (bestmatch < 0 || dist < mindist) {
  76.       bestmatch = i;
  77.       mindist = dist;
  78.     }
  79.   }
  80.  
  81.   /* Return result. */
  82.   subColor.red   = ctable[bestmatch].red;
  83.   subColor.green = ctable[bestmatch].green;
  84.   subColor.blue  = ctable[bestmatch].blue;
  85.   if (!XAllocColor(dpy, cmap, &subColor)) {
  86.     /* do this to work around a problem reported by Frank Ortega */
  87.     subColor.pixel = (unsigned long) bestmatch;
  88.     subColor.red   = ctable[bestmatch].red;
  89.     subColor.green = ctable[bestmatch].green;
  90.     subColor.blue  = ctable[bestmatch].blue;   
  91.     subColor.flags = DoRed | DoGreen | DoBlue;
  92.   }
  93.   free(ctable);
  94.   *color = subColor;
  95. }
  96.  
  97. static int
  98. ifSunCreator(void)
  99. {
  100.   char *xvendor, *glvendor, *renderer;
  101.   int isSunCreator = 0; /* Until proven that it is. */
  102.   int savedDisplayMode;
  103.   char *savedDisplayString;
  104.   GLUTwindow *window;
  105.  
  106. #define VENDOR_SUN "Sun Microsystems"
  107. #define RENDERER_CREATOR "Creator"
  108.  
  109.   /* Check the X vendor string first.  It is easier to check
  110.      than the OpenGL vendor and renderer strings since it
  111.      doesn't require a valid OpenGL rendering context.  Bail
  112.      early if not connected to a Sun. */
  113.   xvendor = ServerVendor(__glutDisplay);
  114.   if (!strncmp(xvendor, VENDOR_SUN, sizeof(VENDOR_SUN) - 1)) {
  115.  
  116.     /* We need a valid current OpenGL rendering context to be
  117.        able to call glGetString successfully.  If there is not
  118.        a current window, set up a temporary one just to call
  119.        glGetString with (gag, expensive). */
  120.     if (__glutCurrentWindow) {
  121.       window = NULL;
  122.     } else {
  123.       savedDisplayMode = __glutDisplayMode;
  124.       savedDisplayString = __glutDisplayString;
  125.       __glutDisplayMode = GLUT_RGB | GLUT_SINGLE;
  126.       __glutDisplayString = NULL;
  127.       window = __glutCreateWindow(NULL, 0, 0, 1, 1);
  128.     }
  129.  
  130.     glvendor = (char *) glGetString(GL_VENDOR);
  131.     if (!strncmp(glvendor, VENDOR_SUN, sizeof(VENDOR_SUN) - 1)) {
  132.       renderer = (char *) glGetString(GL_RENDERER);
  133.       if (!strncmp(renderer, RENDERER_CREATOR, sizeof(RENDERER_CREATOR) - 1)) {
  134.         isSunCreator = 1;
  135.       }
  136.     }
  137.     /* Destroy the temporary window for glGetString if one
  138.        needed to be created. */
  139.     if (window) {
  140.       __glutDestroyWindow(window, window);
  141.       __glutDisplayMode = savedDisplayMode;
  142.       __glutDisplayString = savedDisplayString;
  143.     }
  144.   }
  145.   return isSunCreator;
  146. }
  147.  
  148. static void
  149. menuVisualSetup(void)
  150. {
  151.   XLayerVisualInfo template, *visual, *overlayVisuals;
  152.   XColor color;
  153.   Status status;
  154.   Bool presumablyMesa;
  155.   int layer, nVisuals, i, dummy;
  156.   unsigned long *placeHolders = NULL;
  157.   int numPlaceHolders;
  158.   Bool allocateHigh;
  159.  
  160.   allocateHigh = ifSunCreator();
  161.  
  162.   /* Start with the highest overlay layer and work down.  I
  163.      don't think any hardware has more than 3 overlay layers. */
  164.   for (layer = 3; layer > 0; layer--) {
  165.     template.layer = layer;
  166.     template.vinfo.screen = __glutScreen;
  167.     overlayVisuals = __glutXGetLayerVisualInfo(__glutDisplay,
  168.       VisualScreenMask | VisualLayerMask, &template, &nVisuals);
  169.     if (overlayVisuals) {
  170.       /* First, check if the default visual is in this layer.
  171.          If the default visual is in this layer, we try to use
  172.          it since it has pre-defined black and white pixels and 
  173.  
  174.          using the default visual will probably minimize
  175.          colormap flashing problems. Suggested by Thomas Roell
  176.          (thomas@xig.com). */
  177.       for (i = 0; i < nVisuals; i++) {
  178.         visual = &overlayVisuals[i];
  179.         if (visual->vinfo.colormap_size >= 3) {
  180.           /* Compare visual IDs just to be safe. */
  181.           if (visual->vinfo.visual->visualid == DefaultVisual(__glutDisplay, __glutScreen)->visualid) {
  182.             /* Settle for default visual. */
  183.             menuVisual = DefaultVisual(__glutDisplay, __glutScreen);
  184.             menuDepth = DefaultDepth(__glutDisplay, __glutScreen);
  185.             menuColormap = DefaultColormap(__glutDisplay, __glutScreen);
  186.             menuBlack = BlackPixel(__glutDisplay, __glutScreen);
  187.             menuWhite = WhitePixel(__glutDisplay, __glutScreen);
  188.             color.red = color.green = color.blue = 0xaa00;
  189.             noFaultXAllocColor(__glutDisplay, menuColormap,
  190.               menuVisual->map_entries, &color);
  191.             menuGray = color.pixel;
  192.             useSaveUnders = 0;
  193.             XFree(overlayVisuals);
  194.             return;
  195.           }
  196.         }
  197.       }
  198.       for (i = 0; i < nVisuals; i++) {
  199.         visual = &overlayVisuals[i];
  200.         if (visual->vinfo.colormap_size >= 3) {
  201.           if (allocateHigh) {
  202.             /* For Sun's Creator graphics, try to force the
  203.                read-only colors to the high end of the colormap
  204.                by first allocating read-write place-holder cells
  205.                for all but the last three cells.  This helps
  206.                avoid colormap flashing problems. */
  207.             numPlaceHolders = visual->vinfo.colormap_size - 3;
  208.             if (numPlaceHolders > 0) {
  209.               placeHolders = (unsigned long *)
  210.                 malloc(numPlaceHolders * sizeof(unsigned long));
  211.               /* A malloc failure would be harmless. */
  212.             }
  213.           }
  214.           menuColormap = XCreateColormap(__glutDisplay, __glutRoot,
  215.             visual->vinfo.visual, AllocNone);
  216.           if (placeHolders) {
  217.             /* Again for Sun's Creator graphics, do the actual
  218.                read-write place-holder cell allocation. */
  219.             status = XAllocColorCells(__glutDisplay, menuColormap, False, 0, 0,
  220.               placeHolders, numPlaceHolders);
  221.             if (!status) {
  222.               XFreeColormap(__glutDisplay, menuColormap);
  223.               free(placeHolders);
  224.               continue;
  225.             }
  226.           }
  227.           /* Allocate overlay colormap cells in defined order:
  228.              gray, black, white to match the IRIS GL allocation
  229.              scheme.  Increases likelihood of less overlay
  230.              colormap flashing. */
  231.           /* XXX Nice if these 3 AllocColor's could be done in
  232.              one protocol round-trip. */
  233.           color.red = color.green = color.blue = 0xaa00;
  234.           status = XAllocColor(__glutDisplay,
  235.             menuColormap, &color);
  236.           if (!status) {
  237.             XFreeColormap(__glutDisplay, menuColormap);
  238.             if (placeHolders)
  239.               free(placeHolders);
  240.             continue;
  241.           }
  242.           menuGray = color.pixel;
  243.           color.red = color.green = color.blue = 0x0000;
  244.           status = XAllocColor(__glutDisplay,
  245.             menuColormap, &color);
  246.           if (!status) {
  247.             XFreeColormap(__glutDisplay, menuColormap);
  248.             if (placeHolders)
  249.               free(placeHolders);
  250.             continue;
  251.           }
  252.           menuBlack = color.pixel;
  253.           color.red = color.green = color.blue = 0xffff;
  254.           status = XAllocColor(__glutDisplay,
  255.             menuColormap, &color);
  256.           if (!status) {
  257.             XFreeColormap(__glutDisplay, menuColormap);
  258.             if (placeHolders)
  259.               free(placeHolders);
  260.             continue;
  261.           }
  262.           if (placeHolders) {
  263.             /* Now free the placeholder cells. */
  264.             XFreeColors(__glutDisplay, menuColormap,
  265.               placeHolders, numPlaceHolders, 0);
  266.             free(placeHolders);
  267.           }
  268.           menuWhite = color.pixel;
  269.           menuVisual = visual->vinfo.visual;
  270.           menuDepth = visual->vinfo.depth;
  271.           /* If using overlays, do not request "save unders". */
  272.           useSaveUnders = 0;
  273.           XFree(overlayVisuals);
  274.           return;
  275.         }
  276.       }
  277.       XFree(overlayVisuals);
  278.     }
  279.   }
  280.   /* Settle for default visual. */
  281.   menuVisual = DefaultVisual(__glutDisplay, __glutScreen);
  282.   menuDepth = DefaultDepth(__glutDisplay, __glutScreen);
  283.   menuColormap = DefaultColormap(__glutDisplay, __glutScreen);
  284.   menuBlack = BlackPixel(__glutDisplay, __glutScreen);
  285.   menuWhite = WhitePixel(__glutDisplay, __glutScreen);
  286.   color.red = color.green = color.blue = 0xaa00;
  287.   noFaultXAllocColor(__glutDisplay, menuColormap,
  288.     menuVisual->map_entries, &color);
  289.   menuGray = color.pixel;
  290.  
  291.   /* When no overlays are supported, we would like to use X
  292.      "save unders" to avoid exposes to windows obscured by
  293.      pop-up menus.  However, OpenGL's direct rendering support
  294.      means OpenGL interacts poorly with X backing store and
  295.      save unders.  X servers do not (in implementation
  296.      practice) redirect OpenGL rendering destined to obscured
  297.      window regions into backing store.
  298.  
  299.      Implementation solutions exist for this problem, but they
  300.      are expensive and high-end OpenGL implementations
  301.      typically provide fast rendering and/or overlays to
  302.      obviate the problem associated of user interfaces (pop-up
  303.      menus) forcing redraws of complex normal plane scenes.
  304.      (See support for overlays pop-up menus above.)
  305.  
  306.      Mesa 3D, however, does not support direct rendering.
  307.      Overlays are often unavailable to Mesa, and Mesa is also
  308.      relatively slow.  For these reasons, Mesa-rendering GLUT
  309.      programs can and should use X save unders.
  310.  
  311.      Look for the GLX extension.  If _not_ supported, we are
  312.      presumably using Mesa so enable save unders. */
  313.  
  314.   presumablyMesa = !XQueryExtension(__glutDisplay, "GLX",
  315.     &dummy, &dummy, &dummy);
  316.  
  317.   if (presumablyMesa)
  318.     useSaveUnders = CWSaveUnder;
  319.   else
  320.     useSaveUnders = 0;
  321. }
  322.  
  323. static void
  324. menuSetup(void)
  325. {
  326.   if (menuFont) {
  327.     /* MenuFont overload to indicate menu initalization. */
  328.     return;
  329.   }
  330.   menuFont = XLoadQueryFont(__glutDisplay,
  331.     "-*-helvetica-bold-o-normal--14-*-*-*-p-*-iso8859-1");
  332.   if (!menuFont) {
  333.     /* Try back up font. */
  334.     menuFont = XLoadQueryFont(__glutDisplay, "fixed");
  335.   }
  336.   if (!menuFont) {
  337.     __glutFatalError("could not load font.");
  338.   }
  339.   menuVisualSetup();
  340.   fontHeight = menuFont->ascent + menuFont->descent;
  341.   menuCursor = XCreateFontCursor(__glutDisplay, XC_arrow);
  342. }
  343.  
  344. static void
  345. menuGraphicsContextSetup(Window win)
  346. {
  347.   XGCValues gcvals;
  348.  
  349.   if (blackGC != None)
  350.     return;
  351.   gcvals.font = menuFont->fid;
  352.   gcvals.foreground = menuBlack;
  353.   blackGC = XCreateGC(__glutDisplay, win,
  354.     GCFont | GCForeground, &gcvals);
  355.   gcvals.foreground = menuGray;
  356.   grayGC = XCreateGC(__glutDisplay, win, GCForeground, &gcvals);
  357.   gcvals.foreground = menuWhite;
  358.   whiteGC = XCreateGC(__glutDisplay, win, GCForeground, &gcvals);
  359. }
  360. #endif /* !WIN32 */
  361.  
  362. /* DEPRICATED, use glutMenuStatusFunc instead. */
  363. void APIENTRY 
  364. glutMenuStateFunc(GLUTmenuStateCB menuStateFunc)
  365. {
  366.   __glutMenuStatusFunc = (GLUTmenuStatusCB) menuStateFunc;
  367. }
  368.  
  369. void APIENTRY 
  370. glutMenuStatusFunc(GLUTmenuStatusCB menuStatusFunc)
  371. {
  372.   __glutMenuStatusFunc = menuStatusFunc;
  373. }
  374.  
  375. void
  376. __glutSetMenu(GLUTmenu * menu)
  377. {
  378.   __glutCurrentMenu = menu;
  379. }
  380.  
  381. static void
  382. unmapMenu(GLUTmenu * menu)
  383. {
  384.   if (menu->cascade) {
  385.     unmapMenu(menu->cascade);
  386.     menu->cascade = NULL;
  387.   }
  388.   menu->anchor = NULL;
  389.   menu->highlighted = NULL;
  390.   XUnmapWindow(__glutDisplay, menu->win);
  391. }
  392.  
  393. void
  394. __glutFinishMenu(Window win, int x, int y)
  395. {
  396.   Window dummy;
  397.   int rc;
  398.  
  399.   unmapMenu(__glutMappedMenu);
  400.   XUngrabPointer(__glutDisplay, CurrentTime);
  401.  
  402.   /* Popping up an overlay popup menu will install its own
  403.      colormap.  If the window associated with the menu has an
  404.      overlay, install that window's overlay colormap so the
  405.      overlay isn't left using the popup menu's colormap. */
  406.   if (__glutMenuWindow->overlay)
  407.     XInstallColormap(__glutDisplay,
  408.       __glutMenuWindow->overlay->colormap->cmap);
  409.  
  410.   /* This XFlush is needed to to make sure the pointer is
  411.      really ungrabbed when the application's menu callback is
  412.      called. Otherwise, a deadlock might happen because the
  413.      application may try to read from an terminal window, but
  414.      yet the ungrab hasn't really happened since it hasn't been
  415.      flushed out. */
  416.   XFlush(__glutDisplay);
  417.  
  418.   if (__glutMenuStatusFunc) {
  419.     if (win != __glutMenuWindow->win) {
  420.       /* The button release may have occurred in a window other
  421.          than the window requesting the pop-up menu (for
  422.          example, one of the submenu windows).  In this case, we
  423.          need to translate the coordinates into the coordinate
  424.          system of the window associated with the window. */
  425.       rc = XTranslateCoordinates(__glutDisplay, win, __glutMenuWindow->win,
  426.         x, y, &x, &y, &dummy);
  427.       assert(rc != False);  /* Will always be on same screen. */
  428.     }
  429.     __glutSetWindow(__glutMenuWindow);
  430.     __glutSetMenu(__glutMappedMenu);
  431.  
  432.     /* Setting __glutMappedMenu to NULL permits operations that
  433.        change menus or destroy the menu window again. */
  434.     __glutMappedMenu = NULL;
  435.  
  436.     __glutMenuStatusFunc(GLUT_MENU_NOT_IN_USE, x, y);
  437.   }
  438.   /* Setting __glutMappedMenu to NULL permits operations that
  439.      change menus or destroy the menu window again. */
  440.   __glutMappedMenu = NULL;
  441.  
  442.   /* If an item is selected and it is not a submenu trigger,
  443.      generate menu callback. */
  444.   if (__glutItemSelected && !__glutItemSelected->isTrigger) {
  445.     __glutSetWindow(__glutMenuWindow);
  446.     /* When menu callback is triggered, current menu should be
  447.        set to the callback menu. */
  448.     __glutSetMenu(__glutItemSelected->menu);
  449.     __glutItemSelected->menu->select(
  450.       __glutItemSelected->value);
  451.   }
  452.   __glutMenuWindow = NULL;
  453. }
  454.  
  455. #define MENU_BORDER 1
  456. #define MENU_GAP 2
  457. #define MENU_ARROW_GAP 6
  458. #define MENU_ARROW_WIDTH 8
  459.  
  460. static void
  461. mapMenu(GLUTmenu * menu, int x, int y)
  462. {
  463.   XWindowChanges changes;
  464.   unsigned int mask;
  465.   int subMenuExtension, num;
  466.  
  467.   /* If there are submenus, we need to provide extra space for
  468.      the submenu pull arrow.  */
  469.   if (menu->submenus > 0) {
  470.     subMenuExtension = MENU_ARROW_GAP + MENU_ARROW_WIDTH;
  471.   } else {
  472.     subMenuExtension = 0;
  473.   }
  474.  
  475.   changes.stack_mode = Above;
  476.   mask = CWStackMode | CWX | CWY;
  477.   /* If the menu isn't managed (ie, validated so all the
  478.      InputOnly subwindows are the right size), do so.  */
  479.   if (!menu->managed) {
  480.     GLUTmenuItem *item;
  481.  
  482.     item = menu->list;
  483.     num = menu->num;
  484.     while (item) {
  485.       XWindowChanges itemupdate;
  486.  
  487.       itemupdate.y = (num - 1) * fontHeight + MENU_GAP;
  488.       itemupdate.width = menu->pixwidth;
  489.       itemupdate.width += subMenuExtension;
  490.       XConfigureWindow(__glutDisplay, item->win,
  491.         CWWidth | CWY, &itemupdate);
  492.       item = item->next;
  493.       num--;
  494.     }
  495.     menu->pixheight = MENU_GAP +
  496.       fontHeight * menu->num + MENU_GAP;
  497.     changes.height = menu->pixheight;
  498.     changes.width = MENU_GAP +
  499.       menu->pixwidth + subMenuExtension + MENU_GAP;
  500.     mask |= CWWidth | CWHeight;
  501.     menu->managed = True;
  502.   }
  503.   /* Make sure menu appears fully on screen. */
  504.   if (y + menu->pixheight >= __glutScreenHeight) {
  505.     changes.y = __glutScreenHeight - menu->pixheight;
  506.   } else {
  507.     changes.y = y;
  508.   }
  509.   if (x + menu->pixwidth + subMenuExtension >=
  510.     __glutScreenWidth) {
  511.     changes.x = __glutScreenWidth -
  512.       menu->pixwidth + subMenuExtension;
  513.   } else {
  514.     changes.x = x;
  515.   }
  516.  
  517.   /* Rember where the menu is placed so submenus can be
  518.      properly placed relative to it. */
  519.   menu->x = changes.x;
  520.   menu->y = changes.y;
  521.  
  522.   XConfigureWindow(__glutDisplay, menu->win, mask, &changes);
  523.   XInstallColormap(__glutDisplay, menuColormap);
  524.   /* XXX The XRaiseWindow below should not be necessary because
  525.      the XConfigureWindow requests an Above stack mode (same as
  526.      XRaiseWindow), but some Sun users complained this was still
  527.      necessary.  Probably some window manager or X server bug on
  528.      these machines?? */
  529.   XRaiseWindow(__glutDisplay, menu->win);
  530.   XMapWindow(__glutDisplay, menu->win);
  531. }
  532.  
  533. void
  534. __glutStartMenu(GLUTmenu * menu, GLUTwindow * window,
  535.   int x, int y, int x_win, int y_win)
  536. {
  537.   int grab;
  538.  
  539.   assert(__glutMappedMenu == NULL);
  540.   grab = XGrabPointer(__glutDisplay, __glutRoot, True,
  541.     ButtonPressMask | ButtonReleaseMask,
  542.     GrabModeAsync, GrabModeAsync,
  543.     __glutRoot, menuCursor, CurrentTime);
  544.   if (grab != GrabSuccess) {
  545.     /* Somebody else has pointer grabbed, ignore menu
  546.        activation. */
  547.     return;
  548.   }
  549.   __glutMappedMenu = menu;
  550.   __glutMenuWindow = window;
  551.   __glutItemSelected = NULL;
  552.   if (__glutMenuStatusFunc) {
  553.     __glutSetMenu(menu);
  554.     __glutSetWindow(window);
  555.     __glutMenuStatusFunc(GLUT_MENU_IN_USE, x_win, y_win);
  556.   }
  557.   mapMenu(menu, x, y);
  558. }
  559.  
  560. static void
  561. paintSubMenuArrow(Window win, int x, int y)
  562. {
  563.   XPoint p[5];
  564.  
  565.   p[0].x = p[4].x = x;
  566.   p[0].y = p[4].y = y - menuFont->ascent + 1;
  567.   p[1].x = p[0].x + MENU_ARROW_WIDTH - 1;
  568.   p[1].y = p[0].y + (menuFont->ascent / 2) - 1;
  569.   p[2].x = p[1].x;
  570.   p[2].y = p[1].y + 1;
  571.   p[3].x = p[0].x;
  572.   p[3].y = p[0].y + menuFont->ascent - 2;
  573.   XFillPolygon(__glutDisplay, win,
  574.     whiteGC, p, 4, Convex, CoordModeOrigin);
  575.   XDrawLines(__glutDisplay, win, blackGC, p, 5, CoordModeOrigin);
  576. }
  577.  
  578. static void
  579. paintMenuItem(GLUTmenuItem * item, int num)
  580. {
  581.   Window win = item->menu->win;
  582.   GC gc;
  583.   int y;
  584.   int subMenuExtension;
  585.  
  586.   if (item->menu->submenus > 0) {
  587.     subMenuExtension = MENU_ARROW_GAP + MENU_ARROW_WIDTH;
  588.   } else {
  589.     subMenuExtension = 0;
  590.   }
  591.   if (item->menu->highlighted == item) {
  592.     gc = whiteGC;
  593.   } else {
  594.     gc = grayGC;
  595.   }
  596.   y = MENU_GAP + fontHeight * num - menuFont->descent;
  597.   XFillRectangle(__glutDisplay, win, gc,
  598.     MENU_GAP, y - fontHeight + menuFont->descent,
  599.     item->menu->pixwidth + subMenuExtension, fontHeight);
  600.   XDrawString(__glutDisplay, win, blackGC,
  601.     MENU_GAP, y, item->label, item->len);
  602.   if (item->isTrigger) {
  603.     paintSubMenuArrow(win,
  604.       item->menu->pixwidth + MENU_ARROW_GAP + 1, y);
  605.   }
  606. }
  607.  
  608. void
  609. __glutPaintMenu(GLUTmenu * menu)
  610. {
  611.   GLUTmenuItem *item;
  612.   int i = menu->num;
  613.   int y = MENU_GAP + fontHeight * i - menuFont->descent;
  614.  
  615.   item = menu->list;
  616.   while (item) {
  617.     if (item->menu->highlighted == item) {
  618.       paintMenuItem(item, i);
  619.     } else {
  620.       /* Quick render of the menu item; assume background
  621.          already cleared to gray. */
  622.       XDrawString(__glutDisplay, menu->win, blackGC,
  623.         2, y, item->label, item->len);
  624.       if (item->isTrigger) {
  625.         paintSubMenuArrow(menu->win,
  626.           menu->pixwidth + MENU_ARROW_GAP + 1, y);
  627.       }
  628.     }
  629.     i--;
  630.     y -= fontHeight;
  631.     item = item->next;
  632.   }
  633. }
  634.  
  635. GLUTmenuItem *
  636. __glutGetMenuItem(GLUTmenu * menu, Window win, int *which)
  637. {
  638.   GLUTmenuItem *item;
  639.   int i;
  640.  
  641.   i = menu->num;
  642.   item = menu->list;
  643.   while (item) {
  644.     if (item->win == win) {
  645.       *which = i;
  646.       return item;
  647.     }
  648.     if (item->isTrigger) {
  649.       GLUTmenuItem *subitem;
  650.  
  651.       subitem = __glutGetMenuItem(menuList[item->value],
  652.         win, which);
  653.       if (subitem) {
  654.         return subitem;
  655.       }
  656.     }
  657.     i--;
  658.     item = item->next;
  659.   }
  660.   return NULL;
  661. }
  662.  
  663. static int
  664. getMenuItemIndex(GLUTmenuItem * item)
  665. {
  666.   int count = 0;
  667.  
  668.   while (item) {
  669.     count++;
  670.     item = item->next;
  671.   }
  672.   return count;
  673. }
  674.  
  675. GLUTmenu *
  676. __glutGetMenu(Window win)
  677. {
  678.   GLUTmenu *menu;
  679.  
  680.   menu = __glutMappedMenu;
  681.   while (menu) {
  682.     if (win == menu->win) {
  683.       return menu;
  684.     }
  685.     menu = menu->cascade;
  686.   }
  687.   return NULL;
  688. }
  689.  
  690. GLUTmenu *
  691. __glutGetMenuByNum(int menunum)
  692. {
  693.   if (menunum < 1 || menunum > menuListSize) {
  694.     return NULL;
  695.   }
  696.   return menuList[menunum - 1];
  697. }
  698.  
  699. static int
  700. getUnusedMenuSlot(void)
  701. {
  702.   int i;
  703.  
  704.   /* Look for allocated, unused slot. */
  705.   for (i = 0; i < menuListSize; i++) {
  706.     if (!menuList[i]) {
  707.       return i;
  708.     }
  709.   }
  710.   /* Allocate a new slot. */
  711.   menuListSize++;
  712.   if (menuList) {
  713.     menuList = (GLUTmenu **)
  714.       realloc(menuList, menuListSize * sizeof(GLUTmenu *));
  715.   } else {
  716.     /* XXX Some realloc's do not correctly perform a malloc
  717.        when asked to perform a realloc on a NULL pointer,
  718.        though the ANSI C library spec requires this. */
  719.     menuList = (GLUTmenu **) malloc(sizeof(GLUTmenu *));
  720.   }
  721.   if (!menuList)
  722.     __glutFatalError("out of memory.");
  723.   menuList[menuListSize - 1] = NULL;
  724.   return menuListSize - 1;
  725. }
  726.  
  727. static void
  728. menuModificationError(void)
  729. {
  730.   /* XXX Remove the warning after GLUT 3.0. */
  731.   __glutWarning("The following is a new check for GLUT 3.0; update your code.");
  732.   __glutFatalError("menu manipulation not allowed while menus in use.");
  733. }
  734.  
  735. int APIENTRY 
  736. glutCreateMenu(GLUTselectCB selectFunc)
  737. {
  738.   XSetWindowAttributes wa;
  739.   GLUTmenu *menu;
  740.   int menuid;
  741.  
  742.   if (__glutMappedMenu)
  743.     menuModificationError();
  744.   if (!__glutDisplay)
  745.     __glutOpenXConnection(NULL);
  746.   menuid = getUnusedMenuSlot();
  747.   menu = (GLUTmenu *) malloc(sizeof(GLUTmenu));
  748.   if (!menu)
  749.     __glutFatalError("out of memory.");
  750.   menu->id = menuid;
  751.   menu->num = 0;
  752.   menu->submenus = 0;
  753.   menu->managed = False;
  754.   menu->pixwidth = 0;
  755.   menu->select = selectFunc;
  756.   menu->list = NULL;
  757.   menu->cascade = NULL;
  758.   menu->highlighted = NULL;
  759.   menu->anchor = NULL;
  760.   menuSetup();
  761.   wa.override_redirect = True;
  762.   wa.background_pixel = menuGray;
  763.   wa.border_pixel = menuBlack;
  764.   wa.colormap = menuColormap;
  765.   wa.event_mask = StructureNotifyMask | ExposureMask |
  766.     ButtonPressMask | ButtonReleaseMask |
  767.     EnterWindowMask | LeaveWindowMask;
  768.   /* Save unders really only enabled if useSaveUnders is set to
  769.      CWSaveUnder, ie. using Mesa 3D.  See earlier comments. */
  770.   wa.save_under = True;
  771.   menu->win = XCreateWindow(__glutDisplay, __glutRoot,
  772.   /* Real position determined when mapped. */
  773.     0, 0,
  774.   /* Real size will be determined when menu is manged. */
  775.     1, 1,
  776.     MENU_BORDER, menuDepth, InputOutput, menuVisual,
  777.     CWOverrideRedirect | CWBackPixel | CWBorderPixel |
  778.     CWEventMask | CWColormap | useSaveUnders,
  779.     &wa);
  780.   menuGraphicsContextSetup(menu->win);
  781.   menuList[menuid] = menu;
  782.   __glutSetMenu(menu);
  783.   return menuid + 1;
  784. }
  785.  
  786. /* CENTRY */
  787. void APIENTRY 
  788. glutDestroyMenu(int menunum)
  789. {
  790.   GLUTmenu *menu = __glutGetMenuByNum(menunum);
  791.   GLUTmenuItem *item, *next;
  792.  
  793.   if (__glutMappedMenu)
  794.     menuModificationError();
  795.   assert(menu->id == menunum - 1);
  796.   XDestroySubwindows(__glutDisplay, menu->win);
  797.   XDestroyWindow(__glutDisplay, menu->win);
  798.   menuList[menunum - 1] = NULL;
  799.   /* free all menu entries */
  800.   item = menu->list;
  801.   while (item) {
  802.     assert(item->menu == menu);
  803.     next = item->next;
  804.     free(item->label);
  805.     free(item);
  806.     item = next;
  807.   }
  808.   if (__glutCurrentMenu == menu) {
  809.     __glutCurrentMenu = NULL;
  810.   }
  811.   free(menu);
  812. }
  813.  
  814. int APIENTRY 
  815. glutGetMenu(void)
  816. {
  817.   if (__glutCurrentMenu) {
  818.     return __glutCurrentMenu->id + 1;
  819.   } else {
  820.     return 0;
  821.   }
  822. }
  823.  
  824. void APIENTRY 
  825. glutSetMenu(int menuid)
  826. {
  827.   GLUTmenu *menu;
  828.  
  829.   if (menuid < 1 || menuid > menuListSize) {
  830.     __glutWarning("glutSetMenu attempted on bogus menu.");
  831.     return;
  832.   }
  833.   menu = menuList[menuid - 1];
  834.   if (!menu) {
  835.     __glutWarning("glutSetMenu attempted on bogus menu.");
  836.     return;
  837.   }
  838.   __glutSetMenu(menu);
  839. }
  840. /* ENDCENTRY */
  841.  
  842. static void
  843. setMenuItem(GLUTmenuItem * item, const char *label,
  844.   int value, Bool isTrigger)
  845. {
  846.   GLUTmenu *menu;
  847.  
  848.   menu = item->menu;
  849.   item->label = __glutStrdup(label);
  850.   if (!item->label)
  851.     __glutFatalError("out of memory.");
  852.   item->isTrigger = isTrigger;
  853.   item->len = (int) strlen(label);
  854.   item->value = value;
  855.   item->pixwidth = XTextWidth(menuFont, label, item->len) + 4;
  856.   if (item->pixwidth > menu->pixwidth) {
  857.     menu->pixwidth = item->pixwidth;
  858.   }
  859.   menu->managed = False;
  860. }
  861.  
  862. /* CENTRY */
  863. void APIENTRY 
  864. glutAddMenuEntry(const char *label, int value)
  865. {
  866.   XSetWindowAttributes wa;
  867.   GLUTmenuItem *entry;
  868.  
  869.   if (__glutMappedMenu)
  870.     menuModificationError();
  871.   entry = (GLUTmenuItem *) malloc(sizeof(GLUTmenuItem));
  872.   if (!entry)
  873.     __glutFatalError("out of memory.");
  874.   entry->menu = __glutCurrentMenu;
  875.   setMenuItem(entry, label, value, False);
  876.   wa.event_mask = EnterWindowMask | LeaveWindowMask;
  877.   entry->win = XCreateWindow(__glutDisplay,
  878.     __glutCurrentMenu->win, MENU_GAP,
  879.     __glutCurrentMenu->num * fontHeight + MENU_GAP,  /* x & y */
  880.     entry->pixwidth, fontHeight,  /* width & height */
  881.     0, CopyFromParent, InputOnly, CopyFromParent,
  882.     CWEventMask, &wa);
  883.   XMapWindow(__glutDisplay, entry->win);
  884.   __glutCurrentMenu->num++;
  885.   entry->next = __glutCurrentMenu->list;
  886.   __glutCurrentMenu->list = entry;
  887. }
  888.  
  889. void APIENTRY 
  890. glutAddSubMenu(const char *label, int menu)
  891. {
  892.   XSetWindowAttributes wa;
  893.   GLUTmenuItem *submenu;
  894.  
  895.   if (__glutMappedMenu)
  896.     menuModificationError();
  897.   submenu = (GLUTmenuItem *) malloc(sizeof(GLUTmenuItem));
  898.   if (!submenu)
  899.     __glutFatalError("out of memory.");
  900.   __glutCurrentMenu->submenus++;
  901.   submenu->menu = __glutCurrentMenu;
  902.   setMenuItem(submenu, label, /* base 0 */ menu - 1, True);
  903.   wa.event_mask = EnterWindowMask | LeaveWindowMask;
  904.   submenu->win = XCreateWindow(__glutDisplay,
  905.     __glutCurrentMenu->win, MENU_GAP,
  906.     __glutCurrentMenu->num * fontHeight + MENU_GAP,  /* x & y */
  907.     submenu->pixwidth, fontHeight,  /* width & height */
  908.     0, CopyFromParent, InputOnly, CopyFromParent,
  909.     CWEventMask, &wa);
  910.   XMapWindow(__glutDisplay, submenu->win);
  911.   __glutCurrentMenu->num++;
  912.   submenu->next = __glutCurrentMenu->list;
  913.   __glutCurrentMenu->list = submenu;
  914. }
  915.  
  916. void APIENTRY 
  917. glutChangeToMenuEntry(int num, const char *label, int value)
  918. {
  919.   GLUTmenuItem *item;
  920.   int i;
  921.  
  922.   if (__glutMappedMenu)
  923.     menuModificationError();
  924.   i = __glutCurrentMenu->num;
  925.   item = __glutCurrentMenu->list;
  926.   while (item) {
  927.     if (i == num) {
  928.       if (item->isTrigger) {
  929.         /* If changing a submenu trigger to a menu entry, we
  930.            need to account for submenus.  */
  931.         item->menu->submenus--;
  932.       }
  933.       free(item->label);
  934.       setMenuItem(item, label, value, False);
  935.       return;
  936.     }
  937.     i--;
  938.     item = item->next;
  939.   }
  940.   __glutWarning("Current menu has no %d item.", num);
  941. }
  942.  
  943. void APIENTRY 
  944. glutChangeToSubMenu(int num, const char *label, int menu)
  945. {
  946.   GLUTmenuItem *item;
  947.   int i;
  948.  
  949.   if (__glutMappedMenu)
  950.     menuModificationError();
  951.   i = __glutCurrentMenu->num;
  952.   item = __glutCurrentMenu->list;
  953.   while (item) {
  954.     if (i == num) {
  955.       if (!item->isTrigger) {
  956.         /* If changing a menu entry to as submenu trigger, we
  957.            need to account for submenus.  */
  958.         item->menu->submenus++;
  959.       }
  960.       free(item->label);
  961.       setMenuItem(item, label, /* base 0 */ menu - 1, True);
  962.       return;
  963.     }
  964.     i--;
  965.     item = item->next;
  966.   }
  967.   __glutWarning("Current menu has no %d item.", num);
  968. }
  969.  
  970. void APIENTRY 
  971. glutRemoveMenuItem(int num)
  972. {
  973.   GLUTmenuItem *item, **prev, *remaining;
  974.   int pixwidth, i;
  975.  
  976.   if (__glutMappedMenu)
  977.     menuModificationError();
  978.   i = __glutCurrentMenu->num;
  979.   prev = &__glutCurrentMenu->list;
  980.   item = __glutCurrentMenu->list;
  981.   /* If menu item is removed, the menu's pixwidth may need to
  982.      be recomputed. */
  983.   pixwidth = 1;
  984.   while (item) {
  985.     if (i == num) {
  986.       /* If this menu item's pixwidth is as wide as the menu's
  987.          pixwidth, removing this menu item will necessitate
  988.          shrinking the menu's pixwidth. */
  989.       if (item->pixwidth >= __glutCurrentMenu->pixwidth) {
  990.         /* Continue recalculating menu pixwidth, first skipping
  991.            the removed item. */
  992.         remaining = item->next;
  993.         while (remaining) {
  994.           if (remaining->pixwidth > pixwidth) {
  995.             pixwidth = remaining->pixwidth;
  996.           }
  997.           remaining = remaining->next;
  998.         }
  999.         __glutCurrentMenu->pixwidth = pixwidth;
  1000.       }
  1001.       __glutCurrentMenu->num--;
  1002.       __glutCurrentMenu->managed = False;
  1003.  
  1004.       /* Patch up menu's item list. */
  1005.       *prev = item->next;
  1006.  
  1007.       free(item->label);
  1008.       free(item);
  1009.       return;
  1010.     }
  1011.     if (item->pixwidth > pixwidth) {
  1012.       pixwidth = item->pixwidth;
  1013.     }
  1014.     i--;
  1015.     prev = &item->next;
  1016.     item = item->next;
  1017.   }
  1018.   __glutWarning("Current menu has no %d item.", num);
  1019. }
  1020.  
  1021. void APIENTRY 
  1022. glutAttachMenu(int button)
  1023. {
  1024.   if (__glutMappedMenu)
  1025.     menuModificationError();
  1026.   if (__glutCurrentWindow->menu[button] < 1) {
  1027.     __glutCurrentWindow->buttonUses++;
  1028.   }
  1029.   __glutChangeWindowEventMask(
  1030.     ButtonPressMask | ButtonReleaseMask, True);
  1031.   __glutCurrentWindow->menu[button] = __glutCurrentMenu->id + 1;
  1032. }
  1033.  
  1034. void APIENTRY 
  1035. glutDetachMenu(int button)
  1036. {
  1037.   if (__glutMappedMenu)
  1038.     menuModificationError();
  1039.   if (__glutCurrentWindow->menu[button] > 0) {
  1040.     __glutCurrentWindow->buttonUses--;
  1041.     __glutChangeWindowEventMask(ButtonPressMask | ButtonReleaseMask,
  1042.       __glutCurrentWindow->buttonUses > 0);
  1043.     __glutCurrentWindow->menu[button] = 0;
  1044.   }
  1045. }
  1046. /* ENDCENTRY */
  1047.  
  1048. void
  1049. __glutMenuItemEnterOrLeave(GLUTmenuItem * item,
  1050.   int num, int type)
  1051. {
  1052.   int alreadyUp = 0;
  1053.  
  1054.   if (type == EnterNotify) {
  1055.     GLUTmenuItem *prevItem = item->menu->highlighted;
  1056.  
  1057.     if (prevItem && prevItem != item) {
  1058.       /* If there's an already higlighted item in this menu
  1059.          that is different from this one (we could be
  1060.          re-entering an item with an already cascaded
  1061.          submenu!), unhighlight the previous item. */
  1062.       item->menu->highlighted = NULL;
  1063.       paintMenuItem(prevItem, getMenuItemIndex(prevItem));
  1064.     }
  1065.     item->menu->highlighted = item;
  1066.     __glutItemSelected = item;
  1067.     if (item->menu->cascade) {
  1068.       if (!item->isTrigger) {
  1069.         /* Entered a menu item that is not a submenu trigger,
  1070.            so pop down the current submenu cascade of this
  1071.            menu.  */
  1072.         unmapMenu(item->menu->cascade);
  1073.         item->menu->cascade = NULL;
  1074.       } else {
  1075.         GLUTmenu *submenu = menuList[item->value];
  1076.  
  1077.         if (submenu->anchor == item) {
  1078.           /* We entered the submenu trigger for the submenu
  1079.              that is already up, so don't take down the
  1080.              submenu.  */
  1081.           alreadyUp = 1;
  1082.         } else {
  1083.           /* Submenu already popped up for some other submenu
  1084.              item of this menu; need to pop down that other
  1085.              submenu cascade.  */
  1086.           unmapMenu(item->menu->cascade);
  1087.           item->menu->cascade = NULL;
  1088.         }
  1089.       }
  1090.     }
  1091.     if (!alreadyUp) {
  1092.       /* Make sure the menu item gets painted with
  1093.          highlighting. */
  1094.       paintMenuItem(item, num);
  1095.     } else {
  1096.       /* If already up, should already be highlighted.  */
  1097.     }
  1098.   } else {
  1099.     /* LeaveNotify: Handle leaving a menu item...  */
  1100.     if (item->menu->cascade &&
  1101.       item->menu->cascade->anchor == item) {
  1102.       /* If there is a submenu casacaded from this item, do not
  1103.          change the highlighting on this item upon leaving. */
  1104.     } else {
  1105.       /* Unhighlight this menu item.  */
  1106.       item->menu->highlighted = NULL;
  1107.       paintMenuItem(item, num);
  1108.     }
  1109.     __glutItemSelected = NULL;
  1110.   }
  1111.   if (item->isTrigger) {
  1112.     if (type == EnterNotify && !alreadyUp) {
  1113.       GLUTmenu *submenu = menuList[item->value];
  1114.  
  1115.       mapMenu(submenu,
  1116.         item->menu->x + item->menu->pixwidth +
  1117.         MENU_ARROW_GAP + MENU_ARROW_WIDTH +
  1118.         MENU_GAP + MENU_BORDER,
  1119.         item->menu->y + fontHeight * (num - 1) + MENU_GAP);
  1120.       item->menu->cascade = submenu;
  1121.       submenu->anchor = item;
  1122.     }
  1123.   }
  1124. }
  1125.