summaryrefslogtreecommitdiffstats
path: root/test/stream_test.c
blob: 72f05c64e97888580d8b6e35ee2d121b748fd2e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright by the Board of Trustees of the University of Illinois.         *
 * All rights reserved.                                                      *
 *                                                                           *
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
 * terms governing use, modification, and redistribution, is contained in    *
 * the files COPYING and Copyright.html.  COPYING can be found at the root   *
 * of the source code distribution tree; Copyright.html can be found at the  *
 * root level of an installed copy of the electronic HDF5 document set and   *
 * is linked from the top-level documents page.  It can also be found at     *
 * http://hdf.ncsa.uiuc.edu/HDF5/doc/Copyright.html.  If you do not have     *
 * access to either file, you may request a copy from hdfhelp@ncsa.uiuc.edu. *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/*
 * Copyright © 2000 The author.
 * The author prefers this code not be used for military purposes.
 *
 *
 * Author:  Thomas Radke <tradke@aei-potsdam.mpg.de>
 *          Tuesday, September 12, 2000
 *
 * Modifications:
 *          Thomas Radke, Thursday, October 26, 2000
 *          Made it compiling under Windows.
 *
 */

/*
 *  This program tests the functionality of the Stream Virtual File Driver.
 *    1. It spawns two new processes, a sender and a receiver.
 *    2. The sender opens an HDF5 file for writing using the Stream driver.
 *       It will use a reserved port which should fail to be bound.
 *       Then it will try a couple of successive ports until bind succeeds.
 *       This final "hostname:port" information is written into a temporary
 *       file as a single line of text.
 *       The sender then writes a sample dataset to the HDF5 file.
 *       On closing the file the Stream VFD would send the file
 *       contents to any connected client.
 *    3. The receiver serves as a client attempting to open an
 *       HDF5 file for reading. On opening the file the Stream VFD
 *       would establish a socket connection to the sender process,
 *       identified by its hostname and a port number (which is obtained
 *       from the temporary text file the sender should have created),
 *       and read the file contents via this socket.
 *       Aftwerwards the dataset is read from the file into memory
 *       and verified.
 *    4. The main program waits for termination of its two child
 *       processes and returns their exit code.
 */

#include <stdio.h>
#include "hdf5.h"

#ifndef H5_HAVE_STREAM

int main (void)
{
  printf ("Test skipped because Stream Virtual File Driver not available\n");
  return (0);
}

#elif ! defined (H5_HAVE_FORK) || ! defined (H5_HAVE_WAITPID)

int main (void)
{
  printf ("Test skipped because this architecture doesn't provide "
          "fork(2) and waitpid(2)\n");
  return (0);
}

#else

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


#define SLEEPTIME     10                  /* sleeping time in seconds    */
#define RANK          2                   /* sample dataset rank         */
#define DIMS          50                  /* sample dataset dimensions   */
#define DATASETNAME   "IntArray"          /* sample dataset name         */
#define HOSTNAME      "localhost"         /* hostname of this machine    */
#define PORT          "5678"              /* default port to use         */
#define MAXHUNT       500                 /* max number of ports to hunt */
#define HDF5_FILENAME HOSTNAME ":" PORT   /* name of the streamed file   */
#define TEMPFILENAME  "stream_test.tmp"   /* temporary filename          */


static int sender (void)
{
  int     i;
  hsize_t dims[RANK];
  int     *data;
  herr_t  status;
  hid_t   fapl, file;
  hid_t   dataspace, dataset;
  H5FD_stream_fapl_t stream_fapl;
  FILE    *tempfile;


  /*
   * Create access property list and set it to use the Stream driver.
   */
  fapl = H5Pcreate (H5P_FILE_ACCESS);
  if (fapl < 0)
  {
    fprintf (stderr, "sender: couldn't create file access property list\n");
    return (-1);
  }

  /*
   * Setup file access property list and select Stream VFD.
   *
   *   - block increment for realloc() should be chosen by the driver
   *   - no external socket is provided (should be created internally)
   *   - do I/O on this processor on this socket
   *   - only one client is allowed to connect at a time
   *   - no READ broadcast function is provided (since we only send data)
   *   - if bind to default port (given in the filename argument) fails
   *     do port hunting on the following MAXHUNT ports
   */
  stream_fapl.increment = 0;
  stream_fapl.socket = H5FD_STREAM_INVALID_SOCKET;
  stream_fapl.do_socket_io = 1;
  stream_fapl.backlog = 1;
  stream_fapl.broadcast_fn  = NULL;
  stream_fapl.broadcast_arg = NULL;
  stream_fapl.maxhunt = MAXHUNT;

  status = H5Pset_fapl_stream (fapl, &stream_fapl);
  if (status < 0)
  {
    fprintf (stderr, "sender: couldn't set file access property list "
                     "for Stream VFD\n");
    H5Pclose (fapl);
    return (-2);
  }

  /*
   * Create the data space for fixed size dataset.
   */
  for (i = 0; i < RANK; i++)
  {
    dims[i] = DIMS;
  }
  dataspace = H5Screate_simple (RANK, dims, NULL);
  if (dataspace < 0)
  {
    fprintf (stderr, "sender: couldn't create dataspace\n");
    H5Pclose (fapl);
    return (-3);
  }

  /*
   * Data buffer initialization.
   */
  i = (int) H5Sget_simple_extent_npoints (dataspace);
  data = (int *) malloc (i * sizeof (int));
  if (data == NULL)
  {
    fprintf (stderr, "sender: cannot allocate buffer for dataset with "
                     "%d integers\n", i);
    H5Sclose (dataspace);
    H5Pclose (fapl);
    return (-4);
  }
  while (--i >= 0)
  {
    data[i] = i;
  }

  /*
   * Create a new file using H5F_ACC_TRUNC access,
   * default file creation properties, and STREAM file
   * access properties.
   */
  printf ("  sender: opening file on host '%s' port %s for writing...\n",
          HOSTNAME, PORT);
  file = H5Fcreate (HDF5_FILENAME, H5F_ACC_TRUNC, H5P_DEFAULT, fapl);
  if (file < 0)
  {
    fprintf (stderr, "sender: couldn't create file on '%s' using port %s and "
            "following %d\n", HOSTNAME, PORT, MAXHUNT);
    free (data);
    H5Sclose (dataspace);
    H5Pclose (fapl);
    return (-5);
  }

  /*
   * Get the file access property list to find out what port is actually used.
   */
  status = H5Pget_fapl_stream (fapl, &stream_fapl);
  if (status < 0)
  {
    fprintf (stderr, "sender: couldn't get file access property list "
                     "for Stream VFD\n");
    free (data);
    H5Sclose (dataspace);
    H5Pclose (fapl);
    return (-6);
  }
  printf ("  sender: using port %d...\n", (int) stream_fapl.port);

  /*
   * Write the "hostname:port" information to a temporary file
   * which can be read by the receiver process.
   */
  tempfile = fopen (TEMPFILENAME, "w");
  if (tempfile == NULL)
  {
    fprintf (stderr, "sender: couldn't open temporary file to write "
                     "\"hostname:port\" information\n");
    free (data);
    H5Sclose (dataspace);
    H5Pclose (fapl);
    return (-7);
  }
  fprintf (tempfile, "%s:%d", HOSTNAME, (int) stream_fapl.port);
  fclose (tempfile);

  /*
   * Create a new dataset within the file using defined dataspace and
   * default dataset creation properties.
   */
  dataset = H5Dcreate (file, DATASETNAME, H5T_NATIVE_INT, dataspace,
                       H5P_DEFAULT);
  if (dataset < 0)
  {
    fprintf (stderr, "sender: couldn't create dataset '%s'\n", DATASETNAME);
    free (data);
    H5Fclose (file);
    H5Sclose (dataspace);
    H5Pclose (fapl);
    return (-8);
  }

  /*
   * Write the data to the dataset using default transfer properties.
   */
  printf ("  sender: writing dataset '%s' of type INTEGER to file '%s:%d'...\n",
          DATASETNAME, HOSTNAME, (int) stream_fapl.port);
  status = H5Dwrite (dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT,
                     data);
  if (status < 0)
  {
    free (data);
    H5Fclose (file);
    H5Dclose (dataset);
    H5Sclose (dataspace);
    H5Pclose (fapl);
    fprintf (stderr, "sender: couldn't write dataset\n");
    return (-9);
  }

  /*
   * Now give the receiver some time to connect before closing the file
   * and releasing resources.
   */
  printf ("  sender: sleeping for %d seconds...\n", SLEEPTIME);
  sleep (SLEEPTIME);
  printf ("  sender: closing file '%s:%d'\n", HOSTNAME, (int) stream_fapl.port);
  H5Sclose (dataspace);
  H5Dclose (dataset);
  H5Fclose (file);
  H5Pclose (fapl);
  free (data);

  return (0);
}


static int receiver (void)
{
  int i;                      /* looper */
  hid_t fapl;                 /* file access property list */
  hid_t file;                 /* file handle */
  hid_t dataset;              /* dataset handle */
  hid_t datatype;             /* datatype handle */
  hid_t dataspace;            /* dataspace handle */
  hsize_t nelems;             /* total number of elements in the dataset */
  hsize_t *dims;              /* dataset dimensions */
  int rank;                   /* dataset rank */
  int *data;                  /* read buffer */
  int nerrors;                /* total number of errors during verify */
  int status;                 /* return code of HDF5 routines */
  char filename[50];          /* filename of the streamed HDF5 file */
  FILE    *tempfile;          /* descriptor for temporary file */


  /*
   * Create access property list and set it to use the Stream driver.
   */
  fapl = H5Pcreate (H5P_FILE_ACCESS);
  if (fapl < 0)
  {
    fprintf (stderr, "receiver: couldn't create file access property list\n");
    return (-1);
  }

  status = H5Pset_fapl_stream (fapl, NULL);
  if (status < 0)
  {
    fprintf (stderr, "receiver: couldn't set file access property list "
                     "for Stream VFD\n");
    H5Pclose (fapl);
    return (-2);
  }

  /*
   * Now give the sender some time to open the file and accepting connections.
   */
  printf ("  receiver: sleeping for %d seconds...\n", SLEEPTIME / 2);
  sleep (SLEEPTIME / 2);

  /*
   * Read the "hostname:port" information from the temporary file
   * the sender should have created.
   */
  tempfile = fopen (TEMPFILENAME, "r");
  if (tempfile == NULL)
  {
    fprintf (stderr, "receiver: couldn't open temporary file to read "
                     "\"hostname:port\" information\n");
    H5Pclose (fapl);
    return (-3);
  }
  fgets (filename, sizeof (filename) - 1, tempfile);
  fclose (tempfile);
  unlink (TEMPFILENAME);

  /*
   * Open the streamed HDF5 file for reading.
   */
  printf ("  receiver: opening file '%s' for reading...\n", filename);
  file = H5Fopen (filename, H5F_ACC_RDONLY, fapl);
  H5Pclose (fapl);
  if (file < 0)
  {
    fprintf (stderr, "receiver: couldn't open file from '%s'\n", filename);
    return (-4);
  }

  /*
   * Open the file and the dataset.
   */
  printf ("  receiver: reading dataset '%s'...\n", DATASETNAME);
  dataset = H5Dopen (file, DATASETNAME);
  if (dataset < 0)
  {
    fprintf (stderr, "receiver: couldn't open dataset '%s'\n", DATASETNAME);
    return (-5);
  }

  /*
   * Get dataset class, order, and size information
   */
  datatype = H5Dget_type (dataset);
  if (H5Tget_class (datatype) == H5T_INTEGER)
  {
    printf ("  receiver: dataset is of type INTEGER\n");
  }
  printf ("  receiver: datatype size is %d bytes\n",
          (int) H5Tget_size (datatype));
  printf ("  receiver: byte ordering is %s endian\n",
          H5Tget_order (datatype) == H5T_ORDER_LE ? "little" : "big");
  H5Tclose(datatype);

  /*
   * Get dataset dimensions
   */
  dataspace = H5Dget_space (dataset);
  rank      = H5Sget_simple_extent_ndims (dataspace);
  dims      = (hsize_t *) malloc (rank * sizeof (hsize_t));
  H5Sget_simple_extent_dims (dataspace, dims, NULL);
  H5Sclose (dataspace);

  printf ("  receiver: rank %d, dimensions %u", rank, (unsigned int) dims[0]);
  nelems = dims[0];
  for (i = 1; i < rank; i++)
  {
    printf (" x %u", (unsigned int) dims[i]);
    nelems *= dims[i];
  }
  printf ("\n  receiver: total number of elements: %d\n", (int) nelems);
  free (dims);

  /*
   * Read dataset from file into memory.
   */
  data = (int *) malloc ((size_t) nelems * sizeof (int));
  status = H5Dread (dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT,
                    data);
  H5Dclose (dataset);

  /*
   * Close the file.
   */
  printf ("  receiver: closing file '%s'...\n", filename);
  H5Fclose (file);

  /*
   * Verify the dataset contents
   */
  printf ("  receiver: verifying contents of dataset '%s'...\n", DATASETNAME);
  for (i = nerrors = 0; i < (int) nelems; i++)
  {
    if (data[i] != i)
    {
      fprintf (stderr, "receiver: data error at offset %d: "
                       "expected %d got %d\n", i, i, data[i]);
      nerrors++;
    }
  }
  printf ("  receiver: dataset verified, %d errors found\n", nerrors);

  free (data);

  return (-nerrors);
}


int main (void)
{
  int main_status, sender_status, receiver_status;
  pid_t sender_pid, receiver_pid;


  sender_pid = receiver_pid = 0;

  /* main's return code for success */
  main_status = 0;

  /* spawn off the sender and the receiver process */
  printf ("main: starting sender process...\n");
  sender_pid = fork ();
  if (sender_pid == 0)
  {
    return (sender ());
  }
  else if (sender_pid < 0)
  {
    perror ("Failed to spawn sender");
    main_status = -1;
  }
  else
  {
    printf ("main: starting receiver process...\n");
    receiver_pid = fork ();
    if (receiver_pid == 0)
    {
      return (receiver ());
    }
    else if (sender_pid < 0)
    {
      perror ("Failed to spawn receiver");
      main_status = -1;
    }
  }

  /* wait for the termination of sender and receiver and check their status */
  printf ("main: waiting for termination of sender and receiver process...\n");
  if (sender_pid > 0 &&
      waitpid (sender_pid, &sender_status, 0) != sender_pid)
  {
    perror ("Failed to wait for termination of sender");
    main_status = -1;
  }
  else
  {
    main_status |= sender_status;
  }
  if (receiver_pid > 0 &&
      waitpid (receiver_pid, &receiver_status, 0) != receiver_pid)
  {
    perror ("Failed to wait for termination of receiver");
    main_status = -1;
  }
  else
  {
    main_status |= receiver_status;
  }

  printf (main_status == 0 ?
          "Stream Virtual File Driver test passed.\n" :
          "*** Stream Virtual File Driver TEST FAILED ***\n");

  return (main_status);
}

#endif /* H5_HAVE_STREAM */
57' href='#n1557'>1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
/*
 * tkMacOSXMenu.c --
 *
 *	This module implements the Mac-platform specific features of menus.
 *
 * Copyright (c) 1996-1997 by Sun Microsystems, Inc.
 * Copyright 2001, Apple Computer, Inc.
 * Copyright (c) 2005-2007 Daniel A. Steffen <das@users.sourceforge.net>
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tkMacOSXMenu.c,v 1.43 2007/10/12 03:14:48 das Exp $
 */

#include "tkMacOSXPrivate.h"
#include "tkMenubutton.h"
#include "tkMenu.h"
#include "tkColor.h"
#include "tkFont.h"
#include "tkMacOSXDebug.h"

/*
#ifdef TK_MAC_DEBUG
#define TK_MAC_DEBUG_MENUS
#endif
*/

#define USE_TK_MDEF

typedef struct MacMenu {
    MenuRef menuHdl;		/* The Menu Manager data structure. */
#ifdef USE_TK_MDEF
    int useMDEF;		/* true if this menu uses the MDEF */
#endif
} MacMenu;

typedef struct MenuEntryUserData {
    Drawable mdefDrawable;
    TkMenuEntry *mePtr;
    Tk_Font tkfont;
    Tk_FontMetrics *fmPtr;
} MenuEntryUserData;

/*
 * Platform specific flags for menu entries
 *
 * ENTRY_COMMAND_ACCEL		Indicates the entry has the command key
 *				in its accelerator string.
 * ENTRY_OPTION_ACCEL		Indicates the entry has the option key
 *				in its accelerator string.
 * ENTRY_SHIFT_ACCEL		Indicates the entry has the shift key
 *				in its accelerator string.
 * ENTRY_CONTROL_ACCEL		Indicates the entry has the control key
 *				in its accelerator string.
 */

#define ENTRY_COMMAND_ACCEL	ENTRY_PLATFORM_FLAG1
#define ENTRY_OPTION_ACCEL	ENTRY_PLATFORM_FLAG2
#define ENTRY_SHIFT_ACCEL	ENTRY_PLATFORM_FLAG3
#define ENTRY_CONTROL_ACCEL	ENTRY_PLATFORM_FLAG4
#define ENTRY_ACCEL_MASK	(ENTRY_COMMAND_ACCEL | ENTRY_OPTION_ACCEL \
				| ENTRY_SHIFT_ACCEL | ENTRY_CONTROL_ACCEL)
#define MODIFIER_NUM 4

/*
 * This structure is used to keep track of subfields within Macintosh menu
 * items.
 */

typedef struct EntryGeometry {
    int accelTextStart;		/* Offset into the accel string where
				 * the text starts. Everything before
				 * this is modifier key descriptions.
				 */
    int modifierWidth;		/* Width of modifier symbols. */
    int accelTextWidth;		/* Width of the text after the modifier
				 * keys. */
    int nonAccelMargin;		/* The width of the margin for entries
				 * without accelerators. */
    int modifierNum;		/* Number of modifiers */
    Tcl_UniChar modifierUniChars[MODIFIER_NUM];
				/* Modifiers in unicode */
    char accelGlyph;		/* Accelerator glyph, if any */
} EntryGeometry;

/*
 * Structure to keep track of toplevel windows and their menubars.
 */

typedef struct TopLevelMenubarList {
    struct TopLevelMenubarList *nextPtr;
				/* The next window in the list. */
    Tk_Window tkwin;		/* The toplevel window. */
    TkMenu *menuPtr;		/* The menu associated with this
				 * toplevel. */
} TopLevelMenubarList;

/*
 * Platform-specific flags for menus.
 *
 * MENU_APPLE_MENU		0 indicates a custom Apple menu has
 *				not been installed; 1 a custom Apple
 *				menu has been installed.
 * MENU_HELP_MENU		0 indicates a custom Help menu has
 *				not been installed; 1 a custom Help
 *				menu has been installed.
 * MENU_RECONFIGURE_PENDING	1 indicates that an idle handler has
 *				been scheduled to reconfigure the
 *				Macintosh MenuHandle.
 */

#define MENU_APPLE_MENU			MENU_PLATFORM_FLAG1
#define MENU_HELP_MENU			MENU_PLATFORM_FLAG2
#define MENU_RECONFIGURE_PENDING	MENU_PLATFORM_FLAG3

#define CASCADE_CMD (0x1b)	/* The special command char for cascade
				 * menus. */
#define MENUBAR_REDRAW_PENDING 1

static int gNoTkMenus = 0;	/* This is used by Tk_MacOSXTurnOffMenus as the
				 * flag that Tk is not to draw any menus. */

static Tcl_HashTable commandTable;
				/* The list of menuInstancePtrs associated with
				 * menu ids */
static short currentAppleMenuID;
				/* The id of the current Apple menu. 0 for
				 * none. */
static short currentHelpMenuID; /* The id of the current Help menu. 0 for
				 * none. */
static Tcl_Interp *currentMenuBarInterp;
				/* The interpreter of the window that owns
				 * the current menubar. */
static char *currentMenuBarName;
				/* Malloced. Name of current menu in menu bar.
				 * NULL if no menu set. TO DO: make this a
				 * DString. */
static Tk_Window currentMenuBarOwner;
				/* Which window owns the current menu bar. */
static int inPostMenu;		/* We cannot be re-entrant like X
				 * windows. */
static short lastMenuID;	/* To pass to NewMenu; need to figure out
				 * a good way to do this. */
static short lastCascadeID;
				/* Cascades have to have ids that are
				 * less than 256. */
static int menuBarFlags;	/* Used for whether the menu bar needs
				 * redrawing or not. */

struct MenuCommandHandlerData { /* This is the ClientData we pass to */
    TkMenu *menuPtr;		/* Tcl_DoWhenIdle to move handling */
    int index;			/* menu commands to the event loop. */
};

static TopLevelMenubarList *windowListPtr;
				/* A list of windows that have menubars set. */

/*
 * Array of unicode, charcode and utf representations of the most common
 * special menu symbols.
 */
typedef struct MenuSymbol {
    const Tcl_UniChar unicode;
    const char charCode;
    /* char padding; */
    int utfLen, width;
    char utf[TCL_UTF_MAX + 1];
} MenuSymbol;

static MenuSymbol menuSymbols[] = {
    {kCommandUnicode,	kCommandCharCode},
    {kOptionUnicode,	kMenuOptionGlyph},
    {kControlUnicode,	kMenuControlGlyph},
    {kShiftUnicode,	kMenuShiftGlyph},
    {kCheckUnicode,	kCheckCharCode},
    {kDiamondUnicode,	kDiamondCharCode},
    {kBulletUnicode,	kBulletCharCode},
    {0x2026,		kNullCharCode},
    {0,			0},
};

enum MenuSymbolIdx {
    COMMAND_SYMBOL,
    OPTION_SYMBOL,
    CONTROL_SYMBOL,
    SHIFT_SYMBOL,
    CHECK_SYMBOL,
    DIAMDOND_SYMBOL,
    BULLET_SYMBOL,
    ELLIPSIS_SYMBOL,
};

MenuRef tkCurrentAppleMenu = NULL;

static SInt32 menuMarkColumnWidth = 0, menuMarkIndent = 0;
static SInt32 menuTextLeadingEdgeMargin = 0, menuTextTrailingEdgeMargin = 0;
static SInt16 menuItemExtraHeight = 0, menuItemExtraWidth = 0;
static SInt16 menuSeparatorHeight = 0;

/*
 * Forward declarations for procedures defined later in this file:
 */

MODULE_SCOPE int TkMacOSXGetNewMenuID(Tcl_Interp *interp, TkMenu *menuInstPtr,
	int cascade, short *menuIDPtr);
MODULE_SCOPE void TkMacOSXFreeMenuID(short menuID);

static void CompleteIdlers(TkMenu *menuPtr);
static void DrawMenuBarWhenIdle(ClientData clientData);
static void DrawMenuEntryAccelerator(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Drawable d, GC gc, Tk_Font tkfont, const Tk_FontMetrics *fmPtr,
	Tk_3DBorder activeBorder, int x, int y, int width, int height,
	int drawArrow);
static void DrawMenuEntryBackground(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Drawable d, Tk_3DBorder activeBorder, Tk_3DBorder bgBorder, int x,
	int y, int width, int heigth);
static void DrawMenuEntryIndicator(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Drawable d, GC gc, GC indicatorGC, Tk_Font tkfont,
	const Tk_FontMetrics *fmPtr, int x, int y, int width, int height);
static void DrawMenuEntryLabel(TkMenu * menuPtr, TkMenuEntry *mePtr,
	Drawable d, GC gc, Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int x,
	int y, int width, int height);
static void DrawMenuSeparator(TkMenu *menuPtr, TkMenuEntry *mePtr, Drawable d,
	GC gc, Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int x, int y,
	int width, int height);
static void DrawTearoffEntry(TkMenu *menuPtr, TkMenuEntry *mePtr, Drawable d,
	GC gc, Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int x, int y,
	int width, int height);
static void EventuallyInvokeMenu(ClientData data);
static void GetEntryText(TkMenuEntry *mePtr, Tcl_DString *dStringPtr);
static void GetMenuAccelGeometry(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int *modWidthPtr,
	int *textWidthPtr, int *heightPtr);
static void GetMenuLabelGeometry(TkMenuEntry *mePtr, Tk_Font tkfont,
	const Tk_FontMetrics *fmPtr, int *widthPtr, int *heightPtr);
static void GetMenuIndicatorGeometry(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int *widthPtr,
	int *heightPtr);
static void GetMenuSeparatorGeometry(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int *widthPtr,
	int *heightPtr);
static TkMenuEntry* GetParentMenuEntry(TkMenu *menuPtr);
static void GetTearoffEntryGeometry(TkMenu *menuPtr, TkMenuEntry *mePtr,
	Tk_Font tkfont, const Tk_FontMetrics *fmPtr, int *widthPtr,
	int *heightPtr);
static char FindMarkCharacter(TkMenuEntry *mePtr);
static int GetUtfMarkCharacter(char markChar, const char **markUtfPtr);
static TkMenu* MenuPtrForMenuRef(MenuRef menu);
static int ParseAccelerators(const char **accelStringPtr, int *modifierNumPtr,
	Tcl_UniChar *modifierUniChars, int *modifierWidth);
static void MenuSelectEvent(TkMenu *menuPtr);
static void ReconfigureIndividualMenu(TkMenu *menuPtr, MenuHandle macMenuHdl,
	int base);
static void ReconfigureMacintoshMenu(ClientData clientData);
static void RecursivelyClearActiveMenu(TkMenu *menuPtr);
static void RecursivelyDeleteMenu(TkMenu *menuPtr);
static void RecursivelyInsertMenu(TkMenu *menuPtr);
static void SetDefaultMenubar(void);
static int SetMenuCascade(TkMenu *menuPtr);

#ifdef USE_TK_MDEF
#define SCREEN_MARGIN 5
static MacDrawable macMDEFDrawable;
				/* Drawable for use by MDEF code */
static int MDEFScrollFlag = 0;	/* Used so that popups don't scroll too soon.*/
static MenuItemDrawingUPP tkThemeMenuItemDrawingUPP;
				/* Points to the UPP for theme Item drawing. */
static Tcl_Obj *useMDEFVar;

static void  DrawMenuBackground(TkMenu *menuPtr, Rect *menuRectPtr,
	Drawable d);
static void MenuDefProc(short message, MenuHandle menu, Rect *menuRectPtr,
	Point hitPt, short *whichItem );
static void HandleMenuHiliteMsg(MenuRef menu, Rect *menuRectPtr, Point hitPt,
	SInt16 *whichItem, TkMenu *menuPtr);
static void HandleMenuDrawMsg(MenuRef menu, Rect *menuRectPtr, Point hitPt,
	SInt16 *whichItem, TkMenu *menuPtr);
static void HandleMenuFindItemMsg(MenuRef menu, Rect *menuRectPtr,
	Point hitPt, SInt16 *whichItem, TkMenu *menuPtr);
static void HandleMenuPopUpMsg(MenuRef menu, Rect *menuRectPtr, Point hitPt,
	SInt16 *whichItem, TkMenu *menuPtr);
static void HandleMenuCalcItemMsg(MenuRef menu, Rect *menuRectPtr, Point hitPt,
	SInt16 *whichItem, TkMenu *menuPtr);
static void AppearanceEntryDrawWrapper(TkMenuEntry *mePtr, Rect * menuRectPtr,
	MenuTrackingData *mtdPtr, Drawable d, Tk_FontMetrics *fmPtr,
	Tk_Font tkfont, int erase);
static pascal void ThemeMenuItemDrawingProc(const Rect *inBounds,
	SInt16 inDepth, Boolean inIsColorDevice, SInt32 inUserData);
#else /* USE_TK_MDEF */
#   define useMDEF 0
#endif /* USE_TK_MDEF */

#define IS_THEME_MENU_FONT(tkfont) (strcmp(Tk_NameOfFont(tkfont), "menu") == 0)


/*
 *----------------------------------------------------------------------
 *
 * DrawThemeText --
 *
 *	Wrapper for DrawThemeTextBox API.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
DrawThemeText(
    Drawable d,
    GC gc,
    CFStringRef string,
    ThemeFontID font,
    ThemeDrawState drawState,
    const Rect* bounds,
    int baseline,
    int just)
{
    TkMacOSXDrawingContext dc;
    Rect adjustedBounds;

    /*
     * Menu item text drawn with the .Keyboard font (used for
     * kThemeMenuItemCmdKeyFont) won't always have the same ascent and
     * baseline as text drawn with the regular menu item font, since the
     * glyphs in the .Keyboard font may have a different height. Therefore, we
     * first determine the baseline of the text and then adjust the bounds
     * rect so the baseline aligns with the overall baseline of the menu item.
     */
    if (font == kThemeMenuItemCmdKeyFont) {
	Point size;
	SInt16 cmdKeyBaseline;

	GetThemeTextDimensions(string, font, drawState, false, &size,
		&cmdKeyBaseline);
	adjustedBounds = *bounds;
	OffsetRect(&adjustedBounds, 0, baseline - bounds->top - size.v -
		cmdKeyBaseline);
	bounds = &adjustedBounds;
    }
    if (TkMacOSXSetupDrawingContext(d, gc, 1, &dc)) {
	ChkErr(DrawThemeTextBox, string, font, drawState, false, bounds, just,
		dc.context);
	TkMacOSXRestoreDrawingContext(&dc);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MeasureThemeText --
 *
 *	Wrapper for GetThemeTextDimensions API.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
MeasureThemeText(
    CFStringRef string,
    ThemeFontID font)
{
    Point pt;

    ChkErr(GetThemeTextDimensions, string, font, kThemeStateActive, false, &pt,
	NULL);
    return pt.h;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXUseID --
 *
 *	Take the ID out of the available list for new menus. Used by the
 *	default menu bar's menus so that they do not get created at the tk
 *	level. See TkMacOSXGetNewMenuID for more information.
 *
 * Results:
 *	Returns TCL_OK if the id was not in use. Returns TCL_ERROR if the
 *	id was in use.
 *
 * Side effects:
 *	A hash table entry in the command table is created with a NULL
 *	value.
 *
 *----------------------------------------------------------------------
 */

int
TkMacOSXUseMenuID(
    short macID)		/* The id to take out of the table */
{
    Tcl_HashEntry *commandEntryPtr;
    int newEntry;
    int iMacID = macID; /* Do this to remove compiler warning */

    TkMenuInit();
    commandEntryPtr = Tcl_CreateHashEntry(&commandTable, (char *) iMacID,
	    &newEntry);
    if (!newEntry) {
	return TCL_ERROR;
    }
    Tcl_SetHashValue(commandEntryPtr, NULL);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetNewMenuID --
 *
 *	Allocates a new menu id and marks it in use. Each menu on the
 *	mac must be designated by a unique id, which is a short. In
 *	addition, some ids are reserved by the system. Since Tk uses
 *	mostly dynamic menus, we must allocate and free these ids on
 *	the fly. We use the id as a key into a hash table; if there
 *	is no hash entry, we know that we can use the id.
 *
 *	Carbon allows a much larger number of menus than the old APIs.
 *	I believe this is 32768, but am not sure. This code just uses
 *	2000 as the upper limit. Unfortunately tk leaks menus when
 *	cloning, under some circumstances (see bug on sourceforge).
 *
 * Results:
 *	Returns TCL_OK if succesful; TCL_ERROR if there are no more
 *	ids of the appropriate type to allocate. menuIDPtr contains
 *	the new id if succesful.
 *
 * Side effects:
 *	An entry is created for the menu in the command hash table,
 *	and the hash entry is stored in the appropriate field in the
 *	menu data structure.
 *
 *----------------------------------------------------------------------
 */

int
 TkMacOSXGetNewMenuID(
    Tcl_Interp *interp,		/* Used for error reporting */
    TkMenu *menuPtr,		/* The menu we are working with */
    int cascade,		/* 0 if we are working with a normal menu;
				 * 1 if we are working with a cascade */
    short *menuIDPtr)		/* The resulting id */
{
    int found = 0;
    int newEntry;
    Tcl_HashEntry *commandEntryPtr = NULL;
    short returnID = *menuIDPtr;

    /*
     * The following code relies on shorts and unsigned chars wrapping
     * when the highest value is incremented. Also, the values between
     * 236 and 255 inclusive are reserved for DA's by the Mac OS.
     */

    if (!cascade) {
	short curID = lastMenuID + 1;

	if (curID == 236) {
	    curID = 256;
	}

	while (curID != lastMenuID) {
	    int iCurID = curID;
	    commandEntryPtr = Tcl_CreateHashEntry(&commandTable,
		    (char *) iCurID, &newEntry);
	    if (newEntry == 1) {
		found = 1;
		lastMenuID = returnID = curID;
		break;
	    }
	    curID++;
	    if (curID == 236) {
		curID = 256;
	    }
	}
    } else {
	/*
	 * Cascade ids must be between 0 and 235 only, so they must be
	 * dealt with separately.
	 */

	short curID = lastCascadeID + 1;

	if (curID == 2000) {
	    curID = 0;
	}

	while (curID != lastCascadeID) {
	    int iCurID = curID;
	    commandEntryPtr = Tcl_CreateHashEntry(&commandTable,
		    (char *) iCurID, &newEntry);
	    if (newEntry == 1) {
		found = 1;
		lastCascadeID = returnID = curID;
		break;
	    }
	    curID++;
	    if (curID == 2000) {
		curID = 0;
	    }
	}
    }

    if (!found) {
	Tcl_ResetResult(interp);
	Tcl_AppendResult(interp, "No more menus can be allocated.", NULL);
	return TCL_ERROR;
    }
    Tcl_SetHashValue(commandEntryPtr, (char *) menuPtr);
    *menuIDPtr = returnID;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXFreeMenuID --
 *
 *	Marks the id as free.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The hash table entry for the ID is cleared.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXFreeMenuID(
    short menuID)		/* The id to free */
{
    Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(&commandTable,
	    (char*)(intptr_t)menuID);

    if (entryPtr != NULL) {
	 Tcl_DeleteHashEntry(entryPtr);
    }
    if (menuID == currentAppleMenuID) {
	currentAppleMenuID = 0;
    }
    if (menuID == currentHelpMenuID) {
	currentHelpMenuID = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MenuPtrForMenuRef --
 *
 *	Returns a pointer to the TkMenu corresponding to a given
 *	Carbon MenuRef.
 *
 * Results:
 *	Returns a pointer to a TkMenu or NULL.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

TkMenu*
MenuPtrForMenuRef(
    MenuRef menu)
{
    TkMenu *menuPtr = NULL;
    MenuID menuID = GetMenuID(menu);
    Tcl_HashEntry *commandEntryPtr = Tcl_FindHashEntry(&commandTable,
	    (char*)(intptr_t)menuID);

    if (commandEntryPtr) {
	menuPtr = (TkMenu *) Tcl_GetHashValue(commandEntryPtr);
    }
    return menuPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * GetParentMenuEntry --
 *
 *	Returns a pointer to the parent's TkMenuEntry of a given TkMenu.
 *
 * Results:
 *	Returns a pointer to a TkMenuEntry or NULL.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

TkMenuEntry*
GetParentMenuEntry(
    TkMenu *menuPtr)
{
    TkMenuEntry *cascadeEntryPtr;

    for (cascadeEntryPtr = menuPtr->menuRefPtr->parentEntryPtr;
	    cascadeEntryPtr != NULL;
	    cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) {
	const char *name = (cascadeEntryPtr->namePtr == NULL) ? ""
		: Tcl_GetString(cascadeEntryPtr->namePtr);

	if (strcmp(name, Tk_PathName(menuPtr->tkwin)) == 0) {
	    break;
	}
    }
    return cascadeEntryPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpNewMenu --
 *
 *	Gets a new blank menu. Only the platform specific options are filled
 *	in.
 *
 * Results:
 *	Returns a standard TCL error.
 *
 * Side effects:
 *	Allocates a Macintosh menu handle and puts in the platformData
 *	field of the menuPtr.
 *
 *----------------------------------------------------------------------
 */

int
TkpNewMenu(
    TkMenu *menuPtr)		/* The common structure we are making the
				 * platform structure for. */
{
    short menuID;
    MenuRef macMenuHdl;
#ifdef USE_TK_MDEF
    MenuDefSpec menuDefSpec;
    Tcl_Obj *useMDEFObjPtr;
    int useMDEF = 1;
#endif
    int error = TCL_OK;
    OSStatus err;
    CFStringRef cfStr;

    error = TkMacOSXGetNewMenuID(menuPtr->interp, menuPtr, 0, &menuID);
    if (error != TCL_OK) {
	return error;
    }
    err = ChkErr(CreateNewMenu, menuID, kMenuAttrDoNotUseUserCommandKeys,
	    &macMenuHdl);
    if (err != noErr) {
	Tcl_AppendResult(menuPtr->interp, "CreateNewMenu failed.", NULL);
	return TCL_ERROR;
    }
    cfStr = CFStringCreateWithCString(NULL, Tk_PathName(menuPtr->tkwin),
	    kCFStringEncodingUTF8);
    if (!cfStr) {
	Tcl_AppendResult(menuPtr->interp, "CFStringCreateWithCString failed.",
		NULL);
	return TCL_ERROR;
    }
    err = ChkErr(SetMenuTitleWithCFString, macMenuHdl, cfStr);
    CFRelease(cfStr);
    if (err != noErr) {
	Tcl_AppendResult(menuPtr->interp, "SetMenuTitleWithCFString failed.",
		NULL);
	return TCL_ERROR;
    }

    menuPtr->platformData = (TkMenuPlatformData) ckalloc(sizeof(MacMenu));
    ((MacMenu *) menuPtr->platformData)->menuHdl = macMenuHdl;

#ifdef USE_TK_MDEF
    /*
     * Check whether we want to use the custom mdef or not. For now
     * the default is to use it unless the variable is explicitly
     * set to no.
     */

    useMDEFObjPtr = Tcl_ObjGetVar2(menuPtr->interp, useMDEFVar, NULL,
	    TCL_GLOBAL_ONLY);
    if (useMDEFObjPtr == NULL || Tcl_GetBooleanFromObj(NULL, useMDEFObjPtr,
	    &useMDEF) == TCL_ERROR || useMDEF) {
	menuDefSpec.defType = kMenuDefProcPtr;
	menuDefSpec.u.defProc = MenuDefProc;
	ChkErr(SetMenuDefinition, macMenuHdl, &menuDefSpec);
    }
    ((MacMenu *) menuPtr->platformData)->useMDEF = useMDEF;
#endif /* USE_TK_MDEF */

    if ((currentMenuBarInterp == menuPtr->interp)
	    && (currentMenuBarName != NULL)) {
	Tk_Window parentWin = Tk_Parent(menuPtr->tkwin);

	if (strcmp(currentMenuBarName, Tk_PathName(parentWin)) == 0) {
	    if ((strcmp(Tk_PathName(menuPtr->tkwin)
		    + strlen(Tk_PathName(parentWin)), ".apple") == 0)
		    || (strcmp(Tk_PathName(menuPtr->tkwin)
		    + strlen(Tk_PathName(parentWin)), ".help") == 0)) {
		if (!(menuBarFlags & MENUBAR_REDRAW_PENDING)) {
		    Tcl_DoWhenIdle(DrawMenuBarWhenIdle, NULL);
		    menuBarFlags |= MENUBAR_REDRAW_PENDING;
		}
	    }
	}
    }

    menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
    Tcl_DoWhenIdle(ReconfigureMacintoshMenu, (ClientData) menuPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyMenu --
 *
 *	Destroys platform-specific menu structures.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	All platform-specific allocations are freed up.
 *
 *----------------------------------------------------------------------
 */

void
TkpDestroyMenu(
    TkMenu *menuPtr)		/* The common menu structure */
{
    MenuRef macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl;

    if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) {
	Tcl_CancelIdleCall(ReconfigureMacintoshMenu, (ClientData) menuPtr);
	menuPtr->menuFlags &= ~MENU_RECONFIGURE_PENDING;
    }
    if (GetMenuID(macMenuHdl) == currentHelpMenuID) {
	MenuRef helpMenuHdl;
	MenuItemIndex helpIndex;

	if ((HMGetHelpMenu(&helpMenuHdl,&helpIndex) == noErr)
		&& (helpMenuHdl != NULL)) {
	    int i, count = CountMenuItems(helpMenuHdl);

	    for (i = helpIndex; i <= count; i++) {
		DeleteMenuItem(helpMenuHdl, helpIndex);
	    }
	}
	currentHelpMenuID = 0;
    }
    if (menuPtr->platformData != NULL) {
	MenuID menuID = GetMenuID(macMenuHdl);

	DeleteMenu(menuID);
	TkMacOSXFreeMenuID(menuID);
	DisposeMenu(macMenuHdl);
	ckfree((char *) menuPtr->platformData);
	menuPtr->platformData = NULL;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SetMenuCascade --
 *
 *	Does any cleanup to change a menu from a normal to a cascade.
 *
 * Results:
 *	Standard Tcl error.
 *
 * Side effects:
 *	The mac menu id is reset.
 *
 *----------------------------------------------------------------------
 */

int
SetMenuCascade(
    TkMenu* menuPtr)		/* The menu we are setting up to be a
				 * cascade. */
{
    MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl;
    MenuID newMenuID, menuID = GetMenuID(macMenuHdl);
    int error = TCL_OK;

    if (menuID >= 256) {
	error = TkMacOSXGetNewMenuID(menuPtr->interp, menuPtr, 1, &newMenuID);
	if (error == TCL_OK) {
	    TkMacOSXFreeMenuID(menuID);
	    SetMenuID(macMenuHdl,newMenuID);
	}
    }
    return error;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyMenuEntry --
 *
 *	Cleans up platform-specific menu entry items.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	All platform-specific allocations are freed up.
 *
 *----------------------------------------------------------------------
 */

void
TkpDestroyMenuEntry(
    TkMenuEntry *mePtr)		/* The common structure for the menu entry. */
{
    TkMenu *menuPtr = mePtr->menuPtr;

    ckfree((char *) mePtr->platformEntryData);
    if ((menuPtr->platformData != NULL)
	    && !(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) {
	menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
	Tcl_DoWhenIdle(ReconfigureMacintoshMenu, (ClientData) menuPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetEntryText --
 *
 *	Given a menu entry, gives back the text that should go in it.
 *	Separators should be done by the caller, as they have to be
 *	handled specially. This is primarily used to do a substitution
 *	between "..." and the ellipsis character which looks nicer.
 *
 * Results:
 *	itemText points to the new text for the item.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
GetEntryText(
    TkMenuEntry *mePtr,		/* A pointer to the menu entry. */
    Tcl_DString *dStringPtr)	/* The DString to put the text into. This
				 * will be initialized by this routine. */
{
#ifdef USE_TK_MDEF
    const int useMDEF = ((MacMenu *) mePtr->menuPtr->platformData)->useMDEF;
#endif
    int noLabel = (mePtr->labelPtr == NULL || mePtr->labelLength == 0);

    Tcl_DStringInit(dStringPtr);
    if (mePtr->type == TEAROFF_ENTRY && (useMDEF || noLabel)) {
	Tcl_DStringAppend(dStringPtr, "(Tear-off)", -1);
    } else if (mePtr->imagePtr != NULL && (useMDEF || noLabel) &&
	    mePtr->compound == COMPOUND_NONE) {
	Tcl_DStringAppend(dStringPtr, "(Image)", -1);
    } else if (mePtr->bitmapPtr != NULL && (useMDEF || noLabel) &&
	    mePtr->compound == COMPOUND_NONE) {
	Tcl_DStringAppend(dStringPtr, "(Pixmap)", -1);
    } else if (noLabel) {
	/*
	 * The Mac menu manager does not like null strings.
	 */

	Tcl_DStringAppend(dStringPtr, " ", -1);
    } else {
	int length;
	char *text = Tcl_GetStringFromObj(mePtr->labelPtr, &length);
	char *dStringText;
	int i;

	for (i = 0; *text; text++, i++) {
	    if ((*text == '.') && (*(text+1) == '.') && (*(text+2) == '.')) {
		Tcl_DStringAppend(dStringPtr, menuSymbols[ELLIPSIS_SYMBOL].utf,
			menuSymbols[ELLIPSIS_SYMBOL].utfLen);
		i += menuSymbols[ELLIPSIS_SYMBOL].utfLen - 1;
		text += 2;
	    } else {
		Tcl_DStringSetLength(dStringPtr,
			Tcl_DStringLength(dStringPtr) + 1);
		dStringText = Tcl_DStringValue(dStringPtr);
		dStringText[i] = *text;
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FindMarkCharacter --
 *
 *	Finds the Macintosh mark character based on the font of the
 *	item. We calculate a good mark character based on the font
 *	that this item is rendered in.
 *
 * Results:
 *	Mark char.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

char
FindMarkCharacter(
    TkMenuEntry *mePtr)		/* The entry we are finding the character
				 * for. */
{
    static const char markChars[] = {kCheckCharCode, kDiamondCharCode,
	    kBulletCharCode, '-', kCheckCharCode};
    const char *markChar = markChars;
    int i = sizeof(markChars);
    Tk_Font tkfont;

    tkfont = Tk_GetFontFromObj(mePtr->menuPtr->tkwin,
	    (mePtr->fontPtr == NULL) ? mePtr->menuPtr->fontPtr
	    : mePtr->fontPtr);

    while (--i) {
	if (!TkMacOSXIsCharacterMissing(tkfont, *markChar)) {
	    break;
	}
	markChar++;
    }
    return *markChar;
}

/*
 *----------------------------------------------------------------------
 *
 * GetUtfMarkCharacter --
 *
 *	Get the utf8 string for the given mark character, taking into
 *	account the special menu font char codes.
 *
 * Results:
 *	Length of returned utf8 string.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
GetUtfMarkCharacter(
    char markChar,
    const char **markUtfPtr)
{
    const MenuSymbol *ms = menuSymbols;
    int len = 0;

    while (ms->unicode) {
	if (ms->charCode && ms->charCode == markChar) {
	    *markUtfPtr = ms->utf;
	    len = ms->utfLen;
	    break;
	}
	ms++;
    }
    if (!len) {
	static char markUtf[TCL_UTF_MAX + 1];

	Tcl_ExternalToUtf(NULL, TkMacOSXCarbonEncoding, &markChar, 1, 0, NULL,
		markUtf, TCL_UTF_MAX + 1, NULL, &len, NULL);
	*markUtfPtr = markUtf;
    }
    return len;
}

/*
 *----------------------------------------------------------------------
 *
 * ParseAccelerators --
 *
 *	Parse menu accelerator string.
 *
 * Results:
 *	Accelerator flags.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
ParseAccelerators(
    const char **accelStringPtr,
    int *modifierNumPtr,
    Tcl_UniChar *modifierUniChars,
    int *modifierWidth)
{
    struct Modif {
	const char *name;
	const size_t len;
	const int flag, symbol;
    };
#define MODIF(n, f) { #n, sizeof(#n)-1, ENTRY_##f##_ACCEL, f##_SYMBOL }
    static const struct Modif modifs[] = {
	MODIF(Control,	CONTROL),
	MODIF(Ctrl,	CONTROL),
	MODIF(Option,	OPTION),
	MODIF(Opt,	OPTION),
	MODIF(Alt,	OPTION),
	MODIF(Shift,	SHIFT),
	MODIF(Command,	COMMAND),
	MODIF(Cmd,	COMMAND),
	MODIF(Meta,	COMMAND),
	{ NULL, 0, 0, 0}
    };
#undef MODIF
    const char *accelString = *accelStringPtr;
    int flags = 0, num = 0, seen = 0, width = 0;
    const struct Modif *m;

    while (1) {
	m = modifs;
	while (m->name) {
	    int l = m->len;

	    if (!strncasecmp(accelString, m->name, l) &&
		    (accelString[l] == '-' || accelString[l] == '+')) {
		flags |= m->flag;
		accelString += l+1;
		break;
	    }
	    m++;
	}
	if (!m->name || !*accelString) {
	    break;
	}
    }
    m = modifs;
    while (m->name && num < MODIFIER_NUM) {
	if (flags & m->flag && !(seen & m->flag)) {
	    modifierUniChars[num++] = menuSymbols[m->symbol].unicode;
	    width += menuSymbols[m->symbol].width;
	    seen |= m->flag;
	}
	m++;
    }
    *accelStringPtr = accelString;
    *modifierNumPtr = num;
    *modifierWidth = width;
    return flags;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpConfigureMenuEntry --
 *
 *	Processes configurations for menu entries.
 *
 * Results:
 *	Returns standard TCL result. If TCL_ERROR is returned, then
 *	the interp's result contains an error message.
 *
 * Side effects:
 *	Configuration information get set for mePtr; old resources
 *	get freed, if any need it.
 *
 *----------------------------------------------------------------------
 */

int
TkpConfigureMenuEntry(
    TkMenuEntry *mePtr) 	/* Information about menu entry; may
				 * or may not already have values for
				 * some fields. */
{
    TkMenu *menuPtr = mePtr->menuPtr;
    EntryGeometry *geometryPtr = (EntryGeometry *) mePtr->platformEntryData;

    /*
     * Cascade menus have to have menu IDs of less than 256. So
     * we need to change the child menu if this has been configured
     * for a cascade item.
     */

    if (mePtr->type == CASCADE_ENTRY) {
	if ((mePtr->childMenuRefPtr != NULL)
		&& (mePtr->childMenuRefPtr->menuPtr != NULL)) {
	    MenuHandle childMenuHdl = ((MacMenu *) mePtr
		    ->childMenuRefPtr->menuPtr->platformData)->menuHdl;

	    if (childMenuHdl != NULL) {
		int error = SetMenuCascade(mePtr->childMenuRefPtr->menuPtr);

		if (error != TCL_OK) {
		    return error;
		}

		if (menuPtr->menuType == MENUBAR) {
		    CFStringRef cfStr = CFStringCreateWithCString(NULL,
			    (!(mePtr->labelPtr) ? "" :
			    Tcl_GetString(mePtr->labelPtr)),
			    kCFStringEncodingUTF8);

		    if (cfStr) {
			SetMenuTitleWithCFString(childMenuHdl, cfStr);
			CFRelease(cfStr);
		    }
		}
	    }
	}
    }

    /*
     * We need to parse the accelerator string. If it has the strings
     * for Command, Control, Shift or Option, we need to flag it
     * so we can draw the symbols for it. We also need to precalcuate
     * the position of the first real character we are drawing.
     */

    if (0 == mePtr->accelLength) {
	geometryPtr->accelTextStart = -1;
    } else {
	const char *accelString = (mePtr->accelPtr == NULL) ? ""
		: Tcl_GetString(mePtr->accelPtr);
	const char *accelStart = accelString;

	mePtr->entryFlags &= ~ENTRY_ACCEL_MASK;
	mePtr->entryFlags |= ParseAccelerators(&accelString,
		&geometryPtr->modifierNum, geometryPtr->modifierUniChars,
		&geometryPtr->modifierWidth);
	geometryPtr->accelTextStart = (ptrdiff_t)(accelString - accelStart);
    }

    if (!(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) {
	menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
	Tcl_DoWhenIdle(ReconfigureMacintoshMenu, (ClientData) menuPtr);
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReconfigureIndividualMenu --
 *
 *	This routine redoes the guts of the menu. It works from
 *	a base item and offset, so that a regular menu will
 *	just have all of its items added, but the help menu will
 *	have all of its items appended after the apple-defined
 *	items.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The Macintosh menu handle is updated
 *
 *----------------------------------------------------------------------
 */

void
ReconfigureIndividualMenu(
    TkMenu *menuPtr,		/* The menu we are affecting. */
    MenuHandle macMenuHdl,	/* The macintosh menu we are affecting.
				 * Will not necessarily be
				 * menuPtr->platformData because this could
				 * be the help menu. */
    int base)			/* The last index that we do not want
				 * touched. 0 for normal menus;
				 * # of system help menu items
				 * for help menus. */
{
    int count;
    int index;
    TkMenuEntry *mePtr;
    int parentDisabled = 0;

#ifdef TK_MAC_DEBUG_MENUS
    /*
     * Carbon-internal menu debugging (c.f. Technote 2124)
     */

    TkMacOSXInitNamedDebugSymbol(HIToolbox, void, DebugPrintMenu,
	MenuRef menu);
    if (DebugPrintMenu) {
	DebugPrintMenu(macMenuHdl);
    }
#endif

    mePtr = GetParentMenuEntry(menuPtr);
    if (mePtr && mePtr->state == ENTRY_DISABLED) {
	parentDisabled = 1;
    }

    /*
     * First, we get rid of all of the old items.
     */

    count = CountMenuItems(macMenuHdl);
    for (index = base; index < count; index++) {
	DeleteMenuItem(macMenuHdl, base + 1);
    }

    count = menuPtr->numEntries;

    for (index = 1; index <= count; index++) {
	mePtr = menuPtr->entries[index - 1];

	/*
	 * We have to do separators separately because SetMenuItemText
	 * does not parse meta-characters.
	 */

	if (mePtr->type == SEPARATOR_ENTRY) {
	    AppendMenuItemTextWithCFString(macMenuHdl, NULL,
		    kMenuItemAttrSeparator | kMenuItemAttrDisabled, 0, NULL);
	} else {
	    Tcl_DString itemTextDString;
	    CFStringRef cfStr;

	    GetEntryText(mePtr, &itemTextDString);
	    cfStr = CFStringCreateWithCString(NULL,
		    Tcl_DStringValue(&itemTextDString), kCFStringEncodingUTF8);
	    if (cfStr) {
		AppendMenuItemTextWithCFString(macMenuHdl, cfStr, 0, 0, NULL);
		CFRelease(cfStr);
	    } else {
		AppendMenuItemTextWithCFString(macMenuHdl, CFSTR ("<Error>"),
		    0, 0, NULL);
	    }
	    Tcl_DStringFree(&itemTextDString);

	    /*
	     * Set enabling and disabling correctly.
	     */

	    if (parentDisabled || (mePtr->state == ENTRY_DISABLED)) {
		DisableMenuItem(macMenuHdl, base + index);
	    } else {
		EnableMenuItem(macMenuHdl, base + index);
	    }

	    /*
	     * Set the check mark for check entries and radio entries.
	     */

	    SetItemMark(macMenuHdl, base + index, 0);
	    if ((mePtr->type == CHECK_BUTTON_ENTRY)
		    || (mePtr->type == RADIO_BUTTON_ENTRY)) {
		CheckMenuItem(macMenuHdl, base + index, (mePtr->entryFlags
		& ENTRY_SELECTED) && mePtr->indicatorOn);
		if (mePtr->indicatorOn
			&& (mePtr->entryFlags & ENTRY_SELECTED)) {
		    SetItemMark(macMenuHdl, base + index,
			    FindMarkCharacter(mePtr));
		}
	    }

	    if (mePtr->type == CASCADE_ENTRY) {
		if ((mePtr->childMenuRefPtr != NULL)
			&& (mePtr->childMenuRefPtr->menuPtr != NULL)) {
		    MenuHandle childMenuHdl =
			    ((MacMenu *) mePtr->childMenuRefPtr
			    ->menuPtr->platformData)->menuHdl;

		    if (childMenuHdl != NULL) {
			ChkErr(SetMenuItemHierarchicalID, macMenuHdl,
				base + index, GetMenuID(childMenuHdl));
		    }
		    /*
		     * If we changed the highligthing of this menu, its
		     * children all have to be reconfigured so that
		     * their state will be reflected in the menubar.
		     */

		    if (!(mePtr->childMenuRefPtr->menuPtr->menuFlags
				& MENU_RECONFIGURE_PENDING)) {
			mePtr->childMenuRefPtr->menuPtr->menuFlags
				|= MENU_RECONFIGURE_PENDING;
			Tcl_DoWhenIdle(ReconfigureMacintoshMenu,
				(ClientData) mePtr->childMenuRefPtr->menuPtr);
		    }
		}
	    }

	    if ((mePtr->type != CASCADE_ENTRY) && (mePtr->accelPtr != NULL)) {
		int accelLen, modifiers = 0, hasCmd = 0;
		EntryGeometry *geometryPtr =
			(EntryGeometry*)mePtr->platformEntryData;
		int offset = geometryPtr->accelTextStart;
		char *accel = Tcl_GetStringFromObj(mePtr->accelPtr, &accelLen);

		accelLen -= offset;
		accel += offset;
		if (mePtr->entryFlags & ENTRY_OPTION_ACCEL) {
		    modifiers |= kMenuOptionModifier;
		}
		if (mePtr->entryFlags & ENTRY_SHIFT_ACCEL) {
		    modifiers |= kMenuShiftModifier;
		}
		if (mePtr->entryFlags & ENTRY_CONTROL_ACCEL) {
		    modifiers |= kMenuControlModifier;
		}
		if (mePtr->entryFlags & ENTRY_COMMAND_ACCEL) {
		    hasCmd = 1;
		}
		if (accelLen == 1) {
		    if (hasCmd || (modifiers != 0 && modifiers !=
			    kMenuShiftModifier)) {
			SetItemCmd(macMenuHdl, base + index, accel[0]);
			if (!hasCmd) {
			    modifiers |= kMenuNoCommandModifier;
			}
		    }
		} else {
		    /*
		     * Convert from accelerator names to Carbon menu glyphs.
		     */
		    struct Glyph {
			const char *name;
			const size_t len;
			const char glyph;
		    };
#define GLYPH(n, g) { #n, sizeof(#n)-1, kMenu##g##Glyph }
		    static const struct Glyph glyphs[] = {
			GLYPH(PageUp,	PageUp),
			GLYPH(PageDown, PageDown),
			GLYPH(Left,	LeftArrow),
			GLYPH(Right,	RightArrow),
			GLYPH(Up,	UpArrow),
			GLYPH(Down,	DownArrow),
			GLYPH(Escape,	Escape),
			GLYPH(Clear,	Clear),
			GLYPH(Enter,	Enter),
			GLYPH(Backspace,DeleteLeft),
			GLYPH(Space,	Space),
			GLYPH(Tab,	TabRight),
			GLYPH(Delete,	DeleteRight),
			GLYPH(Home,	NorthwestArrow),
			GLYPH(End,	SoutheastArrow),
			GLYPH(Return,	Return),
			GLYPH(Help,	Help),
			GLYPH(Power,	Power),
			{ NULL, 0, 0}
		    };
#undef GLYPH
		    const struct Glyph *g = glyphs;
		    char glyph = 0;

		    if (accel[0] == 'F' && accelLen < 4 &&
			    (accel[1] > '0' && accel[1] <= '9')) {
			int fkey = accel[1] - '0';

			if (accelLen == 3) {
			    if (accel[2] >= '0' && accel[2] <= '9') {
				fkey = 10 * fkey + (accel[2] - '0');
			    } else {
				fkey = 0;
			    }
			}
			if (fkey >= 1 && fkey <= 12) {
			    glyph = kMenuF1Glyph + fkey - 1;
			} else if (fkey >= 13 && fkey <= 15) {
			    glyph = kMenuF13Glyph + fkey - 13;
			}
		    } else while (g->name) {
			if (accel[0] == g->name[0] &&
				(size_t)accelLen == g->len &&
				!strncasecmp(accel, g->name, g->len)) {
			    glyph = g->glyph;
			    break;
			}
			g++;
		    }
		    if (glyph) {
			ChkErr(SetMenuItemKeyGlyph, macMenuHdl, base + index,
				glyph);
			if (!hasCmd) {
			    modifiers |= kMenuNoCommandModifier;
			}
			geometryPtr->accelGlyph = glyph;
		    }
		}
		ChkErr(SetMenuItemModifiers, macMenuHdl, base + index,
			modifiers);
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ReconfigureMacintoshMenu --
 *
 *	Rebuilds the Macintosh MenuHandle items from the menu. Called
 *	usually as an idle handler, but can be called synchronously
 *	if the menu is about to be posted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Configuration information get set for mePtr; old resources
 *	get freed, if any need it.
 *
 *----------------------------------------------------------------------
 */

void
ReconfigureMacintoshMenu(
    ClientData clientData)	/* Information about menu entry; may
				 * or may not already have values for
				 * some fields. */
{
    TkMenu *menuPtr = (TkMenu *) clientData;
    MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl;
    MenuHandle helpMenuHdl = NULL;

    menuPtr->menuFlags &= ~MENU_RECONFIGURE_PENDING;

    if (NULL == macMenuHdl) {
	return;
    }

    ReconfigureIndividualMenu(menuPtr, macMenuHdl, 0);

    if (GetMenuID(macMenuHdl) == currentHelpMenuID) {
	MenuItemIndex helpIndex;
	HMGetHelpMenu(&helpMenuHdl,&helpIndex);
	if (helpMenuHdl != NULL) {
	    ReconfigureIndividualMenu(menuPtr, helpMenuHdl, helpIndex - 1);
	}
    }

    if (menuPtr->menuType == MENUBAR) {
	if (!(menuBarFlags & MENUBAR_REDRAW_PENDING)) {
	    Tcl_DoWhenIdle(DrawMenuBarWhenIdle, NULL);
	    menuBarFlags |= MENUBAR_REDRAW_PENDING;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * CompleteIdlers --
 *
 *	Completes all idle handling so that the menus are in sync when
 *	the user invokes them with the mouse.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The Macintosh menu handles are flushed out.
 *
 *----------------------------------------------------------------------
 */

void
CompleteIdlers(
    TkMenu *menuPtr)		/* The menu we are completing. */
{
    int i;

    if (menuPtr->menuFlags & MENU_RECONFIGURE_PENDING) {
	Tcl_CancelIdleCall(ReconfigureMacintoshMenu, (ClientData) menuPtr);
	ReconfigureMacintoshMenu((ClientData) menuPtr);
    }

    for (i = 0; i < menuPtr->numEntries; i++) {
	if ((menuPtr->entries[i]->type == CASCADE_ENTRY) &&
		(menuPtr->entries[i]->childMenuRefPtr != NULL) &&
		(menuPtr->entries[i]->childMenuRefPtr->menuPtr != NULL)) {
	    CompleteIdlers(menuPtr->entries[i]->childMenuRefPtr->menuPtr);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpPostMenu --
 *
 *	Posts a menu on the screen
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menu is posted and handled.
 *
 *----------------------------------------------------------------------
 */

int
TkpPostMenu(
    Tcl_Interp *interp,		/* The interpreter this menu lives in */
    TkMenu *menuPtr,		/* The menu we are posting */
    int x,			/* The global x-coordinate of the top, left-
				 * hand corner of where the menu is supposed
				 * to be posted. */
    int y)			/* The global y-coordinate */
{
    MenuHandle macMenuHdl = ((MacMenu *) menuPtr->platformData)->menuHdl;
    long popUpResult;
    int result;

    if (inPostMenu > 0) {
	Tcl_AppendResult(interp,
		"Cannot call post menu while already posting menu", NULL);
	result = TCL_ERROR;
    } else {
	short menuID;
	Window window;
	int oldWidth = menuPtr->totalWidth;

	inPostMenu++;
	result = TkPreprocessMenu(menuPtr);
	/*
	 * The post commands could have deleted the menu, which means
	 * we are dead and should go away.
	 */

	if (result != TCL_OK || !menuPtr->tkwin) {
	    goto endPostMenu;
	}

	CompleteIdlers(menuPtr);
	if (menuBarFlags & MENUBAR_REDRAW_PENDING) {
	    Tcl_CancelIdleCall(DrawMenuBarWhenIdle, NULL);
	    DrawMenuBarWhenIdle(NULL);
	}
	RecursivelyInsertMenu(menuPtr);

	TkMacOSXTrackingLoop(1);
	popUpResult = PopUpMenuSelect(macMenuHdl, y, x, menuPtr->active);
	TkMacOSXTrackingLoop(0);
	menuPtr->totalWidth = oldWidth;

	/*
	 * Simulate the mouse up.
	 */

	window = Tk_WindowId(menuPtr->tkwin);
	TkGenerateButtonEventForXPointer(window);

	/*
	 * Dispatch the command.
	 */

	menuID = HiWord(popUpResult);
	if (menuID != 0) {
	    result = TkMacOSXDispatchMenuEvent(menuID, LoWord(popUpResult));
	}

endPostMenu:
	inPostMenu--;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpMenuNewEntry --
 *
 *	Adds a pointer to a new menu entry structure with the platform-
 *	specific fields filled in. The Macintosh uses the
 *	platformEntryData field of the TkMenuEntry record to store
 *	geometry information.
 *
 * Results:
 *	Standard TCL error.
 *
 * Side effects:
 *	Storage gets allocated. New menu entry data is put into the
 *	platformEntryData field of the mePtr.
 *
 *----------------------------------------------------------------------
 */

int
TkpMenuNewEntry(
    TkMenuEntry *mePtr)		/* The menu we are adding an entry to */
{
    EntryGeometry *geometryPtr =
	    (EntryGeometry *) ckalloc(sizeof(EntryGeometry));
    TkMenu *menuPtr = mePtr->menuPtr;

    geometryPtr->accelTextStart = 0;
    geometryPtr->accelTextWidth = 0;
    geometryPtr->nonAccelMargin = 0;
    geometryPtr->modifierWidth = 0;
    geometryPtr->modifierNum = 0;
    geometryPtr->accelGlyph = 0;
    mePtr->platformEntryData = (TkMenuPlatformEntryData) geometryPtr;
    if (!(menuPtr->menuFlags & MENU_RECONFIGURE_PENDING)) {
	menuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
	Tcl_DoWhenIdle(ReconfigureMacintoshMenu, (ClientData) menuPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_MacOSXTurnOffMenus --
 *
 *	Turns off all the menu drawing code. This is more than just disabling
 *	the "menu" command, this means that Tk will NEVER touch the menubar.
 *	It is needed in the Plugin, where Tk does not own the menubar.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A flag is set which will disable all menu drawing.
 *
 *----------------------------------------------------------------------
 */

void
Tk_MacOSXTurnOffMenus(void)
{
    gNoTkMenus = 1;
}

/*
 *----------------------------------------------------------------------
 *
 * DrawMenuBarWhenIdle --
 *
 *	Update the menu bar next time there is an idle event.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Menu bar is redrawn.
 *
 *----------------------------------------------------------------------
 */

void
DrawMenuBarWhenIdle(
    ClientData clientData)	/* ignored here */
{
    TkMenuReferences *menuRefPtr;
    TkMenu *appleMenuPtr, *helpMenuPtr, *menuBarPtr = NULL;
    MenuHandle macMenuHdl;
    Tcl_HashEntry *hashEntryPtr;

    /*
     * If we have been turned off, exit.
     */

    if (gNoTkMenus) {
	return;
    }

    /*
     * We need to clear the apple and help menus of any extra items.
     */

    if (currentAppleMenuID != 0) {
	hashEntryPtr = Tcl_FindHashEntry(&commandTable,
		(char*)(intptr_t)currentAppleMenuID);
	appleMenuPtr = (TkMenu *) Tcl_GetHashValue(hashEntryPtr);
	TkpDestroyMenu(appleMenuPtr);
	TkpNewMenu(appleMenuPtr);
	appleMenuPtr->menuFlags &= ~MENU_APPLE_MENU;
	appleMenuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
	Tcl_DoWhenIdle(ReconfigureMacintoshMenu, (ClientData) appleMenuPtr);
    }

    if (currentHelpMenuID != 0) {
	hashEntryPtr = Tcl_FindHashEntry(&commandTable,
		(char*)(intptr_t)currentHelpMenuID);
	helpMenuPtr = (TkMenu *) Tcl_GetHashValue(hashEntryPtr);
	TkpDestroyMenu(helpMenuPtr);
	TkpNewMenu(helpMenuPtr);
	helpMenuPtr->menuFlags &= ~MENU_HELP_MENU;
	helpMenuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
	Tcl_DoWhenIdle(ReconfigureMacintoshMenu,
		(ClientData) helpMenuPtr);
    }

    /*
     * We need to find the clone of this menu that is the menubar.
     * Once we do that, for every cascade in the menu, we need to
     * insert the Mac menu in the Mac menubar. Finally, we need
     * to redraw the menubar.
     */

    menuRefPtr = NULL;
    if (currentMenuBarName != NULL) {
	menuRefPtr = TkFindMenuReferences(currentMenuBarInterp,
		currentMenuBarName);
    }
    if (menuRefPtr) {
	TkMenu *menuPtr;
	TkMenu *cascadeMenuPtr;
	char *appleMenuName, *helpMenuName;
	int appleIndex = -1, helpIndex = -1, i;

	menuPtr = menuRefPtr->menuPtr;
	if (menuPtr != NULL) {
	    TkMenuReferences *specialMenuRefPtr;
	    TkMenuEntry *specialEntryPtr;

	    appleMenuName = ckalloc(strlen(currentMenuBarName) + 1 +
		    strlen(".apple") + 1);
	    sprintf(appleMenuName, "%s.apple", Tk_PathName(menuPtr->tkwin));
	    specialMenuRefPtr = TkFindMenuReferences(currentMenuBarInterp,
		    appleMenuName);
	    if ((specialMenuRefPtr != NULL)
		    && (specialMenuRefPtr->menuPtr != NULL)) {
		for (specialEntryPtr = specialMenuRefPtr->parentEntryPtr;
			specialEntryPtr != NULL;
			specialEntryPtr = specialEntryPtr->nextCascadePtr) {
		    if (specialEntryPtr->menuPtr == menuPtr) {
			appleIndex = specialEntryPtr->index;
			break;
		    }
		}
	    }
	    ckfree(appleMenuName);

	    helpMenuName = ckalloc(strlen(currentMenuBarName) + 1 +
		    strlen(".help") + 1);
	    sprintf(helpMenuName, "%s.help", Tk_PathName(menuPtr->tkwin));
	    specialMenuRefPtr = TkFindMenuReferences(currentMenuBarInterp,
		    helpMenuName);
	    if ((specialMenuRefPtr != NULL)
		    && (specialMenuRefPtr->menuPtr != NULL)) {
		for (specialEntryPtr = specialMenuRefPtr->parentEntryPtr;
			specialEntryPtr != NULL;
			specialEntryPtr = specialEntryPtr->nextCascadePtr) {
		    if (specialEntryPtr->menuPtr == menuPtr) {
			helpIndex = specialEntryPtr->index;
			break;
		    }
		}
	    }
	    ckfree(helpMenuName);
	}

	for (menuBarPtr = menuPtr;
		(menuBarPtr != NULL) && (menuBarPtr->menuType != MENUBAR);
		menuBarPtr = menuBarPtr->nextInstancePtr) {
	    /*
	     * Null loop body.
	     */
	}

	if (menuBarPtr) {
	    if (menuBarPtr->tearoff != menuPtr->tearoff) {
		if (menuBarPtr->tearoff) {
		    appleIndex = (-1 == appleIndex) ? appleIndex
			    : appleIndex + 1;
		    helpIndex = (-1 == helpIndex) ? helpIndex
			    : helpIndex + 1;
		} else {
		    appleIndex = (-1 == appleIndex) ? appleIndex
			    : appleIndex - 1;
		    helpIndex = (-1 == helpIndex) ? helpIndex
			    : helpIndex - 1;
		}
	    }
	    ClearMenuBar();

	    if (appleIndex == -1) {
		InsertMenu(tkAppleMenu, 0);
		currentAppleMenuID = 0;
		tkCurrentAppleMenu = tkAppleMenu;
	    } else {
		short appleID;

		appleMenuPtr = menuBarPtr->entries[appleIndex]
			->childMenuRefPtr->menuPtr;
		TkpDestroyMenu(appleMenuPtr);
		TkMacOSXGetNewMenuID(appleMenuPtr->interp, appleMenuPtr, 0,
			&appleID);
		macMenuHdl = NewMenu(appleID, "\p\024");
		appleMenuPtr->platformData =
			(TkMenuPlatformData) ckalloc(sizeof(MacMenu));
		((MacMenu *)appleMenuPtr->platformData)->menuHdl
			= macMenuHdl;
		appleMenuPtr->menuFlags |= MENU_APPLE_MENU;
		if (!(appleMenuPtr->menuFlags
			& MENU_RECONFIGURE_PENDING)) {
		    appleMenuPtr->menuFlags |= MENU_RECONFIGURE_PENDING;
		    Tcl_DoWhenIdle(ReconfigureMacintoshMenu,
			    (ClientData) appleMenuPtr);
		}
		InsertMenu(macMenuHdl, 0);
		RecursivelyInsertMenu(appleMenuPtr);
		currentAppleMenuID = appleID;
		tkCurrentAppleMenu = macMenuHdl;
	    }
	    if (helpIndex == -1) {
		currentHelpMenuID = 0;
	    }

	    for (i = 0; i < menuBarPtr->numEntries; i++) {
		if (i == appleIndex) {
		    if (menuBarPtr->entries[i]->state == ENTRY_DISABLED) {
			DisableMenuItem(((MacMenu *) menuBarPtr->entries[i]
				->childMenuRefPtr->menuPtr
				->platformData)->menuHdl, 0);
		    } else {
			EnableMenuItem(((MacMenu *) menuBarPtr->entries[i]
				->childMenuRefPtr->menuPtr
				->platformData)->menuHdl, 0);
		    }
		    continue;
		} else if (i == helpIndex) {
		    TkMenu *helpMenuPtr = menuBarPtr->entries[i]
			    ->childMenuRefPtr->menuPtr;

		    if (helpMenuPtr == NULL) {
			continue;
		    }
		    helpMenuPtr->menuFlags |= MENU_HELP_MENU;
		    if (!(helpMenuPtr->menuFlags
			    & MENU_RECONFIGURE_PENDING)) {
			helpMenuPtr->menuFlags
				|= MENU_RECONFIGURE_PENDING;
			Tcl_DoWhenIdle(ReconfigureMacintoshMenu,
				(ClientData) helpMenuPtr);
		    }
		    macMenuHdl =
			    ((MacMenu *) helpMenuPtr->platformData)->menuHdl;
		    currentHelpMenuID = GetMenuID(macMenuHdl);
		} else if (menuBarPtr->entries[i]->type
			== CASCADE_ENTRY) {
		    if ((menuBarPtr->entries[i]->childMenuRefPtr != NULL)
			    && menuBarPtr->entries[i]->childMenuRefPtr
			    ->menuPtr != NULL) {
			cascadeMenuPtr = menuBarPtr->entries[i]
				->childMenuRefPtr->menuPtr;
			macMenuHdl = ((MacMenu *) cascadeMenuPtr
				->platformData)->menuHdl;
			DeleteMenu(GetMenuID(macMenuHdl));
			InsertMenu(macMenuHdl, 0);
			RecursivelyInsertMenu(cascadeMenuPtr);
			if (menuBarPtr->entries[i]->state == ENTRY_DISABLED) {
			    DisableMenuItem(((MacMenu *) menuBarPtr->entries[i]
				    ->childMenuRefPtr->menuPtr
				    ->platformData)->menuHdl, 0);
			} else {
			    EnableMenuItem(((MacMenu *) menuBarPtr->entries[i]
				    ->childMenuRefPtr->menuPtr
				    ->platformData)->menuHdl, 0);
			 }
		    }
		}
	    }
	}
    }
    if (!menuRefPtr || !menuBarPtr) {
	SetDefaultMenubar();
    }
    DrawMenuBar();
    menuBarFlags &= ~MENUBAR_REDRAW_PENDING;
}

/*
 *----------------------------------------------------------------------
 *
 * RecursivelyInsertMenu --
 *
 *	Puts all of the cascades of this menu in the Mac hierarchical list.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menubar is changed.
 *
 *----------------------------------------------------------------------
 */

void
RecursivelyInsertMenu(
    TkMenu *menuPtr)		/* All of the cascade items in this menu
				 * will be inserted into the mac menubar. */
{
    int i;
    TkMenu *cascadeMenuPtr;
    MenuHandle macMenuHdl;

    for (i = 0; i < menuPtr->numEntries; i++) {
	if (menuPtr->entries[i]->type == CASCADE_ENTRY) {
	    if ((menuPtr->entries[i]->childMenuRefPtr != NULL) &&
		    (menuPtr->entries[i]->childMenuRefPtr->menuPtr != NULL)) {
		cascadeMenuPtr = menuPtr->entries[i]->childMenuRefPtr->menuPtr;
		macMenuHdl =
			((MacMenu *) cascadeMenuPtr->platformData)->menuHdl;
		InsertMenu(macMenuHdl, -1);
		RecursivelyInsertMenu(cascadeMenuPtr);
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RecursivelyDeleteMenu --
 *
 *	Takes all of the cascades of this menu out of the Mac hierarchical
 *	list.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menubar is changed.
 *
 *----------------------------------------------------------------------
 */

void
RecursivelyDeleteMenu(
    TkMenu *menuPtr)		/* All of the cascade items in this menu
				 * will be deleted from the mac menubar. */
{
    int i;
    TkMenu *cascadeMenuPtr;
    MenuHandle macMenuHdl;

    for (i = 0; i < menuPtr->numEntries; i++) {
	if (menuPtr->entries[i]->type == CASCADE_ENTRY) {
	    if ((menuPtr->entries[i]->childMenuRefPtr != NULL) &&
		    (menuPtr->entries[i]->childMenuRefPtr->menuPtr != NULL)) {
		cascadeMenuPtr = menuPtr->entries[i]->childMenuRefPtr->menuPtr;
		macMenuHdl =
			((MacMenu *) cascadeMenuPtr->platformData)->menuHdl;
		DeleteMenu(GetMenuID(macMenuHdl));
		RecursivelyDeleteMenu(cascadeMenuPtr);
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SetDefaultMenubar --
 *
 *	Puts the Apple, File and Edit menus into the Macintosh menubar.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menubar is changed.
 *
 *----------------------------------------------------------------------
 */

void
SetDefaultMenubar(void)
{
    if (currentMenuBarName != NULL) {
	ckfree(currentMenuBarName);
	currentMenuBarName = NULL;
    }
    currentMenuBarOwner = NULL;
    ClearMenuBar();
    InsertMenu(tkAppleMenu, 0);
    InsertMenu(tkFileMenu, 0);
    InsertMenu(tkEditMenu, 0);
    if (!(menuBarFlags & MENUBAR_REDRAW_PENDING)) {
	Tcl_DoWhenIdle(DrawMenuBarWhenIdle, NULL);
	menuBarFlags |= MENUBAR_REDRAW_PENDING;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpSetMainMenubar --
 *
 *	Puts the menu associated with a window into the menubar. Should
 *	only be called when the window is in front.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menubar is changed.
 *
 *----------------------------------------------------------------------
 */

void
TkpSetMainMenubar(
    Tcl_Interp *interp,		/* The interpreter of the application */
    Tk_Window tkwin,		/* The frame we are setting up */
    char *menuName)		/* The name of the menu to put in front.
				 * If NULL, use the default menu bar.
				 */
{
    TkWindow *winPtr = (TkWindow *) tkwin;
    WindowRef macWindowPtr;
    WindowRef frontNonFloating;

    macWindowPtr = TkMacOSXDrawableWindow(winPtr->window);

    frontNonFloating = ActiveNonFloatingWindow();
    if ((macWindowPtr == NULL) || (macWindowPtr != frontNonFloating)) {
	return;
    }

    if ((currentMenuBarInterp != interp) || (currentMenuBarOwner != tkwin)
	    || (currentMenuBarName == NULL) || (menuName == NULL)
	    || (strcmp(menuName, currentMenuBarName) != 0)) {
	Tk_Window searchWindow;
	TopLevelMenubarList *listPtr;

	if (currentMenuBarName != NULL) {
	    ckfree(currentMenuBarName);
	}

	if (menuName == NULL) {
	    searchWindow = tkwin;
	    if (strcmp(Tk_Class(searchWindow), "Menu") == 0) {
		TkMenuReferences *menuRefPtr;

		menuRefPtr = TkFindMenuReferences(interp, Tk_PathName(tkwin));
		if (menuRefPtr != NULL) {
		    TkMenu *menuPtr = menuRefPtr->menuPtr;

		    if (menuPtr != NULL) {
			searchWindow = menuPtr->masterMenuPtr->tkwin;
		    }
		}
	    }
	    for (; searchWindow != NULL;
		    searchWindow = Tk_Parent(searchWindow)) {
		for (listPtr = windowListPtr; listPtr != NULL;
			listPtr = listPtr->nextPtr) {
		    if (listPtr->tkwin == searchWindow) {
			break;
		    }
		}
		if (listPtr != NULL) {
		    menuName = Tk_PathName(
			    listPtr->menuPtr->masterMenuPtr->tkwin);
		    break;
		}
	    }
	}

	if (menuName == NULL) {
	    currentMenuBarName = NULL;
	} else {
	    currentMenuBarName = ckalloc(strlen(menuName) + 1);
	    strcpy(currentMenuBarName, menuName);
	}
	currentMenuBarOwner = tkwin;
	currentMenuBarInterp = interp;
    }
    if (!(menuBarFlags & MENUBAR_REDRAW_PENDING)) {
	Tcl_DoWhenIdle(DrawMenuBarWhenIdle, NULL);
	menuBarFlags |= MENUBAR_REDRAW_PENDING;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpSetWindowMenuBar --
 *
 *	Associates a given menu with a window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	On Windows and UNIX, associates the platform menu with the
 *	platform window.
 *
 *----------------------------------------------------------------------
 */

void
TkpSetWindowMenuBar(
    Tk_Window tkwin,		/* The window we are setting the menu in */
    TkMenu *menuPtr)		/* The menu we are setting */
{
    TopLevelMenubarList *listPtr, *prevPtr;

    /*
     * Remove any existing reference to this window.
     */

    for (prevPtr = NULL, listPtr = windowListPtr;
	    listPtr != NULL;
	    prevPtr = listPtr, listPtr = listPtr->nextPtr) {
	if (listPtr->tkwin == tkwin) {
	    break;
	}
    }

    if (listPtr != NULL) {
	if (prevPtr != NULL) {
	    prevPtr->nextPtr = listPtr->nextPtr;
	} else {
	    windowListPtr = listPtr->nextPtr;
	}
	ckfree((char *) listPtr);
    }

    if (menuPtr != NULL) {
	listPtr = (TopLevelMenubarList *) ckalloc(sizeof(TopLevelMenubarList));
	listPtr->nextPtr = windowListPtr;
	windowListPtr = listPtr;
	listPtr->tkwin = tkwin;
	listPtr->menuPtr = menuPtr;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * EventuallyInvokeMenu --
 *
 *	This IdleTime callback actually invokes the menu command
 *	scheduled in TkMacOSXDispatchMenuEvent.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands get executed.
 *
 *----------------------------------------------------------------------
 */

void
EventuallyInvokeMenu (
    ClientData data)
{
    struct MenuCommandHandlerData *realData =
	    (struct MenuCommandHandlerData *) data;
    int code;

    code = TkInvokeMenu(realData->menuPtr->interp, realData->menuPtr,
	    realData->index);

    if (code != TCL_OK && code != TCL_CONTINUE && code != TCL_BREAK) {
	Tcl_AddErrorInfo(realData->menuPtr->interp, "\n    (menu invoke)");
	Tcl_BackgroundError(realData->menuPtr->interp);
    }

    if (realData->menuPtr->tkwin) {
	RecursivelyClearActiveMenu(realData->menuPtr);
    }
    TkMacOSXClearMenubarActive();

    Tcl_Release(realData->menuPtr->interp);
    Tcl_Release(realData->menuPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDispatchMenuEvent --
 *
 *	Given a menu id and an item, dispatches the command associated
 *	with it.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands for the event are scheduled for execution at idle time.
 *
 *----------------------------------------------------------------------
 */

int
TkMacOSXDispatchMenuEvent(
    int menuID,			/* The menu id of the menu we are invoking */
    int index)			/* The one-based index of the item that was
				 * selected. */
{
    int result = TCL_OK;

    if (menuID != 0) {
	if (menuID == kHMHelpMenuID) {
	    if (currentMenuBarOwner != NULL) {
		TkMenuReferences *helpMenuRef;
		char *helpMenuName = ckalloc(strlen(currentMenuBarName)
			+ strlen(".help") + 1);

		sprintf(helpMenuName, "%s.help", currentMenuBarName);
		helpMenuRef = TkFindMenuReferences(currentMenuBarInterp,
			helpMenuName);
		ckfree(helpMenuName);
		if ((helpMenuRef != NULL) && (helpMenuRef->menuPtr != NULL)) {
		    MenuRef outHelpMenu;
		    MenuItemIndex itemIndex;
		    int newIndex;

		    HMGetHelpMenu(&outHelpMenu, &itemIndex);
		    newIndex = index - itemIndex;
		    result = TkInvokeMenu(currentMenuBarInterp,
			    helpMenuRef->menuPtr, newIndex);
		}
	    }
	} else {
	    Tcl_HashEntry *commandEntryPtr =
		    Tcl_FindHashEntry(&commandTable, (char*)(intptr_t)menuID);
	    if (commandEntryPtr != NULL) {
		TkMenu *menuPtr = (TkMenu *) Tcl_GetHashValue(commandEntryPtr);

		if ((currentAppleMenuID == menuID)
			&& (index > menuPtr->numEntries + 1)) {
		    /*
		     * We don't need to do anything here, the standard
		     * Application event handler will open the built-in
		     * Apple menu item for us.
		     */
		    result = TCL_OK;
		} else {
		    struct MenuCommandHandlerData *data
			    = (struct MenuCommandHandlerData *)
			    ckalloc(sizeof(struct MenuCommandHandlerData));

		    Tcl_Preserve(menuPtr->interp);
		    Tcl_Preserve(menuPtr);
		    data->menuPtr = menuPtr;
		    data->index = index - 1;
		    Tcl_DoWhenIdle(EventuallyInvokeMenu,
			    (ClientData) data);
		    /* result = TkInvokeMenu(menuPtr->interp, menuPtr, index - 1); */
		}
	    } else {
		return TCL_ERROR;
	    }
	}
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GetMenuIndicatorGeometry --
 *
 *	Gets the width and height of the indicator area of a menu.
 *
 * Results:
 *	widthPtr and heightPtr are set.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
GetMenuIndicatorGeometry (
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are measuring */
    Tk_Font tkfont,		/* Precalculated font */
    const Tk_FontMetrics *fmPtr,/* Precalculated font metrics */
    int *widthPtr,		/* The resulting width */
    int *heightPtr)		/* The resulting height */
{
    *heightPtr = fmPtr->linespace + menuItemExtraHeight;
    if (IS_THEME_MENU_FONT(tkfont)) {
	*widthPtr = menuMarkColumnWidth;
    } else {
	const char markChar = FindMarkCharacter(mePtr);
	const char *markUtf = NULL;
	int len;

	len = GetUtfMarkCharacter(markChar, &markUtf);
	*widthPtr = Tk_TextWidth(tkfont, markUtf, len) + 2*menuMarkIndent;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetMenuAccelGeometry --
 *
 *	Gets the width and height of the accelerator area of a menu.
 *
 * Results:
 *	widthPtr and heightPtr are set.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
GetMenuAccelGeometry (
    TkMenu *menuPtr,		/* The menu we are measuring */
    TkMenuEntry *mePtr,		/* The entry we are measuring */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated font metrics */
    int *modWidthPtr,		/* The width of all of the key
				 * modifier symbols. */
    int *textWidthPtr,		/* The resulting width */
    int *heightPtr)		/* The resulting height */
{
    *heightPtr = fmPtr->linespace + menuItemExtraHeight;
    *modWidthPtr = menuSymbols[COMMAND_SYMBOL].width;
    *textWidthPtr = 0;
    if (mePtr->type != CASCADE_ENTRY && mePtr->accelLength > 0) {
	const char *accel = (mePtr->accelPtr == NULL) ? ""
		: Tcl_GetString(mePtr->accelPtr);
	EntryGeometry *geometryPtr = (EntryGeometry*)mePtr->platformEntryData;

	if (IS_THEME_MENU_FONT(tkfont)) {
	    CFStringRef cfStr;
	    int width = 0;
	    int maxWidth = ((TkFont *)tkfont)->fm.maxWidth;

	    if (geometryPtr->accelGlyph) {
		cfStr = CFStringCreateWithBytes(NULL,
			(UInt8*)&geometryPtr->accelGlyph, 1,
			kTextEncodingMacKeyboardGlyphs, false);
		if (cfStr) {
		    width = MeasureThemeText(cfStr, kThemeMenuItemCmdKeyFont);
		    CFRelease(cfStr);
		}
	    }
	    if ((mePtr->entryFlags & ENTRY_ACCEL_MASK) == 0) {
		if (!geometryPtr->accelGlyph) {
		     width = Tk_TextWidth(tkfont, accel, mePtr->accelLength);
		 }
		*textWidthPtr = maxWidth;
		if (width < maxWidth) {
		    *modWidthPtr = 0;
		} else {
		    *modWidthPtr = width - maxWidth;
		}
	    } else {
		if (!geometryPtr->accelGlyph) {
		    width = Tk_TextWidth(tkfont, accel +
			    geometryPtr->accelTextStart, mePtr->accelLength -
			    geometryPtr->accelTextStart);
		}
		if (width < maxWidth) {
		    *textWidthPtr = maxWidth;
		} else {
		    *textWidthPtr = width;
		}
		if (geometryPtr->modifierNum) {
		    *modWidthPtr = geometryPtr->modifierWidth;
		}
	    }
	} else {
	    *textWidthPtr = Tk_TextWidth(tkfont, accel, mePtr->accelLength);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetTearoffEntryGeometry --
 *
 *	Gets the width and height of of a tearoff entry.
 *
 * Results:
 *	widthPtr and heightPtr are set.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
GetTearoffEntryGeometry (
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are measuring */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated font metrics */
    int *widthPtr,		/* The resulting width */
    int *heightPtr)		/* The resulting height */
{
#ifdef USE_TK_MDEF
    const int useMDEF = ((MacMenu *) menuPtr->platformData)->useMDEF;
#endif
    if (useMDEF && menuPtr->menuType != TEAROFF_MENU) {
	*heightPtr = fmPtr->linespace + menuItemExtraHeight;
	*widthPtr = menuPtr->totalWidth;
    } else {
	*widthPtr = *heightPtr = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetMenuSeparatorGeometry --
 *
 *	Gets the width and height of menu separator.
 *
 * Results:
 *	widthPtr and heightPtr are set.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
GetMenuSeparatorGeometry(
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are measuring */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalcualted font metrics */
    int *widthPtr,		/* The resulting width */
    int *heightPtr)		/* The resulting height */
{
    *widthPtr = 0;
    *heightPtr = menuSeparatorHeight;
}

/*
 *----------------------------------------------------------------------
 *
 * DrawMenuEntryIndicator --
 *
 *	This procedure draws the indicator part of a menu.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
DrawMenuEntryIndicator(
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are drawing */
    Drawable d,			/* The drawable we are drawing */
    GC gc,			/* The GC we are drawing with */
    GC indicatorGC,		/* The GC to use for the indicator */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated font metrics */
    int x,			/* topleft hand corner of entry */
    int y,			/* topleft hand corner of entry */
    int width,			/* width of entry */
    int height)			/* height of entry */
{
    if ((mePtr->type == CHECK_BUTTON_ENTRY) ||
	    (mePtr->type == RADIO_BUTTON_ENTRY)) {
	if (mePtr->indicatorOn && (mePtr->entryFlags & ENTRY_SELECTED)) {
	    short mark;
	    int baseline = y + (height + fmPtr->ascent - fmPtr->descent)/2;

	    GetItemMark(((MacMenu *) menuPtr->platformData)->menuHdl,
		    mePtr->index + 1, &mark);
	    if (IS_THEME_MENU_FONT(tkfont)) {
		ThemeFontID font = kThemeMenuItemMarkFont;
		TextEncoding encoding = GetApplicationTextEncoding();
		CFStringRef cfStr;
		ThemeDrawState drawState;
		Rect bounds = {y, x + menuMarkIndent, y + height, x + width};

		if (mark < kSpaceCharCode) {
		    font = kThemeMenuItemCmdKeyFont;
		    encoding = kTextEncodingMacKeyboardGlyphs;
		}
		switch (mePtr->state) {
		    case ENTRY_ACTIVE:
			drawState = kThemeStatePressed;
			break;
		    case ENTRY_DISABLED:
			drawState = kThemeStateInactive;
			break;
		    default:
			drawState = kThemeStateActive;
			break;
		}
		cfStr = CFStringCreateWithBytes(NULL, (UInt8*)&mark, 1,
			encoding, false);
		if (cfStr) {
		    DrawThemeText(d, gc, cfStr, font, drawState, &bounds,
			    baseline, teFlushDefault);
		    CFRelease(cfStr);
		}
	    } else if (mark != 0) {
		const char *markUtf = NULL;
		int len;

		len = GetUtfMarkCharacter(mark, &markUtf);
		Tk_DrawChars(menuPtr->display, d, gc, tkfont, markUtf, len,
		    x + menuMarkIndent, baseline);
	    }
	}
    }
}

#ifdef USE_TK_MDEF
/*
 *----------------------------------------------------------------------
 *
 * DrawMenuBackground --
 *
 *	If Appearance is present, draws the Appearance background
 *
 * Results:
 *	Nothing
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */
void
DrawMenuBackground(
    TkMenu *menuPtr,
    Rect     *menuRectPtr,	/* The menu rect */
    Drawable d)			/* What we are drawing into */
{
    Tk_3DBorder border;

    EraseMenuBackground(((MacMenu *) menuPtr->platformData)->menuHdl,
	    menuRectPtr, ((MacDrawable*)d)->context);
    border = Tk_Get3DBorderFromObj(menuPtr->tkwin, menuPtr->borderPtr);
    Tk_Fill3DRectangle(menuPtr->tkwin, d, border,
	    menuRectPtr->left, menuRectPtr->top,
	    menuRectPtr->right - menuRectPtr->left,
	    menuRectPtr->bottom - menuRectPtr->top, 0, TK_RELIEF_FLAT);
}
#endif /* USE_TK_MDEF */

/*
 *----------------------------------------------------------------------
 *
 * DrawMenuEntryAccelerator --
 *
 *	This procedure draws the accelerator part of a menu.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
DrawMenuEntryAccelerator(
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are drawing */
    Drawable d,			/* The drawable we are drawing in */
    GC gc,			/* The gc to draw into */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated font metrics */
    Tk_3DBorder activeBorder,	/* border for menu background */
    int x,			/* The left side of the entry */
    int y,			/* The top of the entry */
    int width,			/* The width of the entry */
    int height,			/* The height of the entry */
    int drawArrow)		/* Whether or not to draw cascade arrow */
{
    if (mePtr->type != CASCADE_ENTRY && mePtr->accelLength > 0) {
	const char *accel = (mePtr->accelPtr == NULL) ? ""
		: Tcl_GetString(mePtr->accelPtr);
	EntryGeometry *geometryPtr = (EntryGeometry*)mePtr->platformEntryData;
	int leftEdge = x + width - geometryPtr->accelTextWidth;
	int baseline = y + (height + fmPtr->ascent - fmPtr->descent) / 2;

	if (IS_THEME_MENU_FONT(tkfont)) {
	    CFStringRef cfStr;
	    ThemeDrawState drawState;

	    switch (mePtr->state) {
		case ENTRY_ACTIVE:
		    drawState = kThemeStatePressed;
		    break;
		case ENTRY_DISABLED:
		    drawState = kThemeStateInactive;
		    break;
		default:
		    drawState = kThemeStateActive;
		    break;
	    }
	    if ((mePtr->entryFlags & ENTRY_ACCEL_MASK) == 0) {
		leftEdge -= geometryPtr->modifierWidth;
	    }
	    if (geometryPtr->accelGlyph) {
		Rect bounds = {y, leftEdge, y + height, leftEdge +
			geometryPtr->accelTextWidth};

		cfStr = CFStringCreateWithBytes(NULL,
			(UInt8*)&geometryPtr->accelGlyph, 1,
			kTextEncodingMacKeyboardGlyphs, false);
		if (cfStr) {
		    DrawThemeText(d, gc, cfStr, kThemeMenuItemCmdKeyFont,
			    drawState, &bounds, baseline, teFlushDefault);
		    CFRelease(cfStr);
		}
	    } else {
		Tk_DrawChars(menuPtr->display, d, gc, tkfont, accel + 
			geometryPtr->accelTextStart, mePtr->accelLength -
			geometryPtr->accelTextStart, leftEdge, baseline);
	    }
	    if (geometryPtr->modifierNum) {
		Rect bounds = {y, leftEdge - geometryPtr->modifierWidth,
			y + height, leftEdge};

		cfStr = CFStringCreateWithCharacters(NULL,
			geometryPtr->modifierUniChars,
			geometryPtr->modifierNum);
		if (cfStr) {
		    DrawThemeText(d, gc, cfStr, kThemeMenuItemCmdKeyFont,
			    drawState, &bounds, baseline, teFlushDefault);
		    CFRelease(cfStr);
		}
	    }
	} else {
	    Tk_DrawChars(menuPtr->display, d, gc, tkfont, accel,
		    mePtr->accelLength, leftEdge, baseline);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DrawMenuSeparator --
 *
 *	The menu separator is drawn.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
DrawMenuSeparator(
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are drawing */
    Drawable d,			/* The drawable we are drawing into */
    GC gc,			/* The gc we are drawing with */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated font metrics */
    int x,			/* left coordinate of entry */
    int y,			/* top coordinate of entry */
    int width,			/* width of entry */
    int height)			/* height of entry */
{
    TkMacOSXDrawingContext dc;
    Rect r;

    r.top = y;
    r.left = x;
    r.bottom = y + height;
    r.right = x + width;
    if (TkMacOSXSetupDrawingContext(d, gc, 1, &dc)) {
	ChkErr(DrawThemeMenuSeparator, &r);
	TkMacOSXRestoreDrawingContext(&dc);
    }
}

#ifdef USE_TK_MDEF
/*
 *----------------------------------------------------------------------
 *
 * AppearanceEntryDrawWrapper --
 *
 *	It routes to the Appearance Managers DrawThemeEntry, which will
 *	then call us back after setting up the drawing context.
 *
 * Results:
 *	A menu entry is drawn
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */
void
AppearanceEntryDrawWrapper(
    TkMenuEntry *mePtr,
    Rect *menuRectPtr,
    MenuTrackingData *mtdPtr,
    Drawable d,
    Tk_FontMetrics *fmPtr,
    Tk_Font tkfont,
    int erase)
{
    MenuEntryUserData meData;
    Rect itemRect;
    ThemeMenuState theState;
    ThemeMenuItemType theType;
    Tk_FontMetrics entryMetrics;

    meData.mePtr = mePtr;
    meData.mdefDrawable = d;
    if (mePtr->fontPtr == NULL) {
	meData.fmPtr = fmPtr;
	meData.tkfont = tkfont;
    } else {
	meData.tkfont = Tk_GetFontFromObj(mePtr->menuPtr->tkwin,
		mePtr->fontPtr);
	Tk_GetFontMetrics(meData.tkfont, &entryMetrics);
	fmPtr = &entryMetrics;
    }
    itemRect.left = menuRectPtr->left + mePtr->x;
    itemRect.top = mtdPtr->virtualMenuTop + mePtr->y;
    itemRect.right = mePtr->entryFlags & ENTRY_LAST_COLUMN ?
	    menuRectPtr->right : itemRect.left + mePtr->width;
    itemRect.bottom = itemRect.top + mePtr->height;

    if (mePtr->state == ENTRY_ACTIVE) {
	theState = kThemeMenuSelected;
    } else if (mePtr->state == ENTRY_DISABLED) {
	theState = kThemeMenuDisabled;
    } else {
	theState = kThemeMenuActive;
    }
    if (mePtr->type == CASCADE_ENTRY) {
	theType = kThemeMenuItemHierarchical;
    } else {
	theType = kThemeMenuItemPlain;
    }
    if (erase) {
	DisableScreenUpdates();
	DrawMenuBackground(mePtr->menuPtr, &itemRect, d);
    }
    DrawThemeMenuItem(menuRectPtr, &itemRect,
	mtdPtr->virtualMenuTop, mtdPtr->virtualMenuBottom, theState,
	theType | kThemeMenuItemNoBackground, tkThemeMenuItemDrawingUPP,
	(unsigned long) &meData);
    if (erase) {
	EnableScreenUpdates();
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ThemeMenuItemDrawingProc --
 *
 *	This routine is called from the Appearance DrawThemeMenuEntry
 *
 * Results:
 *	A menu entry is drawn
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */
pascal void
ThemeMenuItemDrawingProc(
    const Rect *inBounds,
    SInt16 inDepth,
    Boolean inIsColorDevice,
    SInt32 inUserData)
{
    MenuEntryUserData *meData = (MenuEntryUserData *) inUserData;

    TkpDrawMenuEntry(meData->mePtr, meData->mdefDrawable, meData->tkfont,
	    meData->fmPtr, inBounds->left, inBounds->top, inBounds->right -
	    inBounds->left + menuItemExtraWidth, inBounds->bottom -
	    inBounds->top + menuItemExtraHeight, 0, 1);
}
#endif /* USE_TK_MDEF */

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXHandleTearoffMenu() --
 *
 *	This routine sees if the MDEF has set a menu and a mouse position
 *	for tearing off and makes a tearoff menu if it has.
 *
 * Results:
 *	menuPtr->interp will have the result of the tearoff command.
 *
 * Side effects:
 *	A new tearoff menu is created if it is supposed to be.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXHandleTearoffMenu(void)
{
    /*
     * Obsolete: Nothing to do.
     */
}

/*
 *--------------------------------------------------------------
 *
 * TkpInitializeMenuBindings --
 *
 *	For every interp, initializes the bindings for Windows
 *	menus. Does nothing on Mac or XWindows.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	C-level bindings are setup for the interp which will
 *	handle Alt-key sequences for menus without beeping
 *	or interfering with user-defined Alt-key bindings.
 *
 *--------------------------------------------------------------
 */

void
TkpInitializeMenuBindings(
    Tcl_Interp *interp,		/* The interpreter to set. */
    Tk_BindingTable bindingTable)
				/* The table to add to. */
{
    /*
     * Nothing to do.
     */
}

/*
 *--------------------------------------------------------------
 *
 * TkpComputeMenubarGeometry --
 *
 *	This procedure is invoked to recompute the size and
 *	layout of a menu that is a menubar clone.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Fields of menu entries are changed to reflect their
 *	current positions, and the size of the menu window
 *	itself may be changed.
 *
 *--------------------------------------------------------------
 */

void
TkpComputeMenubarGeometry(
    TkMenu *menuPtr)		/* Structure describing menu. */
{
    TkpComputeStandardMenuGeometry(menuPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DrawTearoffEntry --
 *
 *	This procedure draws a tearoff entry.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
DrawTearoffEntry(
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are drawing */
    Drawable d,			/* The drawable we are drawing into */
    GC gc,			/* The gc we are drawing with */
    Tk_Font tkfont,		/* The font we are drawing with */
    const Tk_FontMetrics *fmPtr,/* The metrics we are drawing with */
    int x,			/* Left edge of entry. */
    int y,			/* Top edge of entry. */
    int width,			/* Width of entry. */
    int height)			/* Height of entry. */
{
    XPoint points[2];
    int margin, segmentWidth, maxX;
    Tk_3DBorder border;

    if (menuPtr->menuType != MASTER_MENU ) {
	return;
    }

    margin = fmPtr->linespace/2;
    points[0].x = x;
    points[0].y = y + height/2;
    points[1].y = points[0].y;
    segmentWidth = 6;
    maxX  = x + menuPtr->totalWidth - 1;
    border = Tk_Get3DBorderFromObj(menuPtr->tkwin, menuPtr->borderPtr);

    while (points[0].x < maxX) {
	points[1].x = points[0].x + segmentWidth;
	if (points[1].x > maxX) {
	    points[1].x = maxX;
	}
	Tk_Draw3DPolygon(menuPtr->tkwin, d, border, points, 2, 1,
		TK_RELIEF_RAISED);
	points[0].x += 2*segmentWidth;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetHelpMenuItemCount --
 *
 *	Has to be called after the first call to InsertMenu. Sets
 *	up the global variable for the number of items in the
 *	unmodified help menu.
 *	NB. Nobody uses this any more, since you can get the number
 *	of system help items from HMGetHelpMenu trivially.
 *	But it is in the stubs table...
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Nothing.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXSetHelpMenuItemCount(void)
{
    /*
     * Obsolete: Nothing to do.
     */
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXMenuClick --
 *
 *	Prepares a menubar for MenuSelect or MenuKey.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Any pending configurations of the menubar are completed.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXMenuClick(void)
{
    TkMenu *menuPtr;
    TkMenuReferences *menuRefPtr;

    if ((currentMenuBarInterp != NULL) && (currentMenuBarName != NULL)) {
	menuRefPtr = TkFindMenuReferences(currentMenuBarInterp,
		currentMenuBarName);
	for (menuPtr = menuRefPtr->menuPtr->masterMenuPtr;
		menuPtr != NULL; menuPtr = menuPtr->nextInstancePtr) {
	    if (menuPtr->menuType == MENUBAR) {
		CompleteIdlers(menuPtr);
		break;
	    }
	}
    }

    if (menuBarFlags & MENUBAR_REDRAW_PENDING) {
	Tcl_CancelIdleCall(DrawMenuBarWhenIdle, NULL);
	DrawMenuBarWhenIdle(NULL);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpDrawMenuEntry --
 *
 *	Draws the given menu entry at the given coordinates with the
 *	given attributes.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	X Server commands are executed to display the menu entry.
 *
 *----------------------------------------------------------------------
 */

void
TkpDrawMenuEntry(
    TkMenuEntry *mePtr,		/* The entry to draw */
    Drawable d,			/* What to draw into */
    Tk_Font tkfont,		/* Precalculated font for menu */
    const Tk_FontMetrics *menuMetricsPtr,
				/* Precalculated metrics for menu */
    int x,			/* X-coordinate of topleft of entry */
    int y,			/* Y-coordinate of topleft of entry */
    int width,			/* Width of the entry rectangle */
    int height,			/* Height of the current rectangle */
    int strictMotif,		/* Boolean flag */
    int drawArrow)		/* Whether or not to draw the cascade
				 * arrow for cascade items. Only applies
				 * to Windows. */
{
    GC gc;
    TkMenu *menuPtr = mePtr->menuPtr;
    int padY = (menuPtr->menuType == MENUBAR) ? 3 : 0;
    GC indicatorGC;
    Tk_3DBorder bgBorder, activeBorder;
    const Tk_FontMetrics *fmPtr;
    Tk_FontMetrics entryMetrics;
    int adjustedY = y + padY;
    int adjustedHeight = height - 2 * padY;

    /*
     * Choose the gc for drawing the foreground part of the entry.
     * Under Appearance, we pass a null (appearanceGC) to tell
     * ourselves not to change whatever color the appearance manager has set.
     */

    if ((mePtr->state == ENTRY_ACTIVE) && !strictMotif) {
	gc = mePtr->activeGC;
	if (gc == NULL) {
	    gc = menuPtr->activeGC;
	}
    } else {
	TkMenuEntry *parentEntryPtr = GetParentMenuEntry(menuPtr);

	if (((parentEntryPtr && parentEntryPtr->state == ENTRY_DISABLED) ||
		(mePtr->state == ENTRY_DISABLED)) &&
		(menuPtr->disabledFgPtr != NULL)) {
	    gc = mePtr->disabledGC;
	    if (gc == NULL) {
		gc = menuPtr->disabledGC;
	    }
	} else {
	    gc = mePtr->textGC;
	    if (gc == NULL) {
		gc = menuPtr->textGC;
	    }
	}
    }

    indicatorGC = mePtr->indicatorGC;
    if (indicatorGC == NULL) {
	indicatorGC = menuPtr->indicatorGC;
    }

    bgBorder = Tk_Get3DBorderFromObj(menuPtr->tkwin,
	    (mePtr->borderPtr == NULL)
	    ? menuPtr->borderPtr : mePtr->borderPtr);
    if (strictMotif) {
	activeBorder = bgBorder;
    } else {
	activeBorder = Tk_Get3DBorderFromObj(menuPtr->tkwin,
	    (mePtr->activeBorderPtr == NULL)
	    ? menuPtr->activeBorderPtr : mePtr->activeBorderPtr);
    }

    if (mePtr->fontPtr == NULL) {
	fmPtr = menuMetricsPtr;
    } else {
	tkfont = Tk_GetFontFromObj(menuPtr->tkwin, mePtr->fontPtr);
	Tk_GetFontMetrics(tkfont, &entryMetrics);
	fmPtr = &entryMetrics;
    }

    /*
     * Need to draw the entire background, including padding. On Unix,
     * for menubars, we have to draw the rest of the entry taking
     * into account the padding.
     */

    DrawMenuEntryBackground(menuPtr, mePtr, d, activeBorder, bgBorder, x, y,
	    width, height);

    if (mePtr->type == SEPARATOR_ENTRY) {
	DrawMenuSeparator(menuPtr, mePtr, d, gc, tkfont,
		fmPtr, x, adjustedY, width, adjustedHeight);
    } else if (mePtr->type == TEAROFF_ENTRY) {
	DrawTearoffEntry(menuPtr, mePtr, d, gc, tkfont, fmPtr, x, adjustedY,
		width, adjustedHeight);
    } else {
	DrawMenuEntryLabel(menuPtr, mePtr, d, gc, tkfont, fmPtr, x,
		adjustedY, width, adjustedHeight);
	DrawMenuEntryAccelerator(menuPtr, mePtr, d, gc, tkfont, fmPtr,
		activeBorder, x, adjustedY, width, adjustedHeight, drawArrow);
	if (!mePtr->hideMargin) {
	    DrawMenuEntryIndicator(menuPtr, mePtr, d, gc, indicatorGC, tkfont,
		    fmPtr, x, adjustedY, width, adjustedHeight);
	}
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkpComputeStandardMenuGeometry --
 *
 *	This procedure is invoked to recompute the size and
 *	layout of a menu that is not a menubar clone.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Fields of menu entries are changed to reflect their
 *	current positions, and the size of the menu window
 *	itself may be changed.
 *
 *--------------------------------------------------------------
 */

void
TkpComputeStandardMenuGeometry(
    TkMenu *menuPtr)		/* Structure describing menu. */
{
    Tk_Font tkfont, menuFont;
    Tk_FontMetrics menuMetrics, entryMetrics, *fmPtr;
    int x, y, height, modifierWidth, labelWidth, indicatorSpace;
    int windowWidth, windowHeight, accelWidth, maxAccelTextWidth;
    int i, j, lastColumnBreak, maxModifierWidth, maxWidth, nonAccelMargin;
    int maxNonAccelMargin, maxEntryWithAccelWidth, maxEntryWithoutAccelWidth;
    int entryWidth, maxIndicatorSpace, borderWidth, activeBorderWidth;
    TkMenuEntry *mePtr, *columnEntryPtr;
    EntryGeometry *geometryPtr;
    int haveAccel = 0;

    if (menuPtr->tkwin == NULL) {
	return;
    }

    Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr,
	    &borderWidth);
    Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->activeBorderWidthPtr,
	    &activeBorderWidth);
    x = y = borderWidth;
    indicatorSpace = labelWidth = accelWidth = maxAccelTextWidth = 0;
    windowHeight = windowWidth = maxWidth = lastColumnBreak = 0;
    maxModifierWidth = nonAccelMargin = maxNonAccelMargin = 0;
    maxEntryWithAccelWidth = maxEntryWithoutAccelWidth = 0;
    maxIndicatorSpace = 0;

    /*
     * On the Mac especially, getting font metrics can be quite slow,
     * so we want to do it intelligently. We are going to precalculate
     * them and pass them down to all of the measuring and drawing
     * routines. We will measure the font metrics of the menu once.
     * If an entry does not have its own font set, then we give
     * the geometry/drawing routines the menu's font and metrics.
     * If an entry has its own font, we will measure that font and
     * give all of the geometry/drawing the entry's font and metrics.
     */

    menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
    Tk_GetFontMetrics(menuFont, &menuMetrics);

    for (i = 0; i < menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->type == CASCADE_ENTRY || mePtr->accelLength > 0) {
	    haveAccel = 1;
	    break;
	}
    }

    for (i = 0; i < menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->fontPtr == NULL) {
	    tkfont = menuFont;
	    fmPtr = &menuMetrics;
	} else {
	    tkfont = Tk_GetFontFromObj(menuPtr->tkwin, mePtr->fontPtr);
	    Tk_GetFontMetrics(tkfont, &entryMetrics);
	    fmPtr = &entryMetrics;
	}

	if ((i > 0) && mePtr->columnBreak) {
	    if (maxIndicatorSpace != 0) {
		maxIndicatorSpace += 2;
	    }
	    for (j = lastColumnBreak; j < i; j++) {
		columnEntryPtr = menuPtr->entries[j];
		geometryPtr =
			(EntryGeometry *) columnEntryPtr->platformEntryData;

		columnEntryPtr->indicatorSpace = maxIndicatorSpace;
		columnEntryPtr->width = maxIndicatorSpace + maxWidth
			+ 2 * activeBorderWidth;
		geometryPtr->accelTextWidth = maxAccelTextWidth;
		geometryPtr->modifierWidth = maxModifierWidth;
		columnEntryPtr->x = x;
		columnEntryPtr->entryFlags &= ~ENTRY_LAST_COLUMN;
		if (maxEntryWithoutAccelWidth > maxEntryWithAccelWidth) {
		    geometryPtr->nonAccelMargin = maxEntryWithoutAccelWidth
			    - maxEntryWithAccelWidth;
		    if (geometryPtr->nonAccelMargin > maxNonAccelMargin) {
			geometryPtr->nonAccelMargin = maxNonAccelMargin;
		    }
		} else {
		    geometryPtr->nonAccelMargin = 0;
		}
	    }
	    x += maxIndicatorSpace + maxWidth + 2 * borderWidth;
	    windowWidth = x;
	    maxWidth = maxIndicatorSpace = maxAccelTextWidth = 0;
	    maxModifierWidth = maxNonAccelMargin = maxEntryWithAccelWidth = 0;
	    maxEntryWithoutAccelWidth = 0;
	    lastColumnBreak = i;
	    y = borderWidth;
	}
	geometryPtr = (EntryGeometry *) mePtr->platformEntryData;

	if (mePtr->type == SEPARATOR_ENTRY) {
	    GetMenuSeparatorGeometry(menuPtr, mePtr, tkfont,
		    fmPtr, &entryWidth, &height);
	    mePtr->height = height;
	} else if (mePtr->type == TEAROFF_ENTRY) {
	    GetTearoffEntryGeometry(menuPtr, mePtr, tkfont,
		    fmPtr, &entryWidth, &height);
	    mePtr->height = height;
	} else {
	    /*
	     * For each entry, compute the height required by that
	     * particular entry, plus three widths:  the width of the
	     * label, the width to allow for an indicator to be displayed
	     * to the left of the label (if any), and the width of the
	     * accelerator to be displayed to the right of the label
	     * (if any). These sizes depend, of course, on the type
	     * of the entry.
	     */

	    GetMenuLabelGeometry(mePtr, tkfont, fmPtr, &labelWidth, &height);
	    mePtr->height = height;

	    nonAccelMargin = 0;
	    if (mePtr->type == CASCADE_ENTRY) {
		GetMenuAccelGeometry(menuPtr, mePtr, tkfont, fmPtr,
			&modifierWidth, &accelWidth, &height);
	    } else if (mePtr->accelLength == 0) {
		if (haveAccel && !mePtr->hideMargin) {
		    if (IS_THEME_MENU_FONT(tkfont)) {
			nonAccelMargin = menuSymbols[COMMAND_SYMBOL].width;
		    } else {
			nonAccelMargin = Tk_TextWidth(tkfont,
				menuSymbols[COMMAND_SYMBOL].utf,
				menuSymbols[COMMAND_SYMBOL].utfLen);
		    }
		}
		accelWidth = modifierWidth = 0;
	    } else {
		GetMenuAccelGeometry(menuPtr, mePtr, tkfont,
			fmPtr, &modifierWidth, &accelWidth, &height);
		if (height > mePtr->height) {
		    mePtr->height = height;
		}
	    }

	    if (!(mePtr->hideMargin)) {
		GetMenuIndicatorGeometry(menuPtr, mePtr, tkfont,
			fmPtr, &indicatorSpace, &height);
		if (height > mePtr->height) {
		    mePtr->height = height;
		}
	    } else {
		indicatorSpace = 0;
	    }

	    if (nonAccelMargin > maxNonAccelMargin) {
		maxNonAccelMargin = nonAccelMargin;
	    }
	    if (accelWidth > maxAccelTextWidth) {
		maxAccelTextWidth = accelWidth;
	    }
	    if (modifierWidth > maxModifierWidth) {
		maxModifierWidth = modifierWidth;
	    }
	    if (indicatorSpace > maxIndicatorSpace) {
		maxIndicatorSpace = indicatorSpace;
	    }

	    entryWidth = labelWidth + modifierWidth + accelWidth
		    + nonAccelMargin;

	    if (entryWidth > maxWidth) {
		maxWidth = entryWidth;
	    }

	    if (mePtr->accelLength > 0) {
		if (entryWidth > maxEntryWithAccelWidth) {
		    maxEntryWithAccelWidth = entryWidth;
		}
	    } else {
		if (entryWidth > maxEntryWithoutAccelWidth) {
		    maxEntryWithoutAccelWidth = entryWidth;
		}
	    }
	    mePtr->height += 2 * activeBorderWidth;
	}
	mePtr->y = y;
	y += menuPtr->entries[i]->height + borderWidth;
	if (y > windowHeight) {
	    windowHeight = y;
	}
    }

    for (j = lastColumnBreak; j < menuPtr->numEntries; j++) {
	columnEntryPtr = menuPtr->entries[j];
	geometryPtr = (EntryGeometry *) columnEntryPtr->platformEntryData;

	columnEntryPtr->indicatorSpace = maxIndicatorSpace;
	columnEntryPtr->width = maxIndicatorSpace + maxWidth
		+ 2 * activeBorderWidth;
	geometryPtr->accelTextWidth = maxAccelTextWidth;
	columnEntryPtr->x = x;
	columnEntryPtr->entryFlags |= ENTRY_LAST_COLUMN;
	if (maxEntryWithoutAccelWidth > maxEntryWithAccelWidth) {
	    geometryPtr->nonAccelMargin = maxEntryWithoutAccelWidth
		    - maxEntryWithAccelWidth;
	    if (geometryPtr->nonAccelMargin > maxNonAccelMargin) {
		geometryPtr->nonAccelMargin = maxNonAccelMargin;
	    }
	} else {
	    geometryPtr->nonAccelMargin = 0;
	}
    }
    windowWidth = x + maxIndicatorSpace + maxWidth
	    + 2 * activeBorderWidth + borderWidth;
    windowHeight += borderWidth;

    /*
     * The X server doesn't like zero dimensions, so round up to at least
     * 1 (a zero-sized menu should never really occur, anyway).
     */

    if (windowWidth <= 0) {
	windowWidth = 1;
    }
    if (windowHeight <= 0) {
	windowHeight = 1;
    }
    menuPtr->totalWidth = windowWidth;
    menuPtr->totalHeight = windowHeight;
}

/*
 *----------------------------------------------------------------------
 *
 * DrawMenuEntryLabel --
 *
 *	This procedure draws the label part of a menu.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
DrawMenuEntryLabel(
    TkMenu *menuPtr,		/* The menu we are drawing */
    TkMenuEntry *mePtr,		/* The entry we are drawing */
    Drawable d,			/* What we are drawing into */
    GC gc,			/* The gc we are drawing into */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated font metrics */
    int x,			/* left edge */
    int y,			/* right edge */
    int width,			/* width of entry */
    int height)			/* height of entry */
{
    int imageWidth, imageHeight, textWidth = 0, textHeight = 0;
    int indicatorSpace =  mePtr->indicatorSpace;
    int leftEdge = x + indicatorSpace;
    int haveImage = 0, haveText = 0;
    int imageXOffset = 0, imageYOffset = 0;
    int textXOffset = 0, textYOffset = 0;
    Pixmap bitmap = (Pixmap) NULL;
    Tcl_DString itemTextDString;

    /*
     * Work out what we will need to draw first.
     */

    if (mePtr->image != NULL) {
	Tk_SizeOfImage(mePtr->image, &imageWidth, &imageHeight);
	haveImage = 1;
    } else if (mePtr->bitmapPtr != NULL) {
	bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin, mePtr->bitmapPtr);
	Tk_SizeOfBitmap(menuPtr->display, bitmap, &imageWidth, &imageHeight);
	haveImage = 1;
    }
    if (!haveImage || (mePtr->compound != COMPOUND_NONE)) {
	if (mePtr->labelLength > 0) {
	    GetEntryText(mePtr, &itemTextDString);
	    if (mePtr->compound != COMPOUND_NONE) {
		textWidth = Tk_TextWidth(tkfont,
			Tcl_DStringValue(&itemTextDString),
			Tcl_DStringLength(&itemTextDString)) +
			menuTextLeadingEdgeMargin + menuTextTrailingEdgeMargin;
		textHeight = fmPtr->linespace;
	    }
	    haveText = 1;
	}
    }

    /*
     * Now work out what the relative positions are.
     */

    if (haveImage && haveText && (mePtr->compound != COMPOUND_NONE)) {
	int fullWidth = (imageWidth > textWidth ? imageWidth : textWidth);

	switch ((enum compound) mePtr->compound) {
	    case COMPOUND_TOP:
		textXOffset = (fullWidth - textWidth)/2;
		textYOffset = imageHeight/2 + 2;
		imageXOffset = (fullWidth - imageWidth)/2;
		imageYOffset = -textHeight/2;
		break;
	    case COMPOUND_BOTTOM:
		textXOffset = (fullWidth - textWidth)/2;
		textYOffset = -imageHeight/2;
		imageXOffset = (fullWidth - imageWidth)/2;
		imageYOffset = textHeight/2 + 2;
		break;
	    case COMPOUND_LEFT:
		/*
		 * Position image in the indicator space to the left of the
		 * entries, unless this entry is a radio|check button because
		 * then the indicator space will be used.
		 */

		textXOffset = imageWidth + 2 - menuTextLeadingEdgeMargin;
		if ((mePtr->type != CHECK_BUTTON_ENTRY)
			&& (mePtr->type != RADIO_BUTTON_ENTRY)) {
		    textXOffset -= indicatorSpace;
		    imageXOffset = -indicatorSpace;
		}
		if (textXOffset < 0) {
		    textXOffset = 0;
		}
		break;
	    case COMPOUND_RIGHT:
		imageXOffset = textWidth + 2 - menuTextTrailingEdgeMargin;
		break;
	    case COMPOUND_CENTER:
		textXOffset = (fullWidth - textWidth)/2;
		imageXOffset = (fullWidth - imageWidth)/2;
		break;
	    case COMPOUND_NONE:
	    	/*
	    	 * Never reached.
	    	 */
		break;
	}
    }

    /*
     * Draw label and/or bitmap or image for entry.
     */

    if (mePtr->image != NULL) {
	if ((mePtr->selectImage != NULL)
		&& (mePtr->entryFlags & ENTRY_SELECTED)) {
	    Tk_RedrawImage(mePtr->selectImage, 0, 0, imageWidth, imageHeight,
		    d, leftEdge + imageXOffset,
		    y + (mePtr->height - imageHeight)/2 + imageYOffset);
	} else {
	    Tk_RedrawImage(mePtr->image, 0, 0, imageWidth, imageHeight,
		    d, leftEdge + imageXOffset,
		    y + (mePtr->height - imageHeight)/2 + imageYOffset);
	}
    } else if (mePtr->bitmapPtr != NULL) {
	XCopyPlane(menuPtr->display, bitmap, d, gc, 0, 0, imageWidth,
		imageHeight, leftEdge + imageXOffset,
		y + (mePtr->height - imageHeight)/2  + imageYOffset, 1);
    }
    if (haveText) {
	int baseline = y + (height + fmPtr->ascent - fmPtr->descent)/2;

	Tk_DrawChars(menuPtr->display, d, gc, tkfont,
		Tcl_DStringValue(&itemTextDString),
		Tcl_DStringLength(&itemTextDString),
		leftEdge + menuTextLeadingEdgeMargin + textXOffset,
		baseline + textYOffset);
	Tcl_DStringFree(&itemTextDString);
    }

    if (mePtr->state == ENTRY_DISABLED) {
	if (menuPtr->disabledFgPtr == NULL) {
	    /* XFillRectangle(menuPtr->display, d, menuPtr->disabledGC, x, y,
		    width, height); */
	} else if ((mePtr->image != NULL)
		&& (menuPtr->disabledImageGC != None)) {
	    XFillRectangle(menuPtr->display, d, menuPtr->disabledImageGC,
		    leftEdge + imageXOffset,
		    y + (mePtr->height - imageHeight)/2 + imageYOffset,
		    imageWidth, imageHeight);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DrawMenuEntryBackground --
 *
 *	This procedure draws the background part of a menu entry.
 *	Under Appearance, we only draw the background if the entry's
 *	border is set, we DO NOT inherit it from the menu...
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menu in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
DrawMenuEntryBackground(
    TkMenu *menuPtr,		/* The menu we are drawing. */
    TkMenuEntry *mePtr,		/* The entry we are drawing. */
    Drawable d,			/* What we are drawing into */
    Tk_3DBorder activeBorder,	/* Border for active items */
    Tk_3DBorder bgBorder,	/* Border for the background */
    int x,			/* left edge */
    int y,			/* top edge */
    int width,			/* width of rectangle to draw */
    int height)			/* height of rectangle to draw */
{
    if ((menuPtr->menuType == TEAROFF_MENU)
	    || ((mePtr->state == ENTRY_ACTIVE)
		    && (mePtr->activeBorderPtr != None))
	    || ((mePtr->state != ENTRY_ACTIVE) && (mePtr->borderPtr != None))) {
	if (mePtr->state == ENTRY_ACTIVE) {
	    bgBorder = activeBorder;
	}
	Tk_Fill3DRectangle(menuPtr->tkwin, d, bgBorder,
		x, y, width, height, 0, TK_RELIEF_FLAT);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetMenuLabelGeometry --
 *
 *	Figures out the size of the label portion of a menu item.
 *
 * Results:
 *	widthPtr and heightPtr are filled in with the correct geometry
 *	information.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
GetMenuLabelGeometry(
    TkMenuEntry *mePtr,		/* The entry we are computing */
    Tk_Font tkfont,		/* The precalculated font */
    const Tk_FontMetrics *fmPtr,/* The precalculated metrics */
    int *widthPtr,		/* The resulting width of the label portion */
    int *heightPtr)		/* The resulting height of the label portion */
{
    TkMenu *menuPtr = mePtr->menuPtr;
    int haveImage = 0, tornOff = (menuPtr->menuType == TEAROFF_MENU);
#ifdef USE_TK_MDEF
    const int useMDEF = ((MacMenu *) menuPtr->platformData)->useMDEF;
#endif

    if (mePtr->image != NULL && (useMDEF || tornOff)) {
	Tk_SizeOfImage(mePtr->image, widthPtr, heightPtr);
	haveImage = 1;
    } else if (mePtr->bitmapPtr != NULL && (useMDEF || tornOff)) {
	Pixmap bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin, mePtr->bitmapPtr);
	Tk_SizeOfBitmap(menuPtr->display, bitmap, widthPtr, heightPtr);
	haveImage = 1;
    }
    if (!haveImage || (mePtr->compound != COMPOUND_NONE)) {
	int textWidth = 0, textHeight = fmPtr->linespace;

	if (mePtr->labelPtr != NULL) {
	    Tcl_DString itemTextDString;

	    GetEntryText(mePtr, &itemTextDString);
	    textWidth = Tk_TextWidth(tkfont,
		    Tcl_DStringValue(&itemTextDString),
		    Tcl_DStringLength(&itemTextDString)) +
		    menuTextLeadingEdgeMargin + menuTextTrailingEdgeMargin;
	    Tcl_DStringFree(&itemTextDString);

	    if (haveImage && (mePtr->compound != COMPOUND_NONE)) {
		switch ((enum compound) mePtr->compound) {
		    int margin;

		    case COMPOUND_TOP:
		    case COMPOUND_BOTTOM:
			if (textWidth > *widthPtr) {
			    *widthPtr = textWidth;
			}
			*heightPtr += textHeight + 2;
			break;
		    case COMPOUND_LEFT:
			margin = *widthPtr + 2;
			if (margin > menuTextLeadingEdgeMargin) {
			    margin = menuTextLeadingEdgeMargin;
			}
			*widthPtr += textWidth + 2 - margin;
			if (textHeight > *heightPtr) {
			    *heightPtr = textHeight;
			}
			break;
		    case COMPOUND_RIGHT:
			margin = menuTextTrailingEdgeMargin;
			*widthPtr += textWidth + 2 - margin;
			if (textHeight > *heightPtr) {
			    *heightPtr = textHeight;
			}
			break;
		    case COMPOUND_CENTER:
			if (textWidth > *widthPtr) {
			    *widthPtr = textWidth;
			}
			if (textHeight > *heightPtr) {
			    *heightPtr = textHeight;
			}
			break;
		    case COMPOUND_NONE:
			/*
			 * Never reached.
			 */
			break;
		}
		goto labelGeomDone;
	    }
	}
	*widthPtr = textWidth;
	*heightPtr = textHeight;
    }

labelGeomDone:
    *heightPtr += menuItemExtraHeight;
    *widthPtr += menuItemExtraWidth;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGenerateParentMenuSelectEvent --
 *
 *	Respond to a hierarchical menu being opened.
 *
 * Results:
 *	True if event(s) are generated - false otherwise.
 *
 * Side effects:
 *	Places a virtual event on the event queue.
 *
 *----------------------------------------------------------------------
 */

int
TkMacOSXGenerateParentMenuSelectEvent(
    MenuRef menu)
{
    TkMenu *menuPtr = MenuPtrForMenuRef(menu);

    if (menuPtr) {
	TkMenuEntry *parentEntryPtr = GetParentMenuEntry(menuPtr);

	if (parentEntryPtr && (menuPtr = parentEntryPtr->menuPtr)) {
	    TkActivateMenuEntry(menuPtr, parentEntryPtr->index);
	    MenuSelectEvent(menuPtr);
	    Tcl_ServiceAll();
	    return true;
	}
    }
    return false;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGenerateMenuSelectEvent --
 *
 *	Respond to a menu item being selected.
 *
 * Results:
 *	True if event(s) are generated - false otherwise.
 *
 * Side effects:
 *	Places a virtual event on the event queue.
 *
 *----------------------------------------------------------------------
 */

int
TkMacOSXGenerateMenuSelectEvent(
    MenuRef menu,
    MenuItemIndex index)
{
    TkMenu *menuPtr = MenuPtrForMenuRef(menu);
    int item = index - 1;

    if (menuPtr) {
	if (item < 0 || item >= menuPtr->numEntries ||
		(menuPtr->entries[item])->state == ENTRY_DISABLED) {
	    TkActivateMenuEntry(menuPtr, -1);
	} else {
	    TkActivateMenuEntry(menuPtr, item);
	    MenuSelectEvent(menuPtr);
	    Tcl_ServiceAll();
	    return true;
	}
    }
    return false;
}

/*
 *----------------------------------------------------------------------
 *
 * MenuSelectEvent --
 *
 *	Generates a "MenuSelect" virtual event. This can be used to
 *	do context-sensitive menu help.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Places a virtual event on the event queue.
 *
 *----------------------------------------------------------------------
 */

void
MenuSelectEvent(
    TkMenu *menuPtr)		/* the menu we have selected. */
{
    XVirtualEvent event;

    bzero(&event, sizeof(XVirtualEvent));
    event.type = VirtualEvent;
    event.serial = menuPtr->display->request;
    event.send_event = false;
    event.display = menuPtr->display;
    Tk_MakeWindowExist(menuPtr->tkwin);
    event.event = Tk_WindowId(menuPtr->tkwin);
    event.root = XRootWindow(menuPtr->display, 0);
    event.subwindow = None;
    event.time = TkpGetMS();

    XQueryPointer(NULL, None, NULL, NULL, &event.x_root, &event.y_root, NULL,
	    NULL, &event.state);
    event.same_screen = true;
    event.name = Tk_GetUid("MenuSelect");
    Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL);
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXClearActiveMenu --
 *
 *	Clears Tk's active entry for the given MenuRef.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Generates <<MenuSelect>> virtual events.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXClearActiveMenu(
    MenuRef menu)
{
    TkMenu *menuPtr = MenuPtrForMenuRef(menu);

    if (menuPtr) {
	RecursivelyClearActiveMenu(menuPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RecursivelyClearActiveMenu --
 *
 *	Recursively clears the active entry in the menu's cascade hierarchy.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Generates <<MenuSelect>> virtual events.
 *
 *----------------------------------------------------------------------
 */

void
RecursivelyClearActiveMenu(
    TkMenu *menuPtr)		/* The menu to reset. */
{
    int i;
    TkMenuEntry *mePtr;

    TkActivateMenuEntry(menuPtr, -1);
    for (i = 0; i < menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->type == CASCADE_ENTRY) {
	    if ((mePtr->childMenuRefPtr != NULL)
		    && (mePtr->childMenuRefPtr->menuPtr != NULL)) {
		RecursivelyClearActiveMenu(mePtr->childMenuRefPtr->menuPtr);
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXClearMenubarActive --
 *
 *	Recursively clears the active entry in the current menubar hierarchy.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Generates <<MenuSelect>> virtual events.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXClearMenubarActive(void)
{
    TkMenuReferences *menuBarRefPtr;

    if (currentMenuBarName != NULL) {
	menuBarRefPtr = TkFindMenuReferences(currentMenuBarInterp,
		currentMenuBarName);
	if ((menuBarRefPtr != NULL) && (menuBarRefPtr->menuPtr != NULL)) {
	    TkMenu *menuPtr;

	    for (menuPtr = menuBarRefPtr->menuPtr->masterMenuPtr;
		    menuPtr != NULL; menuPtr = menuPtr->nextInstancePtr) {
		if (menuPtr->menuType == MENUBAR) {
		    RecursivelyClearActiveMenu(menuPtr);
		}
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpMenuNotifyToplevelCreate --
 *
 *	This routine reconfigures the menu and the clones indicated by
 *	menuName becuase a toplevel has been created and any system
 *	menus need to be created. Only applicable to Windows.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	An idle handler is set up to do the reconfiguration.
 *
 *----------------------------------------------------------------------
 */

void
TkpMenuNotifyToplevelCreate(
    Tcl_Interp *interp,		/* The interp the menu lives in. */
    char *menuName)		/* The name of the menu to reconfigure. */
{
    /*
     * Nothing to do.
     */
}

/*
 *----------------------------------------------------------------------
 *
 * TkpMenuInit --
 *
 *	Initializes Mac-specific menu data.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Allocates a hash table.
 *
 *----------------------------------------------------------------------
 */

void
TkpMenuInit(void)
{
    MenuSymbol *ms = menuSymbols;
    CFStringRef cfStr;

    lastMenuID = 256;
    Tcl_InitHashTable(&commandTable, TCL_ONE_WORD_KEYS);
    currentMenuBarOwner = NULL;
    currentAppleMenuID = 0;
    currentHelpMenuID = 0;
    currentMenuBarInterp = NULL;
    currentMenuBarName = NULL;
    windowListPtr = NULL;

#ifdef USE_TK_MDEF
    tkThemeMenuItemDrawingUPP
	    = NewMenuItemDrawingUPP(ThemeMenuItemDrawingProc);
    useMDEFVar = Tcl_NewStringObj("::tk::mac::useCustomMDEF", -1);
    macMDEFDrawable.winPtr = NULL;
    macMDEFDrawable.xOff = 0;
    macMDEFDrawable.yOff = 0;
    macMDEFDrawable.visRgn = NULL;
    macMDEFDrawable.aboveVisRgn = NULL;
    macMDEFDrawable.drawRect = CGRectNull;
    macMDEFDrawable.referenceCount = 0;
    macMDEFDrawable.toplevel = NULL;
    macMDEFDrawable.flags = 0;
    macMDEFDrawable.grafPtr = NULL;
    macMDEFDrawable.context = NULL;
#endif

    ChkErr(GetThemeMetric, kThemeMetricMenuMarkColumnWidth,
	    &menuMarkColumnWidth);
    ChkErr(GetThemeMetric, kThemeMetricMenuMarkIndent, &menuMarkIndent);
    ChkErr(GetThemeMetric, kThemeMetricMenuTextLeadingEdgeMargin,
	    &menuTextLeadingEdgeMargin);
    ChkErr(GetThemeMetric, kThemeMetricMenuTextTrailingEdgeMargin,
	    &menuTextTrailingEdgeMargin);
    ChkErr(GetThemeMenuItemExtra, kThemeMenuItemPlain, &menuItemExtraHeight,
	    &menuItemExtraWidth);
    ChkErr(GetThemeMenuSeparatorHeight, &menuSeparatorHeight);

    while (ms->unicode) {
	ms->utfLen = Tcl_UniCharToUtf(ms->unicode, ms->utf);
	ms->utf[ms->utfLen] = 0;
	cfStr = CFStringCreateWithCharacters(NULL, &ms->unicode, 1);
	if (cfStr) {
	    ms->width = MeasureThemeText(cfStr, kThemeMenuItemCmdKeyFont);
	    CFRelease(cfStr);
	}
	ms++;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpMenuThreadInit --
 *
 *	Does platform-specific initialization of thread-specific
 *	menu state.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkpMenuThreadInit(void)
{
    /*
     * Nothing to do.
     */
}

/*
 *----------------------------------------------------------------------
 *
 * TkpPreprocessMacMenu --
 *
 *    Handle preprocessing of menubar if it exists.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    All post commands for the current menubar get executed.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXPreprocessMenu(void)
{
    if ((currentMenuBarName != NULL) && (currentMenuBarInterp != NULL)) {
	TkMenuReferences *mbRefPtr =
		TkFindMenuReferences(currentMenuBarInterp,currentMenuBarName);

	if ((mbRefPtr != NULL) && (mbRefPtr->menuPtr != NULL)) {
	    int code;

	    Tcl_Preserve((ClientData) currentMenuBarInterp);
	    code = TkPreprocessMenu(mbRefPtr->menuPtr->masterMenuPtr);
	    if ((code != TCL_OK) && (code != TCL_CONTINUE)
		    && (code != TCL_BREAK)) {
		Tcl_AddErrorInfo(currentMenuBarInterp,
			"\n    (menu preprocess)");
		Tcl_BackgroundError(currentMenuBarInterp);
	    }
	    Tcl_Release((ClientData) currentMenuBarInterp);
	}
    }
}

#ifdef USE_TK_MDEF
#pragma mark MDEF
/*
 *----------------------------------------------------------------------
 *
 * MenuDefProc --
 *
 *	This routine is the MDEF handler for Tk. It receives all messages
 *	for the menu and dispatches them.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	This routine causes menus to be drawn and will certainly allocate
 *	memory as a result. Also, the menu can scroll up and down, and
 *	various other interface actions can take place.
 *
 *----------------------------------------------------------------------
 */

void
MenuDefProc(
    SInt16 message,		/* What action are we taking? */
    MenuRef menu,		/* The menu we are working with */
    Rect *menuRectPtr,		/* A pointer to the rect for the
				 * whole menu. */
    Point hitPt,		/* Where the mouse was clicked for
				 * the appropriate messages. */
    SInt16 *whichItem)		/* Output result. Which item was
				 * hit by the user? */
{
    TkMenu *menuPtr;
    Tcl_HashEntry *commandEntryPtr;
    MenuID menuID;

    menuID = GetMenuID(menu);
    commandEntryPtr = Tcl_FindHashEntry(&commandTable, (char*)(intptr_t)menuID);

    if (commandEntryPtr) {
	menuPtr = (TkMenu *) Tcl_GetHashValue(commandEntryPtr);
    } else {
	menuPtr = NULL;
    }

    switch (message) {
	case kMenuInitMsg:
	    *whichItem = noErr;
	    break;
	case kMenuDisposeMsg:
	    break;
	case kMenuHiliteItemMsg:
	    HandleMenuHiliteMsg(menu, menuRectPtr, hitPt, whichItem, menuPtr);
	    break;
	case kMenuCalcItemMsg:
	    HandleMenuCalcItemMsg(menu, menuRectPtr, hitPt, whichItem,
		    menuPtr);
	    break;
	case kMenuDrawItemsMsg:
#ifdef TK_MAC_DEBUG_MENUS
	    TkMacOSXDbgMsg("MDEF: DrawItemsMsg");
#endif
	    /*
	     * We do nothing  here, because we don't support the Menu Managers
	     * dynamic item groups
	     */
	    break;
	case kMenuThemeSavvyMsg:
	    *whichItem = kThemeSavvyMenuResponse;
	    break;
	case kMenuSizeMsg:
#ifdef TK_MAC_DEBUG_MENUS
	    TkMacOSXDbgMsg("MDEF: SizeMsg %d, %d", hitPt.h, hitPt.v);
#endif
	    SetMenuWidth(menu, hitPt.h < menuPtr->totalWidth ?	hitPt.h :
		    menuPtr->totalWidth);
	    SetMenuHeight(menu, hitPt.v < menuPtr->totalHeight ? hitPt.v :
		    menuPtr->totalHeight);
	    break;
	case kMenuDrawMsg:
	    HandleMenuDrawMsg(menu, menuRectPtr, hitPt, whichItem, menuPtr);
	    break;
	case kMenuFindItemMsg:
	    HandleMenuFindItemMsg(menu, menuRectPtr, hitPt, whichItem,
		    menuPtr);
	    break;
	case kMenuPopUpMsg:
	    HandleMenuPopUpMsg(menu, menuRectPtr, hitPt, whichItem, menuPtr);
	    break;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * HandleMenuHiliteMsg --
 *
 *	Handles the MenuDefProc's hilite message.
 *
 * Results:
 *	A menu entry is drawn
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

void
HandleMenuHiliteMsg(
    MenuRef menu,
    Rect *menuRectPtr,
    Point hitPt,
    SInt16 *whichItem,
    TkMenu *menuPtr)
{
    OSStatus err;
    Tk_Font tkfont;
    Tk_FontMetrics fontMetrics;
    MDEFHiliteItemData *hidPtr = (MDEFHiliteItemData *)whichItem;
    int oldItem = hidPtr->previousItem - 1;
    int newItem = hidPtr->newItem - 1;
    MenuTrackingData mtd, *mtdPtr = &mtd;

#ifdef TK_MAC_DEBUG_MENUS
    TkMacOSXDbgMsg("MDEF: HiliteMsg %d -> %d", hidPtr->previousItem,
	    hidPtr->newItem);
#endif
    GetPort(&macMDEFDrawable.grafPtr);
    macMDEFDrawable.context = (CGContextRef) hidPtr->context;

    err = ChkErr(GetMenuTrackingData, menu, mtdPtr);
    if (err != noErr) {
	return;
    }

    tkfont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
    Tk_GetFontMetrics(tkfont, &fontMetrics);
    if (oldItem >= 0) {
	AppearanceEntryDrawWrapper(menuPtr->entries[oldItem], menuRectPtr,
		mtdPtr, (Drawable) &macMDEFDrawable, &fontMetrics, tkfont, 1);
    }
    if (newItem >= 0) {
	AppearanceEntryDrawWrapper(menuPtr->entries[newItem], menuRectPtr,
		mtdPtr, (Drawable) &macMDEFDrawable, &fontMetrics, tkfont, 0);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * HandleMenuDrawMsg --
 *
 *	Handles the MenuDefProc's draw message.
 *
 * Results:
 *	A menu entry is drawn
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

void
HandleMenuDrawMsg(
    MenuRef menu,
    Rect *menuRectPtr,
    Point hitPt,
    SInt16 *whichItem,
    TkMenu *menuPtr)
{
    Tk_Font menuFont;
    Tk_FontMetrics fontMetrics;
    TkMenuEntry *mePtr;
    int i;
    Rect menuClipRect, bounds;
    MDEFDrawData *ddPtr = (MDEFDrawData*)whichItem;
    MenuTrackingData *mtdPtr = &(ddPtr->trackingData);
    TkWindow *winPtr = (TkWindow*)menuPtr->tkwin;

    GetPort(&macMDEFDrawable.grafPtr);
    GetPortBounds(macMDEFDrawable.grafPtr, &bounds);
    macMDEFDrawable.context = (CGContextRef) ddPtr->context;
#ifdef TK_MAC_DEBUG_MENUS
    TkMacOSXDbgMsg("MDEF: DrawMsg %d - %d; %d - %d", menuRectPtr->top,
	    menuRectPtr->bottom, bounds.top, bounds.bottom);
#endif
    winPtr->changes.x = menuRectPtr->left;
    winPtr->changes.y = menuRectPtr->top;
    winPtr->changes.width = menuRectPtr->right - menuRectPtr->left;
    winPtr->changes.height = menuRectPtr->bottom - menuRectPtr->top;
    TkpClipDrawableToRect(menuPtr->display, (Drawable) &macMDEFDrawable,
	    0, 0, -1, -1);
#if 0
    if (menuPtr->menuRefPtr->topLevelListPtr != NULL) {
	menuType = kThemeMenuTypePullDown;
    } else if (menuPtr->menuRefPtr->parentEntryPtr != NULL) {
	menuType = kThemeMenuTypeHierarchical;
    } else {
	menuType = kThemeMenuTypePopUp;
    }
#endif
    DrawMenuBackground(menuPtr, menuRectPtr, (Drawable) &macMDEFDrawable);
    menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
    Tk_GetFontMetrics(menuFont, &fontMetrics);
    menuClipRect = *menuRectPtr;
    mtdPtr->virtualMenuBottom = mtdPtr->virtualMenuTop + menuPtr->totalHeight;

    /*
     * Next, figure out scrolling information.
     */

    if ((menuRectPtr->bottom - menuRectPtr->top) < menuPtr->totalHeight) {
	short arrowHeight = fontMetrics.linespace + 1;
	Rect arrowRect, eraseRect;
	ThemeMenuState menuState = IsMenuItemEnabled(menu, 0) ?
		kThemeMenuActive : kThemeMenuDisabled;

	if (mtdPtr->virtualMenuTop < menuRectPtr->top) {
	    arrowRect = bounds;
	    /*arrowRect.top += 1;*/
	    arrowRect.bottom = arrowRect.top + arrowHeight;
	    eraseRect = arrowRect;
	    eraseRect.top = menuRectPtr->top;
	    menuClipRect.top = arrowRect.bottom;
	    ChkErr(EraseMenuBackground, menu, &eraseRect,
		    macMDEFDrawable.context);
	    ChkErr(DrawThemeMenuItem, menuRectPtr, &arrowRect,
		    mtdPtr->virtualMenuTop, mtdPtr->virtualMenuBottom,
		    menuState, kThemeMenuItemScrollUpArrow, NULL, 0);
#ifdef TK_MAC_DEBUG_MENUS
	    TkMacOSXDbgMsg("upArrow:   %d - %d, %d - %d", arrowRect.top,
		    arrowRect.bottom, arrowRect.left, arrowRect.right);
#endif
	}
	if (mtdPtr->virtualMenuBottom > menuRectPtr->bottom) {
	    arrowRect = bounds;
	    arrowRect.bottom -= 1;
	    arrowRect.top = arrowRect.bottom - arrowHeight;
	    eraseRect = arrowRect;
	    eraseRect.bottom = menuRectPtr->bottom;
	    menuClipRect.bottom = arrowRect.top;
	    ChkErr(EraseMenuBackground, menu, &eraseRect,
		    macMDEFDrawable.context);
	    ChkErr(DrawThemeMenuItem, menuRectPtr, &arrowRect,
		    mtdPtr->virtualMenuTop, mtdPtr->virtualMenuBottom,
		    menuState, kThemeMenuItemScrollDownArrow, NULL, 0);
#ifdef TK_MAC_DEBUG_MENUS
	    TkMacOSXDbgMsg("downArrow: %d - %d, %d - %d", arrowRect.top,
		    arrowRect.bottom, arrowRect.left, arrowRect.right);
#endif
	}
	TkpClipDrawableToRect(menuPtr->display, (Drawable) &macMDEFDrawable,
		menuClipRect.left, menuClipRect.top, menuClipRect.right -
		menuClipRect.left, menuClipRect.bottom - menuClipRect.top);
    }

    /*
     * Now, actually draw the menu. Don't draw entries that
     * are higher than the top arrow, and don't draw entries
     * that are lower than the bottom.
     */

    for (i = 0; i < menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mtdPtr->virtualMenuTop + mePtr->y + mePtr->height <
		menuClipRect.top || mtdPtr->virtualMenuTop + mePtr->y >
		menuClipRect.bottom) {
	    continue;
	}
	AppearanceEntryDrawWrapper(mePtr, menuRectPtr, mtdPtr,
		(Drawable) &macMDEFDrawable, &fontMetrics, menuFont, 0);
    }
    MDEFScrollFlag = 1;
}

/*
 *----------------------------------------------------------------------
 *
 * HandleMenuFindItemMsg --
 *
 *	Handles the MenuDefProc's FindItems message. We have to
 *	respond by filling in the itemSelected, itemUnderMouse and
 *	itemRect fields. This is also the time to scroll the menu if
 *	it is too long to fit on the screen.
 *
 * Results:
 *	The Menu system is informed of the selected item & the item
 *	under the mouse.
 *
 * Side effects:
 *	The menu might get scrolled.
 *
 *----------------------------------------------------------------------
 */
void
HandleMenuFindItemMsg(
    MenuRef menu,
    Rect *menuRectPtr,
    Point hitPt,
    SInt16 *whichItem,
    TkMenu *menuPtr)
{
    Tk_Font menuFont;
    Tk_FontMetrics fontMetrics;
    TkMenuEntry *mePtr;
    int i, newItem = -1, itemUnderMouse = -1;
    Rect itemRect = {0, 0, 0, 0}, menuClipRect, bounds;
    int hasTopScroll, hasBottomScroll;
    MDEFFindItemData *fiPtr = (MDEFFindItemData *)whichItem;
    MenuTrackingData *mtdPtr = &(fiPtr->trackingData), topMtd;
    enum {
	DONT_SCROLL, DOWN_SCROLL, UP_SCROLL
    } scrollDirection;
    short arrowHeight;

#ifdef TK_MAC_DEBUG_MENUS
    static Point lastHitPt = {0, 0};
    if (hitPt.h != lastHitPt.h || hitPt.v != lastHitPt.v) {
	lastHitPt = hitPt;
	TkMacOSXDbgMsg("MDEF: FindItemMsg: %d, %d", hitPt.h, hitPt.v);
    }
#endif

    GetPort(&macMDEFDrawable.grafPtr);
    GetPortBounds(macMDEFDrawable.grafPtr, &bounds);
    macMDEFDrawable.context = (CGContextRef) fiPtr->context;

    /*
     * Now we need to take care of scrolling the menu.
     */

    menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
    Tk_GetFontMetrics(menuFont, &fontMetrics);
    arrowHeight = fontMetrics.linespace + 1;
    menuClipRect = *menuRectPtr;
    hasTopScroll = mtdPtr->virtualMenuTop < menuRectPtr->top;
    hasBottomScroll = mtdPtr->virtualMenuBottom > menuRectPtr->bottom;
    scrollDirection = DONT_SCROLL;
    if (hasTopScroll) {
	menuClipRect.top = bounds.top + arrowHeight;
	if (hitPt.v < menuClipRect.top) {
	    newItem = -1;
	    scrollDirection = DOWN_SCROLL;
	}
    }
    if (hasBottomScroll) {
	menuClipRect.bottom = bounds.bottom - 1 - arrowHeight;
	if (hitPt.v > menuClipRect.bottom) {
	    newItem = -1;
	    scrollDirection = UP_SCROLL;
	}
    }
    if (MDEFScrollFlag) {
	scrollDirection = DONT_SCROLL;
	MDEFScrollFlag = 0;
    }
    /*
     * Don't scroll if there are other menus open above us
     */
    ChkErr(GetMenuTrackingData, NULL, &topMtd);
    if (menu != topMtd.menu) {
	scrollDirection = DONT_SCROLL;
    }
    if (scrollDirection == DONT_SCROLL) {
	/*
	 * Find out which item was hit. If it is the same as the old item,
	 * we don't need to do anything.
	 */

	if (PtInRect(hitPt, menuRectPtr)) {
	    for (i = 0; i < menuPtr->numEntries; i++) {
		mePtr = menuPtr->entries[i];
		itemRect.left = menuRectPtr->left + mePtr->x;
		itemRect.top = mtdPtr->virtualMenuTop + mePtr->y;
		itemRect.right = mePtr->entryFlags & ENTRY_LAST_COLUMN ?
			menuRectPtr->right : itemRect.left + mePtr->width;
		itemRect.bottom = itemRect.top + mePtr->height;
		if (PtInRect(hitPt, &itemRect)) {
		    if ((mePtr->type == SEPARATOR_ENTRY)
			    || (mePtr->state == ENTRY_DISABLED)) {
			newItem = -1;
			itemUnderMouse = i;
		    } else {
			TkMenuEntry *parentEntryPtr =
				GetParentMenuEntry(menuPtr);

			if (parentEntryPtr &&
				parentEntryPtr->state == ENTRY_DISABLED) {
			    newItem = -1;
			    itemUnderMouse = i;
			} else {
			    newItem = i;
			    itemUnderMouse = i;
			}
		    }
		    break;
		}
	    }
	}
    } else {
	short scrollAmt;
	unsigned long scrollDelay;
	Rect arrowRect, eraseRect, scrolledMenuClipRect;
	ThemeMenuState menuState = IsMenuItemEnabled(menu, 0) ?
		kThemeMenuActive : kThemeMenuDisabled;
	int oldItem = mtdPtr->itemSelected - 1;
	short d;

	TkpClipDrawableToRect(menuPtr->display, (Drawable) &macMDEFDrawable,
		0, 0, -1, -1);
	scrollAmt = fontMetrics.linespace + menuItemExtraHeight;
	if (scrollDirection == UP_SCROLL) {
	    scrollAmt = -scrollAmt;
	    d = hitPt.v - bounds.bottom;
	} else {
	    d = bounds.top - hitPt.v;
	}
	scrollDelay = (d >= scrollAmt/2) ? 1 : 10;
	menuClipRect = *menuRectPtr;
	if (mtdPtr->virtualMenuTop + scrollAmt < menuRectPtr->top) {
	    arrowRect = bounds;
	    /*arrowRect.top += 1;*/
	    arrowRect.bottom = arrowRect.top + arrowHeight;
	    eraseRect = arrowRect;
	    eraseRect.top = menuRectPtr->top;
	    menuClipRect.top = arrowRect.bottom;
	    if (!hasTopScroll) {
		ChkErr(EraseMenuBackground, menu, &eraseRect,
			macMDEFDrawable.context);
		ChkErr(DrawThemeMenuItem, menuRectPtr, &arrowRect,
			mtdPtr->virtualMenuTop + scrollAmt,
			mtdPtr->virtualMenuBottom + scrollAmt,
			menuState, kThemeMenuItemScrollUpArrow, NULL, 0);
#ifdef TK_MAC_DEBUG_MENUS
		TkMacOSXDbgMsg("upArrow:   %d - %d, %d - %d", arrowRect.top,
			arrowRect.bottom, arrowRect.left, arrowRect.right);
#endif
	    }
	}
	if (mtdPtr->virtualMenuBottom + scrollAmt > menuRectPtr->bottom) {
	    arrowRect = bounds;
	    arrowRect.bottom -= 1;
	    arrowRect.top = arrowRect.bottom - arrowHeight;
	    eraseRect = arrowRect;
	    eraseRect.bottom = menuRectPtr->bottom;
	    menuClipRect.bottom = arrowRect.top;
	    if (!hasBottomScroll) {
		ChkErr(EraseMenuBackground, menu, &eraseRect,
			macMDEFDrawable.context);
		ChkErr(DrawThemeMenuItem, menuRectPtr, &arrowRect,
			mtdPtr->virtualMenuTop + scrollAmt,
			mtdPtr->virtualMenuBottom + scrollAmt,
			menuState, kThemeMenuItemScrollDownArrow, NULL, 0);
#ifdef TK_MAC_DEBUG_MENUS
		TkMacOSXDbgMsg("downArrow: %d - %d, %d - %d", arrowRect.top,
			arrowRect.bottom, arrowRect.left, arrowRect.right);
#endif
	    }
	}
	TkpClipDrawableToRect(menuPtr->display, (Drawable) &macMDEFDrawable,
		menuClipRect.left, menuClipRect.top, menuClipRect.right -
		menuClipRect.left, menuClipRect.bottom - menuClipRect.top);
	TkActivateMenuEntry(menuPtr, -1);
	if (oldItem >= 0) {
	    AppearanceEntryDrawWrapper(menuPtr->entries[oldItem], menuRectPtr,
		    mtdPtr, (Drawable) &macMDEFDrawable, &fontMetrics,
		    menuFont, 1);
	}
	ChkErr(ScrollMenuImage, menu, &menuClipRect, 0, scrollAmt,
		macMDEFDrawable.context);
	mtdPtr->virtualMenuTop += scrollAmt;
	mtdPtr->virtualMenuBottom += scrollAmt;
	scrolledMenuClipRect = menuClipRect;
	OffsetRect(&scrolledMenuClipRect, 0, scrollAmt);
	menuClipRect = bounds;
	if (mtdPtr->virtualMenuTop < menuRectPtr->top) {
	    menuClipRect.top += arrowHeight;
	}
	if (mtdPtr->virtualMenuBottom > menuRectPtr->bottom) {
	    menuClipRect.bottom -= arrowHeight;
	}
	TkpClipDrawableToRect(menuPtr->display, (Drawable) &macMDEFDrawable,
		menuClipRect.left, menuClipRect.top, menuClipRect.right -
		menuClipRect.left, menuClipRect.bottom - menuClipRect.top);
	if (scrolledMenuClipRect.bottom < menuClipRect.bottom) {
	    menuClipRect.top = scrolledMenuClipRect.bottom;
	} else if (scrolledMenuClipRect.top < menuClipRect.top) {
	    menuClipRect.bottom = scrolledMenuClipRect.top;
	}
	for (i = 0; i < menuPtr->numEntries; i++) {
	    mePtr = menuPtr->entries[i];
	    if (mtdPtr->virtualMenuTop + mePtr->y + mePtr->height <
		    menuClipRect.top || mtdPtr->virtualMenuTop + mePtr->y >
		    menuClipRect.bottom) {
		continue;
	    }
#ifdef TK_MAC_DEBUG_MENUS
	    TkMacOSXDbgMsg("Drawing item %i", i);
#endif
	    AppearanceEntryDrawWrapper(mePtr, menuRectPtr, mtdPtr,
		    (Drawable) &macMDEFDrawable, &fontMetrics, menuFont, 1);
	}
	Delay(scrollDelay, NULL);
    }
    mtdPtr->itemSelected = newItem + 1;
    mtdPtr->itemUnderMouse = itemUnderMouse + 1;
    mtdPtr->itemRect = itemRect;
}

/*
 *----------------------------------------------------------------------
 *
 * HandleMenuPopUpMsg --
 *
 *	Handles the MenuDefProc's PopUp message. The menu is
 *	posted with the selected item at the point given in hitPt.
 *
 * Results:
 *	A menu is posted.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
void
HandleMenuPopUpMsg(
    MenuRef menu,
    Rect *menuRectPtr,
    Point hitPt,
    SInt16 *whichItem,
    TkMenu *menuPtr)
{
    int maxMenuHeight;
    int oldItem;
    Rect portRect;
    BitMap screenBits;
    static SInt16 menuBarHeight = 0;

#ifdef TK_MAC_DEBUG_MENUS
    TkMacOSXDbgMsg("MDEF: PopUpMsg");
#endif

    if (!menuBarHeight) {
	ChkErr(GetThemeMenuBarHeight, &menuBarHeight);
    }
    GetQDGlobalsScreenBits(&screenBits);

    /*
     * Note that for some oddball reason, h and v are reversed in the
     * point given to us by the MDEF.
     */

    oldItem = *whichItem;
    if (oldItem >= menuPtr->numEntries) {
	oldItem = -1;
    }
    portRect.top = 0;
    portRect.bottom = 1280;
    maxMenuHeight = screenBits.bounds.bottom - screenBits.bounds.top
	    - menuBarHeight - SCREEN_MARGIN;
    if (menuPtr->totalHeight > maxMenuHeight) {
	menuRectPtr->top = menuBarHeight;
    } else {
	int delta;

	menuRectPtr->top = hitPt.h;
	if (oldItem >= 0) {
	    menuRectPtr->top -= menuPtr->entries[oldItem]->y;
	}

	if (menuRectPtr->top < menuBarHeight) {
	    /*
	     * Displace downward if the menu would stick off the top of the
	     * screen.
	     */

	    menuRectPtr->top = menuBarHeight + SCREEN_MARGIN;
	} else {
	    /*
	     * Or upward if the menu sticks off the bottom end...
	     */

	    delta = menuRectPtr->top + menuPtr->totalHeight - maxMenuHeight;
	    if (delta > 0) {
		menuRectPtr->top -= delta;
	    }
	}
    }
    menuRectPtr->left = hitPt.v;
    menuRectPtr->right = menuRectPtr->left + menuPtr->totalWidth;
    menuRectPtr->bottom = menuRectPtr->top +
	    ((maxMenuHeight < menuPtr->totalHeight)
	    ? maxMenuHeight : menuPtr->totalHeight);
    if (menuRectPtr->top == menuBarHeight) {
	*whichItem = hitPt.h;
    } else {
	*whichItem = menuRectPtr->top;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * HandleMenuCalcItemMsg --
 *
 *	Handles the MenuDefProc's CalcItem message. It is supposed
 *	to calculate the Rect of the menu entry in whichItem in the
 *	menu, and put that in menuRectPtr. I assume this works, but I
 *	have never seen the MenuManager send this message.
 *
 * Results:
 *	The Menu Manager is informed of the bounding rect of a
 *	menu rect.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
HandleMenuCalcItemMsg(
    MenuRef menu,
    Rect *menuRectPtr,
    Point hitPt,
    SInt16 *whichItem,
    TkMenu *menuPtr)
{
    TkMenuEntry *mePtr;
    MenuTrackingData mtd, *mtdPtr = &mtd;
    OSStatus err;
    int virtualTop, item = *whichItem-1;

    err = ChkErr(GetMenuTrackingData, menu, mtdPtr);
    if (err == noErr) {
	virtualTop = mtdPtr->virtualMenuTop;
    } else {
	virtualTop = 0;
    }

    if (item >= 0 && item < menuPtr->numEntries) {
	mePtr = menuPtr->entries[item];
	menuRectPtr->left = mePtr->x;
	menuRectPtr->top = mePtr->y + virtualTop;
	if (mePtr->entryFlags & ENTRY_LAST_COLUMN) {
	    menuRectPtr->right = menuPtr->totalWidth;
	} else {
	    menuRectPtr->right = mePtr->x + mePtr->width;
	}
	menuRectPtr->bottom = menuRectPtr->top + mePtr->height;
    }
#ifdef TK_MAC_DEBUG_MENUS
    TkMacOSXDbgMsg("MDEF: CalcItemMsg %d: %d, %d", *whichItem,
	    menuRectPtr->left, menuRectPtr->top);
#endif
}
#endif /* USE_TK_MDEF */